qlogicagent 2.24.5 → 2.24.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -1,73 +1,74 @@
1
- var Sg=Object.create;var Dl=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var $g=Object.getPrototypeOf,Pg=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Mg=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ag(t))!Pg.call(e,r)&&r!==n&&Dl(e,r,{get:()=>t[r],enumerable:!(o=Eg(t,r))||o.enumerable});return e};var Ig=(e,t,n)=>(n=e!=null?Sg($g(e)):{},Mg(t||!e||!e.__esModule?Dl(n,"default",{value:e,enumerable:!0}):n,e));var Qn=w(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 Yn=class{};W._CodeOrName=Yn;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Bt=class extends Yn{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=Bt;var qe=class extends Yn{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 Bt&&(n[o.str]=(n[o.str]||0)+1),n),{})}};W._Code=qe;W.nil=new qe("");function ku(e,...t){let n=[e[0]],o=0;for(;o<t.length;)ci(n,t[o]),n.push(e[++o]);return new qe(n)}W._=ku;var ai=new qe("+");function Cu(e,...t){let n=[Zn(e[0])],o=0;for(;o<t.length;)n.push(ai),ci(n,t[o]),n.push(ai,Zn(e[++o]));return Hh(n),new qe(n)}W.str=Cu;function ci(e,t){t instanceof qe?e.push(...t._items):t instanceof Bt?e.push(t):e.push(Wh(t))}W.addCodeArg=ci;function Hh(e){let t=1;for(;t<e.length-1;){if(e[t]===ai){let n=Vh(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function Vh(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Bt||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 Bt))return`"${e}${t.slice(1)}`}function Gh(e,t){return t.emptyStr()?e:e.emptyStr()?t:Cu`${e}${t}`}W.strConcat=Gh;function Wh(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Zn(Array.isArray(e)?e.join(","):e)}function Kh(e){return new qe(Zn(e))}W.stringify=Kh;function Zn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=Zn;function Jh(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new qe(`.${e}`):ku`[${e}]`}W.getProperty=Jh;function Xh(e){if(typeof e=="string"&&W.IDENTIFIER.test(e))return new qe(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}W.getEsmExportName=Xh;function Yh(e){return new qe(e.toString())}W.regexpCode=Yh});var di=w(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.ValueScope=Ae.ValueScopeName=Ae.Scope=Ae.varKinds=Ae.UsedValueState=void 0;var Ee=Qn(),li=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},rr;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(rr||(Ae.UsedValueState=rr={}));Ae.varKinds={const:new Ee.Name("const"),let:new Ee.Name("let"),var:new Ee.Name("var")};var sr=class{constructor({prefixes:t,parent:n}={}){this._names={},this._prefixes=t,this._parent=n}toName(t){return t instanceof Ee.Name?t:this.name(t)}name(t){return new Ee.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}}};Ae.Scope=sr;var ir=class extends Ee.Name{constructor(t,n){super(n),this.prefix=t}setValue(t,{property:n,itemIndex:o}){this.value=t,this.scopePath=(0,Ee._)`.${new Ee.Name(n)}[${o}]`}};Ae.ValueScopeName=ir;var Zh=(0,Ee._)`\n`,ui=class extends sr{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Zh:Ee.nil}}get(){return this._scope}name(t){return new ir(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,Ee._)`${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=Ee.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,rr.Started);let d=n(l);if(d){let p=this.opts.es5?Ae.varKinds.var:Ae.varKinds.const;s=(0,Ee._)`${s}${p} ${l} = ${d};${this.opts._n}`}else if(d=r?.(l))s=(0,Ee._)`${s}${d}${this.opts._n}`;else throw new li(l);c.set(l,rr.Completed)})}return s}};Ae.ValueScope=ui});var F=w(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=Qn(),Ye=di(),vt=Qn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return vt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return vt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return vt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return vt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return vt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return vt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return vt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return vt.Name}});var ur=di();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return ur.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return ur.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return ur.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return ur.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 dt=class{optimizeNodes(){return this}optimizeNames(t,n){return this}},fi=class extends dt{constructor(t,n,o){super(),this.varKind=t,this.name=n,this.rhs=o}render({es5:t,_n:n}){let o=t?Ye.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=gn(this.rhs,t,n)),this}get names(){return this.rhs instanceof V._CodeOrName?this.rhs.names:{}}},ar=class extends dt{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=gn(this.rhs,t,n),this}get names(){let t=this.lhs instanceof V.Name?{}:{...this.lhs.names};return lr(t,this.rhs)}},pi=class extends ar{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 dt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},gi=class extends dt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},hi=class extends dt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},yi=class extends dt{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=gn(this.code,t,n),this}get names(){return this.code instanceof V._CodeOrName?this.code.names:{}}},eo=class extends dt{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)||(Qh(t,s.names),o.splice(r,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((t,n)=>zt(t,n.names),{})}},ft=class extends eo{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},bi=class extends eo{},mn=class extends ft{};mn.kind="else";var qt=class e extends ft{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 mn(o):o}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(wu(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=gn(this.condition,t,n),this}get names(){let t=super.names;return lr(t,this.condition),this.else&&zt(t,this.else.names),t}};qt.kind="if";var Ut=class extends ft{};Ut.kind="for";var _i=class extends Ut{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=gn(this.iteration,t,n),this}get names(){return zt(super.names,this.iteration.names)}},vi=class extends Ut{constructor(t,n,o,r){super(),this.varKind=t,this.name=n,this.from=o,this.to=r}render(t){let n=t.es5?Ye.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=lr(super.names,this.from);return lr(t,this.to)}},cr=class extends Ut{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=gn(this.iterable,t,n),this}get names(){return zt(super.names,this.iterable.names)}},to=class extends ft{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)}};to.kind="func";var no=class extends eo{render(t){return"return "+super.render(t)}};no.kind="return";var Ti=class extends ft{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&&zt(t,this.catch.names),this.finally&&zt(t,this.finally.names),t}},oo=class extends ft{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};oo.kind="catch";var ro=class extends ft{render(t){return"finally"+super.render(t)}};ro.kind="finally";var ki=class{constructor(t,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
2
- `:""},this._extScope=t,this._scope=new Ye.Scope({parent:t}),this._nodes=[new bi]}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 fi(t,s,o)),s}const(t,n,o){return this._def(Ye.varKinds.const,t,n,o)}let(t,n,o){return this._def(Ye.varKinds.let,t,n,o)}var(t,n,o){return this._def(Ye.varKinds.var,t,n,o)}assign(t,n,o){return this._leafNode(new ar(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 yi(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 qt(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 qt(t))}else(){return this._elseNode(new mn)}endIf(){return this._endBlockNode(qt,mn)}_for(t,n){return this._blockNode(t),n&&this.code(n).endFor(),this}for(t,n){return this._for(new _i(t),n)}forRange(t,n,o,r,s=this.opts.es5?Ye.varKinds.var:Ye.varKinds.let){let i=this._scope.toName(t);return this._for(new vi(s,i,n,o),()=>r(i))}forOf(t,n,o,r=Ye.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 cr("of",r,s,n),()=>o(s))}forIn(t,n,o,r=this.opts.es5?Ye.varKinds.var:Ye.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 cr("in",r,s,n),()=>o(s))}endFor(){return this._endBlockNode(Ut)}label(t){return this._leafNode(new mi(t))}break(t){return this._leafNode(new gi(t))}return(t){let n=new no;if(this._blockNode(n),this.code(t),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(no)}try(t,n,o){if(!n&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let r=new Ti;if(this._blockNode(r),this.code(t),n){let s=this.name("e");this._currNode=r.catch=new oo(s),n(s)}return o&&(this._currNode=r.finally=new ro,this.code(o)),this._endBlockNode(oo,ro)}throw(t){return this._leafNode(new hi(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 to(t,n,o)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(to)}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 qt))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=ki;function zt(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function lr(e,t){return t instanceof V._CodeOrName?zt(e,t.names):e}function gn(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 Qh(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function wu(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,V._)`!${Ci(e)}`}D.not=wu;var ey=Ru(D.operators.AND);function ty(...e){return e.reduce(ey)}D.and=ty;var ny=Ru(D.operators.OR);function oy(...e){return e.reduce(ny)}D.or=oy;function Ru(e){return(t,n)=>t===V.nil?n:n===V.nil?t:(0,V._)`${Ci(t)} ${e} ${Ci(n)}`}function Ci(e){return e instanceof V.Name?e:(0,V._)`(${e})`}});var q=w(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.checkStrictMode=B.getErrorPath=B.Type=B.useFunc=B.setEvaluated=B.evaluatedPropsToName=B.mergeEvaluated=B.eachItem=B.unescapeJsonPointer=B.escapeJsonPointer=B.escapeFragment=B.unescapeFragment=B.schemaRefOrVal=B.schemaHasRulesButRef=B.schemaHasRules=B.checkUnknownRules=B.alwaysValidSchema=B.toHash=void 0;var Z=F(),ry=Qn();function sy(e){let t={};for(let n of e)t[n]=!0;return t}B.toHash=sy;function iy(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Eu(e,t),!Au(t,e.self.RULES.all))}B.alwaysValidSchema=iy;function Eu(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]||Mu(e,`unknown keyword: "${s}"`)}B.checkUnknownRules=Eu;function Au(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}B.schemaHasRules=Au;function ay(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}B.schemaHasRulesButRef=ay;function cy({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)}`}B.schemaRefOrVal=cy;function ly(e){return $u(decodeURIComponent(e))}B.unescapeFragment=ly;function uy(e){return encodeURIComponent(Ri(e))}B.escapeFragment=uy;function Ri(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}B.escapeJsonPointer=Ri;function $u(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}B.unescapeJsonPointer=$u;function dy(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}B.eachItem=dy;function xu({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}}B.mergeEvaluated={props:xu({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} || {}`),xi(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Pu}),items:xu({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 Pu(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",(0,Z._)`{}`);return t!==void 0&&xi(e,n,t),n}B.evaluatedPropsToName=Pu;function xi(e,t,n){Object.keys(n).forEach(o=>e.assign((0,Z._)`${t}${(0,Z.getProperty)(o)}`,!0))}B.setEvaluated=xi;var Su={};function fy(e,t){return e.scopeValue("func",{ref:t,code:Su[t.code]||(Su[t.code]=new ry._Code(t.code))})}B.useFunc=fy;var wi;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(wi||(B.Type=wi={}));function py(e,t,n){if(e instanceof Z.Name){let o=t===wi.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():"/"+Ri(e)}B.getErrorPath=py;function Mu(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}B.checkStrictMode=Mu});var Ue=w(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});var be=F(),my={data:new be.Name("data"),valCxt:new be.Name("valCxt"),instancePath:new be.Name("instancePath"),parentData:new be.Name("parentData"),parentDataProperty:new be.Name("parentDataProperty"),rootData:new be.Name("rootData"),dynamicAnchors:new be.Name("dynamicAnchors"),vErrors:new be.Name("vErrors"),errors:new be.Name("errors"),this:new be.Name("this"),self:new be.Name("self"),scope:new be.Name("scope"),json:new be.Name("json"),jsonPos:new be.Name("jsonPos"),jsonLen:new be.Name("jsonLen"),jsonPart:new be.Name("jsonPart")};Si.default=my});var so=w(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.extendErrors=_e.resetErrorsCount=_e.reportExtraError=_e.reportError=_e.keyword$DataError=_e.keywordError=void 0;var G=F(),dr=q(),Re=Ue();_e.keywordError={message:({keyword:e})=>(0,G.str)`must pass "${e}" keyword validation`};_e.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 gy(e,t=_e.keywordError,n,o){let{it:r}=e,{gen:s,compositeRule:i,allErrors:a}=r,c=Nu(e,t,n);o??(i||a)?Iu(s,c):Ou(r,(0,G._)`[${c}]`)}_e.reportError=gy;function hy(e,t=_e.keywordError,n){let{it:o}=e,{gen:r,compositeRule:s,allErrors:i}=o,a=Nu(e,t,n);Iu(r,a),s||i||Ou(o,Re.default.vErrors)}_e.reportExtraError=hy;function yy(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)))}_e.resetErrorsCount=yy;function by({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))})}_e.extendErrors=by;function Iu(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 Ou(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 Ht={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 Nu(e,t,n){let{createErrors:o}=e.it;return o===!1?(0,G._)`{}`:_y(e,t,n)}function _y(e,t,n={}){let{gen:o,it:r}=e,s=[vy(r,n),Ty(e,n)];return ky(e,t,s),o.object(...s)}function vy({errorPath:e},{instancePath:t}){let n=t?(0,G.str)`${e}${(0,dr.getErrorPath)(t,dr.Type.Str)}`:e;return[Re.default.instancePath,(0,G.strConcat)(Re.default.instancePath,n)]}function Ty({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,dr.getErrorPath)(n,dr.Type.Str)}`),[Ht.schemaPath,r]}function ky(e,{params:t,message:n},o){let{keyword:r,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:p}=a;o.push([Ht.keyword,r],[Ht.params,typeof t=="function"?t(e):t||(0,G._)`{}`]),c.messages&&o.push([Ht.message,typeof n=="function"?n(e):n]),c.verbose&&o.push([Ht.schema,i],[Ht.parentSchema,(0,G._)`${d}${p}`],[Re.default.data,s]),l&&o.push([Ht.propertyName,l])}});var Lu=w(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.boolOrEmptySchema=hn.topBoolOrEmptySchema=void 0;var Cy=so(),wy=F(),Ry=Ue(),xy={message:"boolean schema is false"};function Sy(e){let{gen:t,schema:n,validateName:o}=e;n===!1?Fu(e,!1):typeof n=="object"&&n.$async===!0?t.return(Ry.default.data):(t.assign((0,wy._)`${o}.errors`,null),t.return(!0))}hn.topBoolOrEmptySchema=Sy;function Ey(e,t){let{gen:n,schema:o}=e;o===!1?(n.var(t,!1),Fu(e)):n.var(t,!0)}hn.boolOrEmptySchema=Ey;function Fu(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,Cy.reportError)(r,xy,void 0,t)}});var Ei=w(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.getRules=yn.isJSONType=void 0;var Ay=["string","number","integer","boolean","null","object","array"],$y=new Set(Ay);function Py(e){return typeof e=="string"&&$y.has(e)}yn.isJSONType=Py;function My(){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:{}}}yn.getRules=My});var Ai=w(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.shouldUseRule=Tt.shouldUseGroup=Tt.schemaHasRulesForType=void 0;function Iy({schema:e,self:t},n){let o=t.RULES.types[n];return o&&o!==!0&&ju(e,o)}Tt.schemaHasRulesForType=Iy;function ju(e,t){return t.rules.some(n=>Du(e,n))}Tt.shouldUseGroup=ju;function Du(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))}Tt.shouldUseRule=Du});var io=w(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.reportTypeError=ve.checkDataTypes=ve.checkDataType=ve.coerceAndCheckDataType=ve.getJSONTypes=ve.getSchemaTypes=ve.DataType=void 0;var Oy=Ei(),Ny=Ai(),Fy=so(),L=F(),Bu=q(),bn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(bn||(ve.DataType=bn={}));function Ly(e){let t=qu(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}ve.getSchemaTypes=Ly;function qu(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Oy.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ve.getJSONTypes=qu;function jy(e,t){let{gen:n,data:o,opts:r}=e,s=Dy(t,r.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Ny.schemaHasRulesForType)(e,t[0]));if(i){let a=Pi(t,o,r.strictNumbers,bn.Wrong);n.if(a,()=>{s.length?By(e,t,s):Mi(e)})}return i}ve.coerceAndCheckDataType=jy;var Uu=new Set(["string","number","integer","boolean","null"]);function Dy(e,t){return t?e.filter(n=>Uu.has(n)||t==="array"&&n==="array"):[]}function By(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(Pi(t,r,s.strictNumbers),()=>o.assign(a,r))),o.if((0,L._)`${a} !== undefined`);for(let l of n)(Uu.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);o.else(),Mi(e),o.endIf(),o.if((0,L._)`${a} !== undefined`,()=>{o.assign(r,a),qy(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
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
3
  || (${i} == "string" && ${r} && ${r} == +${r})`).assign(a,(0,L._)`+${r}`);return;case"integer":o.elseIf((0,L._)`${i} === "boolean" || ${r} === null
4
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 qy({gen:e,parentData:t,parentDataProperty:n},o){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${n}]`,o))}function $i(e,t,n,o=bn.Correct){let r=o===bn.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===bn.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)}}ve.checkDataType=$i;function Pi(e,t,n,o){if(e.length===1)return $i(e[0],t,n,o);let r,s=(0,Bu.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,$i(i,t,n,o));return r}ve.checkDataTypes=Pi;var Uy={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function Mi(e){let t=zy(e);(0,Fy.reportError)(t,Uy)}ve.reportTypeError=Mi;function zy(e){let{gen:t,data:n,schema:o}=e,r=(0,Bu.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:n,schema:o.type,schemaCode:r,schemaValue:r,parentSchema:o,params:{},it:e}}});var Hu=w(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.assignDefaults=void 0;var _n=F(),Hy=q();function Vy(e,t){let{properties:n,items:o}=e.schema;if(t==="object"&&n)for(let r in n)zu(e,r,n[r].default);else t==="array"&&Array.isArray(o)&&o.forEach((r,s)=>zu(e,s,r.default))}fr.assignDefaults=Vy;function zu(e,t,n){let{gen:o,compositeRule:r,data:s,opts:i}=e;if(n===void 0)return;let a=(0,_n._)`${s}${(0,_n.getProperty)(t)}`;if(r){(0,Hy.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,_n._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,_n._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,_n._)`${a} = ${(0,_n.stringify)(n)}`)}});var ze=w(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(),Ii=q(),kt=Ue(),Gy=q();function Wy(e,t){let{gen:n,data:o,it:r}=e;n.if(Ni(n,o,t,r.opts.ownProperties),()=>{e.setParams({missingProperty:(0,te._)`${t}`},!0),e.error()})}X.checkReportMissingProp=Wy;function Ky({gen:e,data:t,it:{opts:n}},o,r){return(0,te.or)(...o.map(s=>(0,te.and)(Ni(e,t,s,n.ownProperties),(0,te._)`${r} = ${s}`)))}X.checkMissingProp=Ky;function Jy(e,t){e.setParams({missingProperty:t},!0),e.error()}X.reportMissingProp=Jy;function Vu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,te._)`Object.prototype.hasOwnProperty`})}X.hasPropFunc=Vu;function Oi(e,t,n){return(0,te._)`${Vu(e)}.call(${t}, ${n})`}X.isOwnProperty=Oi;function Xy(e,t,n,o){let r=(0,te._)`${t}${(0,te.getProperty)(n)} !== undefined`;return o?(0,te._)`${r} && ${Oi(e,t,n)}`:r}X.propertyInData=Xy;function Ni(e,t,n,o){let r=(0,te._)`${t}${(0,te.getProperty)(n)} === undefined`;return o?(0,te.or)(r,(0,te.not)(Oi(e,t,n))):r}X.noPropertyInData=Ni;function Gu(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}X.allSchemaProperties=Gu;function Yy(e,t){return Gu(t).filter(n=>!(0,Ii.alwaysValidSchema)(e,t[n]))}X.schemaProperties=Yy;function Zy({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,p=[[kt.default.instancePath,(0,te.strConcat)(kt.default.instancePath,s)],[kt.default.parentData,i.parentData],[kt.default.parentDataProperty,i.parentDataProperty],[kt.default.rootData,kt.default.rootData]];i.opts.dynamicRef&&p.push([kt.default.dynamicAnchors,kt.default.dynamicAnchors]);let y=(0,te._)`${d}, ${n.object(...p)}`;return c!==te.nil?(0,te._)`${a}.call(${c}, ${y})`:(0,te._)`${a}(${y})`}X.callValidateCode=Zy;var Qy=(0,te._)`new RegExp`;function eb({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"?Qy:(0,Gy.useFunc)(e,r)}(${n}, ${o})`})}X.usePattern=eb;function tb(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:Ii.Type.Num},s),t.if((0,te.not)(s),a)})}}X.validateArray=tb;function nb(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,Ii.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=nb});var Ju=w(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.validateKeywordUsage=rt.validSchemaType=rt.funcKeywordCode=rt.macroKeywordCode=void 0;var xe=F(),Vt=Ue(),ob=ze(),rb=so();function sb(e,t){let{gen:n,keyword:o,schema:r,parentSchema:s,it:i}=e,a=t.macro.call(i.self,r,s,i),c=Ku(n,o,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=n.name("valid");e.subschema({schema:a,schemaPath:xe.nil,errSchemaPath:`${i.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}rt.macroKeywordCode=sb;function ib(e,t){var n;let{gen:o,keyword:r,schema:s,parentSchema:i,$data:a,it:c}=e;cb(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,d=Ku(o,r,l),p=o.let("valid");e.block$data(p,y),e.ok((n=t.valid)!==null&&n!==void 0?n:p);function y(){if(t.errors===!1)_(),t.modifying&&Wu(e),k(()=>e.error());else{let C=t.async?v():h();t.modifying&&Wu(e),k(()=>ab(e,C))}}function v(){let C=o.let("ruleErrs",null);return o.try(()=>_((0,xe._)`await `),E=>o.assign(p,!1).if((0,xe._)`${E} instanceof ${c.ValidationError}`,()=>o.assign(C,(0,xe._)`${E}.errors`),()=>o.throw(E))),C}function h(){let C=(0,xe._)`${d}.errors`;return o.assign(C,null),_(xe.nil),C}function _(C=t.async?(0,xe._)`await `:xe.nil){let E=c.opts.passContext?Vt.default.this:Vt.default.self,O=!("compile"in t&&!a||t.schema===!1);o.assign(p,(0,xe._)`${C}${(0,ob.callValidateCode)(e,d,E,O)}`,t.modifying)}function k(C){var E;o.if((0,xe.not)((E=t.valid)!==null&&E!==void 0?E:p),C)}}rt.funcKeywordCode=ib;function Wu(e){let{gen:t,data:n,it:o}=e;t.if(o.parentData,()=>t.assign(n,(0,xe._)`${o.parentData}[${o.parentDataProperty}]`))}function ab(e,t){let{gen:n}=e;n.if((0,xe._)`Array.isArray(${t})`,()=>{n.assign(Vt.default.vErrors,(0,xe._)`${Vt.default.vErrors} === null ? ${t} : ${Vt.default.vErrors}.concat(${t})`).assign(Vt.default.errors,(0,xe._)`${Vt.default.vErrors}.length`),(0,rb.extendErrors)(e)},()=>e.error())}function cb({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Ku(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,xe.stringify)(n)})}function lb(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")}rt.validSchemaType=lb;function ub({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)}}rt.validateKeywordUsage=ub});var Yu=w(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.extendSubschemaMode=Ct.extendSubschemaData=Ct.getSubschema=void 0;var st=F(),Xu=q();function db(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,st._)`${e.schemaPath}${(0,st.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,st._)`${e.schemaPath}${(0,st.getProperty)(t)}${(0,st.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Xu.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')}Ct.getSubschema=db;function fb(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:p}=t,y=a.let("data",(0,st._)`${t.data}${(0,st.getProperty)(n)}`,!0);c(y),e.errorPath=(0,st.str)`${l}${(0,Xu.getErrorPath)(n,o,p.jsPropertySyntax)}`,e.parentDataProperty=(0,st._)`${n}`,e.dataPathArr=[...d,e.parentDataProperty]}if(r!==void 0){let l=r instanceof st.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]}}Ct.extendSubschemaData=fb;function pb(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}Ct.extendSubschemaMode=pb});var Fi=w((KS,Zu)=>{"use strict";Zu.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 ed=w((JS,Qu)=>{"use strict";var wt=Qu.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(){};pr(t,o,r,e,"",e)};wt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};wt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wt.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 pr(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 p=o[d];if(Array.isArray(p)){if(d in wt.arrayKeywords)for(var y=0;y<p.length;y++)pr(e,t,n,p[y],r+"/"+d+"/"+y,s,r,d,o,y)}else if(d in wt.propsKeywords){if(p&&typeof p=="object")for(var v in p)pr(e,t,n,p[v],r+"/"+d+"/"+mb(v),s,r,d,o,v)}else(d in wt.keywords||e.allKeys&&!(d in wt.skipKeywords))&&pr(e,t,n,p,r+"/"+d,s,r,d,o)}n(o,r,s,i,a,c,l)}}function mb(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ao=w($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.getSchemaRefs=$e.resolveUrl=$e.normalizeId=$e._getFullPath=$e.getFullPath=$e.inlineRef=void 0;var gb=q(),hb=Fi(),yb=ed(),bb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _b(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Li(e):t?td(e)<=t:!1}$e.inlineRef=_b;var vb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Li(e){for(let t in e){if(vb.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(Li)||typeof n=="object"&&Li(n))return!0}return!1}function td(e){let t=0;for(let n in e){if(n==="$ref")return 1/0;if(t++,!bb.has(n)&&(typeof e[n]=="object"&&(0,gb.eachItem)(e[n],o=>t+=td(o)),t===1/0))return 1/0}return t}function nd(e,t="",n){n!==!1&&(t=vn(t));let o=e.parse(t);return od(e,o)}$e.getFullPath=nd;function od(e,t){return e.serialize(t).split("#")[0]+"#"}$e._getFullPath=od;var Tb=/#\/?$/;function vn(e){return e?e.replace(Tb,""):""}$e.normalizeId=vn;function kb(e,t,n){return n=vn(n),e.resolve(t,n)}$e.resolveUrl=kb;var Cb=/^[a-z_][-a-z0-9._]*$/i;function wb(e,t){if(typeof e=="boolean")return{};let{schemaId:n,uriResolver:o}=this.opts,r=vn(e[n]||t),s={"":r},i=nd(o,r,!1),a={},c=new Set;return yb(e,{allKeys:!0},(p,y,v,h)=>{if(h===void 0)return;let _=i+y,k=s[h];typeof p[n]=="string"&&(k=C.call(this,p[n])),E.call(this,p.$anchor),E.call(this,p.$dynamicAnchor),s[y]=k;function C(O){let U=this.opts.uriResolver.resolve;if(O=vn(k?U(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(p,M.schema,O):O!==vn(_)&&(O[0]==="#"?(l(p,a[O],O),a[O]=p):this.refs[O]=_),O}function E(O){if(typeof O=="string"){if(!Cb.test(O))throw new Error(`invalid anchor "${O}"`);C.call(this,`#${O}`)}}}),a;function l(p,y,v){if(y!==void 0&&!hb(p,y))throw d(v)}function d(p){return new Error(`reference "${p}" resolves to more than one schema`)}}$e.getSchemaRefs=wb});var uo=w(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.getData=Rt.KeywordCxt=Rt.validateFunctionCode=void 0;var cd=Lu(),rd=io(),Di=Ai(),mr=io(),Rb=Hu(),lo=Ju(),ji=Yu(),A=F(),N=Ue(),xb=ao(),pt=q(),co=so();function Sb(e){if(dd(e)&&(fd(e),ud(e))){$b(e);return}ld(e,()=>(0,cd.topBoolOrEmptySchema)(e))}Rt.validateFunctionCode=Sb;function ld({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"; ${sd(n,r)}`),Ab(e,r),e.code(s)}):e.func(t,(0,A._)`${N.default.data}, ${Eb(r)}`,o.$async,()=>e.code(sd(n,r)).code(s))}function Eb(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 Ab(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 $b(e){let{schema:t,opts:n,gen:o}=e;ld(e,()=>{n.$comment&&t.$comment&&md(e),Nb(e),o.let(N.default.vErrors,null),o.let(N.default.errors,0),n.unevaluated&&Pb(e),pd(e),jb(e)})}function Pb(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 sd(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 Mb(e,t){if(dd(e)&&(fd(e),ud(e))){Ib(e,t);return}(0,cd.boolOrEmptySchema)(e,t)}function ud({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 dd(e){return typeof e.schema!="boolean"}function Ib(e,t){let{schema:n,gen:o,opts:r}=e;r.$comment&&n.$comment&&md(e),Fb(e),Lb(e);let s=o.const("_errs",N.default.errors);pd(e,s),o.var(t,(0,A._)`${s} === ${N.default.errors}`)}function fd(e){(0,pt.checkUnknownRules)(e),Ob(e)}function pd(e,t){if(e.opts.jtd)return id(e,[],!1,t);let n=(0,rd.getSchemaTypes)(e.schema),o=(0,rd.coerceAndCheckDataType)(e,n);id(e,n,!o,t)}function Ob(e){let{schema:t,errSchemaPath:n,opts:o,self:r}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,pt.schemaHasRulesButRef)(t,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Nb(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,pt.checkStrictMode)(e,"default is ignored in the schema root")}function Fb(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,xb.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Lb(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function md({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 jb(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&&Db(e),t.return((0,A._)`${N.default.errors} === 0`))}function Db({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,pt.schemaHasRulesButRef)(s,d))){r.block(()=>hd(e,"$ref",d.all.$ref.definition));return}c.jtd||Bb(e,t),r.block(()=>{for(let y of d.rules)p(y);p(d.post)});function p(y){(0,Di.shouldUseGroup)(s,y)&&(y.type?(r.if((0,mr.checkDataType)(y.type,i,c.strictNumbers)),ad(e,y),t.length===1&&t[0]===y.type&&n&&(r.else(),(0,mr.reportTypeError)(e)),r.endIf()):ad(e,y),a||r.if((0,A._)`${N.default.errors} === ${o||0}`))}}function ad(e,t){let{gen:n,schema:o,opts:{useDefaults:r}}=e;r&&(0,Rb.assignDefaults)(e,t.type),n.block(()=>{for(let s of t.rules)(0,Di.shouldUseRule)(o,s)&&hd(e,s.keyword,s.definition,t.type)})}function Bb(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(qb(e,t),e.opts.allowUnionTypes||Ub(e,t),zb(e,e.dataTypes))}function qb(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{gd(e.dataTypes,n)||Bi(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),Vb(e,t)}}function Ub(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Bi(e,"use allowUnionTypes to allow union type keyword")}function zb(e,t){let n=e.self.RULES.all;for(let o in n){let r=n[o];if(typeof r=="object"&&(0,Di.shouldUseRule)(e.schema,r)){let{type:s}=r.definition;s.length&&!s.some(i=>Hb(t,i))&&Bi(e,`missing type "${s.join(",")}" for keyword "${o}"`)}}}function Hb(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function gd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Vb(e,t){let n=[];for(let o of e.dataTypes)gd(t,o)?n.push(o):t.includes("integer")&&o==="number"&&n.push("integer");e.dataTypes=n}function Bi(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,pt.checkStrictMode)(e,t,e.opts.strictTypes)}var gr=class{constructor(t,n,o){if((0,lo.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,pt.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",yd(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,lo.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?co.reportExtraError:co.reportError)(this,this.def.error,n)}$dataError(){(0,co.reportError)(this,this.def.$dataError||co.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,co.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,mr.checkDataTypes)(c,n,s.opts.strictNumbers,mr.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,ji.getSubschema)(this.it,t);(0,ji.extendSubschemaData)(o,this.it,t),(0,ji.extendSubschemaMode)(o,t);let r={...this.it,...o,items:void 0,props:void 0};return Mb(r,n),r}mergeEvaluated(t,n){let{it:o,gen:r}=this;o.opts.unevaluated&&(o.props!==!0&&t.props!==void 0&&(o.props=pt.mergeEvaluated.props(r,t.props,o.props,n)),o.items!==!0&&t.items!==void 0&&(o.items=pt.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}};Rt.KeywordCxt=gr;function hd(e,t,n,o){let r=new gr(e,n,t);"code"in n?n.code(r,o):r.$data&&n.validate?(0,lo.funcKeywordCode)(r,n):"macro"in n?(0,lo.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,lo.funcKeywordCode)(r,n)}var Gb=/^\/(?:[^~]|~0|~1)*$/,Wb=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function yd(e,{dataLevel:t,dataNames:n,dataPathArr:o}){let r,s;if(e==="")return N.default.rootData;if(e[0]==="/"){if(!Gb.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);r=e,s=N.default.rootData}else{let l=Wb.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,pt.unescapeJsonPointer)(l))}`,i=(0,A._)`${i} && ${s}`);return i;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Rt.getData=yd});var hr=w(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var qi=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ui.default=qi});var fo=w(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var zi=ao(),Hi=class extends Error{constructor(t,n,o,r){super(r||`can't resolve reference ${o} from id ${n}`),this.missingRef=(0,zi.resolveUrl)(t,n,o),this.missingSchema=(0,zi.normalizeId)((0,zi.getFullPath)(t,this.missingRef))}};Vi.default=Hi});var po=w(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.resolveSchema=He.getCompilingSchema=He.resolveRef=He.compileSchema=He.SchemaEnv=void 0;var Ze=F(),Kb=hr(),Gt=Ue(),Qe=ao(),bd=q(),Jb=uo(),Tn=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,Qe.normalizeId)(o?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=o?.$async,this.refs={}}};He.SchemaEnv=Tn;function Wi(e){let t=_d.call(this,e);if(t)return t;let n=(0,Qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:r}=this.opts.code,{ownProperties:s}=this.opts,i=new Ze.CodeGen(this.scope,{es5:o,lines:r,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:Kb.default,code:(0,Ze._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Gt.default.data,parentData:Gt.default.parentData,parentDataProperty:Gt.default.parentDataProperty,dataNames:[Gt.default.data],dataPathArr:[Ze.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ze.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ze.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ze._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,Jb.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();d=`${i.scopeRefs(Gt.default.scope)}return ${p}`,this.opts.code.process&&(d=this.opts.code.process(d,e));let v=new Function(`${Gt.default.self}`,`${Gt.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:v}),v.errors=null,v.schema=e.schema,v.schemaEnv=e,e.$async&&(v.$async=!0),this.opts.code.source===!0&&(v.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:_}=l;v.evaluated={props:h instanceof Ze.Name?void 0:h,items:_ instanceof Ze.Name?void 0:_,dynamicProps:h instanceof Ze.Name,dynamicItems:_ instanceof Ze.Name},v.source&&(v.source.evaluated=(0,Ze.stringify)(v.evaluated))}return e.validate=v,e}catch(p){throw delete e.validate,delete e.validateName,d&&this.logger.error("Error compiling schema, function code:",d),p}finally{this._compilations.delete(e)}}He.compileSchema=Wi;function Xb(e,t,n){var o;n=(0,Qe.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let s=Qb.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 Tn({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=Yb.call(this,s)}He.resolveRef=Xb;function Yb(e){return(0,Qe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Wi.call(this,e)}function _d(e){for(let t of this._compilations)if(Zb(t,e))return t}He.getCompilingSchema=_d;function Zb(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Qb(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||yr.call(this,e,t)}function yr(e,t){let n=this.opts.uriResolver.parse(t),o=(0,Qe._getFullPath)(this.opts.uriResolver,n),r=(0,Qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===r)return Gi.call(this,n,e);let s=(0,Qe.normalizeId)(o),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=yr.call(this,e,i);return typeof a?.schema!="object"?void 0:Gi.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Wi.call(this,i),s===(0,Qe.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(r=(0,Qe.resolveUrl)(this.opts.uriResolver,r,l)),new Tn({schema:a,schemaId:c,root:e,baseId:r})}return Gi.call(this,n,i)}}He.resolveSchema=yr;var e_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gi(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,bd.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!e_.has(a)&&l&&(t=(0,Qe.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,bd.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Qe.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=yr.call(this,o,a)}let{schemaId:i}=this.opts;if(s=s||new Tn({schema:n,schemaId:i,root:o,baseId:t}),s.schema!==s.root.schema)return s}});var vd=w((tE,t_)=>{t_.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 Xi=w((nE,xd)=>{"use strict";var n_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kd=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),Ki=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Cd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ji(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 r_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Td(e){return e.length=0,!0}function s_(e,t,n){if(e.length){let o=Ji(e);if(o!=="")t.push(o);else return n.error=!0,!1;e.length=0}return!0}function i_(e){let t=0,n={error:!1,address:"",zone:""},o=[],r=[],s=!1,i=!1,a=s_;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=Td}else{r.push(l);continue}}return r.length&&(a===Td?n.zone=r.join(""):i?o.push(r.join("")):o.push(Ji(r))),n.address=o.join(""),n}function wd(e){if(a_(e,":")<2)return{host:e,isIPV6:!1};let t=i_(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 a_(e,t){let n=0;for(let o=0;o<e.length;o++)e[o]===t&&n++;return n}function c_(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 l_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},u_=/[@/?#:]/g,d_=/[@/?#]/g;function Rd(e,t){let n=t?d_:u_;return n.lastIndex=0,e.replace(n,o=>l_[o])}function f_(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(Ki(r)){let s=r.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Cd(i)?n+=i:n+="%"+s,o+=2;continue}}n+=e[o]}return n}function p_(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(Ki(o)){let r=o.toUpperCase(),s=String.fromCharCode(parseInt(r,16));s!=="."&&Cd(s)?t+=s:t+="%"+r,n+=2;continue}}o_(e[n])?t+=e[n]:t+=escape(e[n])}return t}function m_(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(Ki(o)){t+="%"+o.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function g_(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!kd(n)){let o=wd(n);o.isIPV6===!0?n=`[${o.escapedHost}]`:n=Rd(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}xd.exports={nonSimpleDomain:r_,recomposeAuthority:g_,reescapeHostDelimiters:Rd,normalizePercentEncoding:f_,normalizePathEncoding:p_,escapePreservingEscapes:m_,removeDotSegments:c_,isIPv4:kd,isUUID:n_,normalizeIPv6:wd,stringArrayToHexStripped:Ji}});var Pd=w((oE,$d)=>{"use strict";var{isUUID:h_}=Xi(),y_=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,b_=["http","https","ws","wss","urn","urn:uuid"];function __(e){return b_.indexOf(e)!==-1}function Yi(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 Sd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Ed(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 v_(e){return e.secure=Yi(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function T_(e){if((e.port===(Yi(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 k_(e,t){if(!e.path)return e.error="URN can not be parsed",e;let n=e.path.match(y_);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=Zi(r);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function C_(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=Zi(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 w_(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!h_(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function R_(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Ad={scheme:"http",domainHost:!0,parse:Sd,serialize:Ed},x_={scheme:"https",domainHost:Ad.domainHost,parse:Sd,serialize:Ed},br={scheme:"ws",domainHost:!0,parse:v_,serialize:T_},S_={scheme:"wss",domainHost:br.domainHost,parse:br.parse,serialize:br.serialize},E_={scheme:"urn",parse:k_,serialize:C_,skipNormalize:!0},A_={scheme:"urn:uuid",parse:w_,serialize:R_,skipNormalize:!0},_r={http:Ad,https:x_,ws:br,wss:S_,urn:E_,"urn:uuid":A_};Object.setPrototypeOf(_r,null);function Zi(e){return e&&(_r[e]||_r[e.toLowerCase()])||void 0}$d.exports={wsIsSecure:Yi,SCHEMES:_r,isValidSchemeName:__,getSchemeHandler:Zi}});var Ld=w((rE,vr)=>{"use strict";var{normalizeIPv6:$_,removeDotSegments:mo,recomposeAuthority:P_,normalizePercentEncoding:M_,normalizePathEncoding:I_,escapePreservingEscapes:O_,reescapeHostDelimiters:N_,isIPv4:F_,nonSimpleDomain:L_}=Xi(),{SCHEMES:j_,getSchemeHandler:Id}=Pd();function D_(e,t){return typeof e=="string"?e=H_(e,t):typeof e=="object"&&(e=kn(Wt(e,t),t)),e}function B_(e,t,n){let o=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=Od(kn(e,o),kn(t,o),o,!0);return o.skipEscape=!0,Wt(r,o)}function Od(e,t,n,o){let r={};return o||(e=kn(Wt(e,n),n),t=kn(Wt(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=mo(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=mo(t.path||""),r.query=t.query):(t.path?(t.path[0]==="/"?r.path=mo(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=mo(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 q_(e,t,n){let o=Md(e,n),r=Md(t,n);return o!==void 0&&r!==void 0&&o.toLowerCase()===r.toLowerCase()}function Wt(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=Id(o.scheme||n.scheme);s&&s.serialize&&s.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=M_(n.path):(n.path=O_(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),o.reference!=="suffix"&&n.scheme&&r.push(n.scheme,":");let i=P_(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=mo(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 U_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function z_(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 Nd(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(U_);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=z_(o,i);if(a!==void 0&&(o.error=o.error||a,r=!0),o.host)if(F_(o.host)===!1){let d=$_(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=Id(n.scheme||o.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&o.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&L_(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=N_(unescape(o.host),s))),o.path&&(o.path=I_(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 kn(e,t){return Nd(e,t).parsed}function H_(e,t){return Fd(e,t).normalized}function Fd(e,t){let{parsed:n,malformedAuthorityOrPort:o}=Nd(e,t);return{normalized:o?e:Wt(n,t),malformedAuthorityOrPort:o}}function Md(e,t){if(typeof e=="string"){let{normalized:n,malformedAuthorityOrPort:o}=Fd(e,t);return o?void 0:n}if(typeof e=="object")return Wt(e,t)}var Qi={SCHEMES:j_,normalize:D_,resolve:B_,resolveComponent:Od,equal:q_,serialize:Wt,parse:kn};vr.exports=Qi;vr.exports.default=Qi;vr.exports.fastUri=Qi});var Dd=w(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var jd=Ld();jd.code='require("ajv/dist/runtime/uri").default';ea.default=jd});var Wd=w(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.CodeGen=pe.Name=pe.nil=pe.stringify=pe.str=pe._=pe.KeywordCxt=void 0;var V_=uo();Object.defineProperty(pe,"KeywordCxt",{enumerable:!0,get:function(){return V_.KeywordCxt}});var Cn=F();Object.defineProperty(pe,"_",{enumerable:!0,get:function(){return Cn._}});Object.defineProperty(pe,"str",{enumerable:!0,get:function(){return Cn.str}});Object.defineProperty(pe,"stringify",{enumerable:!0,get:function(){return Cn.stringify}});Object.defineProperty(pe,"nil",{enumerable:!0,get:function(){return Cn.nil}});Object.defineProperty(pe,"Name",{enumerable:!0,get:function(){return Cn.Name}});Object.defineProperty(pe,"CodeGen",{enumerable:!0,get:function(){return Cn.CodeGen}});var G_=hr(),Hd=fo(),W_=Ei(),go=po(),K_=F(),ho=ao(),Tr=io(),na=q(),Bd=vd(),J_=Dd(),Vd=(e,t)=>new RegExp(e,t);Vd.code="new RegExp";var X_=["removeAdditional","useDefaults","coerceTypes"],Y_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Z_={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."},Q_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},qd=200;function ev(e){var t,n,o,r,s,i,a,c,l,d,p,y,v,h,_,k,C,E,O,U,M,Q,Ie,ee,Ge;let nt=e.strict,an=(t=e.code)===null||t===void 0?void 0:t.optimize,at=an===!0||an===void 0?1:an||0,Oe=(o=(n=e.code)===null||n===void 0?void 0:n.regExp)!==null&&o!==void 0?o:Vd,ct=(r=e.uriResolver)!==null&&r!==void 0?r:J_.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=(p=e.strictTuples)!==null&&p!==void 0?p:nt)!==null&&y!==void 0?y:"log",strictRequired:(h=(v=e.strictRequired)!==null&&v!==void 0?v:nt)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:at,regExp:Oe}:{optimize:at,regExp:Oe},loopRequired:(_=e.loopRequired)!==null&&_!==void 0?_:qd,loopEnum:(k=e.loopEnum)!==null&&k!==void 0?k:qd,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:(U=e.schemaId)!==null&&U!==void 0?U:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(Q=e.validateSchema)!==null&&Q!==void 0?Q:!0,validateFormats:(Ie=e.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(ee=e.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(Ge=e.int32range)!==null&&Ge!==void 0?Ge:!0,uriResolver:ct}}var yo=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,...ev(t)};let{es5:n,lines:o}=this.opts.code;this.scope=new K_.ValueScope({scope:{},prefixes:Y_,es5:n,lines:o}),this.logger=iv(t.logger);let r=t.validateFormats;t.validateFormats=!1,this.RULES=(0,W_.getRules)(),Ud.call(this,Z_,t,"NOT SUPPORTED"),Ud.call(this,Q_,t,"DEPRECATED","warn"),this._metaOpts=rv.call(this),t.formats&&nv.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&ov.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),tv.call(this),t.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:n,schemaId:o}=this.opts,r=Bd;o==="id"&&(r={...Bd},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,p){await s.call(this,d.$schema);let y=this._addSchema(d,p);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(p){if(!(p instanceof Hd.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:p}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${p} cannot be resolved`)}async function c(d){let p=await l.call(this,d);this.refs[d]||await s.call(this,p.$schema),this.refs[d]||this.addSchema(p,d,n)}async function l(d){let p=this._loading[d];if(p)return p;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,ho.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=zd.call(this,t))=="string";)t=n;if(n===void 0){let{schemaId:o}=this.opts,r=new go.SchemaEnv({schema:{},schemaId:o});if(n=go.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=zd.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,ho.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(cv.call(this,o,n),!n)return(0,na.eachItem)(o,s=>ta.call(this,s)),this;uv.call(this,n);let r={...n,type:(0,Tr.getJSONTypes)(n.type),schemaType:(0,Tr.getJSONTypes)(n.schemaType)};return(0,na.eachItem)(o,r.type.length===0?s=>ta.call(this,s,r):s=>r.type.forEach(i=>ta.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]=Gd(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,ho.normalizeId)(i||o);let l=ho.getSchemaRefs.call(this,t,o);return c=new go.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):go.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{go.compileSchema.call(this,t)}finally{this.opts=n}}};yo.ValidationError=G_.default;yo.MissingRefError=Hd.default;pe.default=yo;function Ud(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 zd(e){return e=(0,ho.normalizeId)(e),this.schemas[e]||this.refs[e]}function tv(){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 nv(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ov(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 rv(){let e={...this.opts};for(let t of X_)delete e[t];return e}var sv={log(){},warn(){},error(){}};function iv(e){if(e===!1)return sv;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 av=/^[a-z_$][a-z0-9_$:-]*$/i;function cv(e,t){let{RULES:n}=this;if((0,na.eachItem)(e,o=>{if(n.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!av.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 ta(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,Tr.getJSONTypes)(t.type),schemaType:(0,Tr.getJSONTypes)(t.schemaType)}};t.before?lv.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 lv(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 uv(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Gd(t)),e.validateSchema=this.compile(t,!0))}var dv={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Gd(e){return{anyOf:[e,dv]}}});var Kd=w(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});var fv={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};oa.default=fv});var wr=w(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.callRef=Kt.getValidate=void 0;var pv=fo(),Jd=ze(),Pe=F(),wn=Ue(),Xd=po(),kr=q(),mv={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 p();let d=Xd.resolveRef.call(c,l,r,n);if(d===void 0)throw new pv.default(o.opts.uriResolver,r,n);if(d instanceof Xd.SchemaEnv)return y(d);return v(d);function p(){if(s===l)return Cr(e,i,s,s.$async);let h=t.scopeValue("root",{ref:l});return Cr(e,(0,Pe._)`${h}.validate`,l,l.$async)}function y(h){let _=Yd(e,h);Cr(e,_,h,h.$async)}function v(h){let _=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Pe.stringify)(h)}:{ref:h}),k=t.name("valid"),C=e.subschema({schema:h,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:_,errSchemaPath:n},k);e.mergeEvaluated(C),e.ok(k)}}};function Yd(e,t){let{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Kt.getValidate=Yd;function Cr(e,t,n,o){let{gen:r,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?wn.default.this:Pe.nil;o?d():p();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=r.let("valid");r.try(()=>{r.code((0,Pe._)`await ${(0,Jd.callValidateCode)(e,t,l)}`),v(t),i||r.assign(h,!0)},_=>{r.if((0,Pe._)`!(${_} instanceof ${s.ValidationError})`,()=>r.throw(_)),y(_),i||r.assign(h,!1)}),e.ok(h)}function p(){e.result((0,Jd.callValidateCode)(e,t,l),()=>v(t),()=>y(t))}function y(h){let _=(0,Pe._)`${h}.errors`;r.assign(wn.default.vErrors,(0,Pe._)`${wn.default.vErrors} === null ? ${_} : ${wn.default.vErrors}.concat(${_})`),r.assign(wn.default.errors,(0,Pe._)`${wn.default.vErrors}.length`)}function v(h){var _;if(!s.opts.unevaluated)return;let k=(_=n?.validate)===null||_===void 0?void 0:_.evaluated;if(s.props!==!0)if(k&&!k.dynamicProps)k.props!==void 0&&(s.props=kr.mergeEvaluated.props(r,k.props,s.props));else{let C=r.var("props",(0,Pe._)`${h}.evaluated.props`);s.props=kr.mergeEvaluated.props(r,C,s.props,Pe.Name)}if(s.items!==!0)if(k&&!k.dynamicItems)k.items!==void 0&&(s.items=kr.mergeEvaluated.items(r,k.items,s.items));else{let C=r.var("items",(0,Pe._)`${h}.evaluated.items`);s.items=kr.mergeEvaluated.items(r,C,s.items,Pe.Name)}}}Kt.callRef=Cr;Kt.default=mv});var Zd=w(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var gv=Kd(),hv=wr(),yv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gv.default,hv.default];ra.default=yv});var Qd=w(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});var Rr=F(),xt=Rr.operators,xr={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},bv={message:({keyword:e,schemaCode:t})=>(0,Rr.str)`must be ${xr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Rr._)`{comparison: ${xr[e].okStr}, limit: ${t}}`},_v={keyword:Object.keys(xr),type:"number",schemaType:"number",$data:!0,error:bv,code(e){let{keyword:t,data:n,schemaCode:o}=e;e.fail$data((0,Rr._)`${n} ${xr[t].fail} ${o} || isNaN(${n})`)}};sa.default=_v});var ef=w(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});var bo=F(),vv={message:({schemaCode:e})=>(0,bo.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,bo._)`{multipleOf: ${e}}`},Tv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:vv,code(e){let{gen:t,data:n,schemaCode:o,it:r}=e,s=r.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,bo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bo._)`${i} !== parseInt(${i})`;e.fail$data((0,bo._)`(${o} === 0 || (${i} = ${n}/${o}, ${a}))`)}};ia.default=Tv});var nf=w(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});function tf(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}aa.default=tf;tf.code='require("ajv/dist/runtime/ucs2length").default'});var of=w(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});var Jt=F(),kv=q(),Cv=nf(),wv={message({keyword:e,schemaCode:t}){let n=e==="maxLength"?"more":"fewer";return(0,Jt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,Jt._)`{limit: ${e}}`},Rv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wv,code(e){let{keyword:t,data:n,schemaCode:o,it:r}=e,s=t==="maxLength"?Jt.operators.GT:Jt.operators.LT,i=r.opts.unicode===!1?(0,Jt._)`${n}.length`:(0,Jt._)`${(0,kv.useFunc)(e.gen,Cv.default)}(${n})`;e.fail$data((0,Jt._)`${i} ${s} ${o}`)}};ca.default=Rv});var rf=w(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});var xv=ze(),Sv=q(),Rn=F(),Ev={message:({schemaCode:e})=>(0,Rn.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Rn._)`{pattern: ${e}}`},Av={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ev,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,Rn._)`new RegExp`:(0,Sv.useFunc)(t,c),d=t.let("valid");t.try(()=>t.assign(d,(0,Rn._)`${l}(${s}, ${a}).test(${n})`),()=>t.assign(d,!1)),e.fail$data((0,Rn._)`!${d}`)}else{let c=(0,xv.usePattern)(e,r);e.fail$data((0,Rn._)`!${c}.test(${n})`)}}};la.default=Av});var sf=w(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});var _o=F(),$v={message({keyword:e,schemaCode:t}){let n=e==="maxProperties"?"more":"fewer";return(0,_o.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,_o._)`{limit: ${e}}`},Pv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$v,code(e){let{keyword:t,data:n,schemaCode:o}=e,r=t==="maxProperties"?_o.operators.GT:_o.operators.LT;e.fail$data((0,_o._)`Object.keys(${n}).length ${r} ${o}`)}};ua.default=Pv});var af=w(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});var vo=ze(),To=F(),Mv=q(),Iv={message:({params:{missingProperty:e}})=>(0,To.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,To._)`{missingProperty: ${e}}`},Ov={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Iv,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 v=e.parentSchema.properties,{definedProperties:h}=e.it;for(let _ of n)if(v?.[_]===void 0&&!h.has(_)){let k=i.schemaEnv.baseId+i.errSchemaPath,C=`required property "${_}" is not defined at "${k}" (strictRequired)`;(0,Mv.checkStrictMode)(i,C,i.opts.strictRequired)}}function l(){if(c||s)e.block$data(To.nil,p);else for(let v of n)(0,vo.checkReportMissingProp)(e,v)}function d(){let v=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>y(v,h)),e.ok(h)}else t.if((0,vo.checkMissingProp)(e,n,v)),(0,vo.reportMissingProp)(e,v),t.else()}function p(){t.forOf("prop",o,v=>{e.setParams({missingProperty:v}),t.if((0,vo.noPropertyInData)(t,r,v,a.ownProperties),()=>e.error())})}function y(v,h){e.setParams({missingProperty:v}),t.forOf(v,o,()=>{t.assign(h,(0,vo.propertyInData)(t,r,v,a.ownProperties)),t.if((0,To.not)(h),()=>{e.error(),t.break()})},To.nil)}}};da.default=Ov});var cf=w(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});var ko=F(),Nv={message({keyword:e,schemaCode:t}){let n=e==="maxItems"?"more":"fewer";return(0,ko.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,ko._)`{limit: ${e}}`},Fv={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Nv,code(e){let{keyword:t,data:n,schemaCode:o}=e,r=t==="maxItems"?ko.operators.GT:ko.operators.LT;e.fail$data((0,ko._)`${n}.length ${r} ${o}`)}};fa.default=Fv});var Sr=w(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});var lf=Fi();lf.code='require("ajv/dist/runtime/equal").default';pa.default=lf});var uf=w(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});var ma=io(),me=F(),Lv=q(),jv=Sr(),Dv={message:({params:{i:e,j:t}})=>(0,me.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,me._)`{i: ${e}, j: ${t}}`},Bv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Dv,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,me._)`${i} === false`),e.ok(c);function d(){let h=t.let("i",(0,me._)`${n}.length`),_=t.let("j");e.setParams({i:h,j:_}),t.assign(c,!0),t.if((0,me._)`${h} > 1`,()=>(p()?y:v)(h,_))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function y(h,_){let k=t.name("item"),C=(0,ma.checkDataTypes)(l,k,a.opts.strictNumbers,ma.DataType.Wrong),E=t.const("indices",(0,me._)`{}`);t.for((0,me._)`;${h}--;`,()=>{t.let(k,(0,me._)`${n}[${h}]`),t.if(C,(0,me._)`continue`),l.length>1&&t.if((0,me._)`typeof ${k} == "string"`,(0,me._)`${k} += "_"`),t.if((0,me._)`typeof ${E}[${k}] == "number"`,()=>{t.assign(_,(0,me._)`${E}[${k}]`),e.error(),t.assign(c,!1).break()}).code((0,me._)`${E}[${k}] = ${h}`)})}function v(h,_){let k=(0,Lv.useFunc)(t,jv.default),C=t.name("outer");t.label(C).for((0,me._)`;${h}--;`,()=>t.for((0,me._)`${_} = ${h}; ${_}--;`,()=>t.if((0,me._)`${k}(${n}[${h}], ${n}[${_}])`,()=>{e.error(),t.assign(c,!1).break(C)})))}}};ga.default=Bv});var df=w(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});var ha=F(),qv=q(),Uv=Sr(),zv={message:"must be equal to constant",params:({schemaCode:e})=>(0,ha._)`{allowedValue: ${e}}`},Hv={keyword:"const",$data:!0,error:zv,code(e){let{gen:t,data:n,$data:o,schemaCode:r,schema:s}=e;o||s&&typeof s=="object"?e.fail$data((0,ha._)`!${(0,qv.useFunc)(t,Uv.default)}(${n}, ${r})`):e.fail((0,ha._)`${s} !== ${n}`)}};ya.default=Hv});var ff=w(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});var Co=F(),Vv=q(),Gv=Sr(),Wv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Co._)`{allowedValues: ${e}}`},Kv={keyword:"enum",schemaType:"array",$data:!0,error:Wv,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,Vv.useFunc)(t,Gv.default)),d;if(a||o)d=t.let("valid"),e.block$data(d,p);else{if(!Array.isArray(r))throw new Error("ajv implementation error");let v=t.const("vSchema",s);d=(0,Co.or)(...r.map((h,_)=>y(v,_)))}e.pass(d);function p(){t.assign(d,!1),t.forOf("v",s,v=>t.if((0,Co._)`${l()}(${n}, ${v})`,()=>t.assign(d,!0).break()))}function y(v,h){let _=r[h];return typeof _=="object"&&_!==null?(0,Co._)`${l()}(${n}, ${v}[${h}])`:(0,Co._)`${n} === ${_}`}}};ba.default=Kv});var pf=w(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});var Jv=Qd(),Xv=ef(),Yv=of(),Zv=rf(),Qv=sf(),eT=af(),tT=cf(),nT=uf(),oT=df(),rT=ff(),sT=[Jv.default,Xv.default,Yv.default,Zv.default,Qv.default,eT.default,tT.default,nT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oT.default,rT.default];_a.default=sT});var Ta=w(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateAdditionalItems=void 0;var Xt=F(),va=q(),iT={message:({params:{len:e}})=>(0,Xt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Xt._)`{limit: ${e}}`},aT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:iT,code(e){let{parentSchema:t,it:n}=e,{items:o}=t;if(!Array.isArray(o)){(0,va.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}mf(e,o)}};function mf(e,t){let{gen:n,schema:o,data:r,keyword:s,it:i}=e;i.items=!0;let a=n.const("len",(0,Xt._)`${r}.length`);if(o===!1)e.setParams({len:t.length}),e.pass((0,Xt._)`${a} <= ${t.length}`);else if(typeof o=="object"&&!(0,va.alwaysValidSchema)(i,o)){let l=n.var("valid",(0,Xt._)`${a} <= ${t.length}`);n.if((0,Xt.not)(l),()=>c(l)),e.ok(l)}function c(l){n.forRange("i",t.length,a,d=>{e.subschema({keyword:s,dataProp:d,dataPropType:va.Type.Num},l),i.allErrors||n.if((0,Xt.not)(l),()=>n.break())})}}wo.validateAdditionalItems=mf;wo.default=aT});var ka=w(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.validateTuple=void 0;var gf=F(),Er=q(),cT=ze(),lT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:n}=e;if(Array.isArray(t))return hf(e,"additionalItems",t);n.items=!0,!(0,Er.alwaysValidSchema)(n,t)&&e.ok((0,cT.validateArray)(e))}};function hf(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=Er.mergeEvaluated.items(o,n.length,a.items));let c=o.name("valid"),l=o.const("len",(0,gf._)`${s}.length`);n.forEach((p,y)=>{(0,Er.alwaysValidSchema)(a,p)||(o.if((0,gf._)`${l} > ${y}`,()=>e.subschema({keyword:i,schemaProp:y,dataProp:y},c)),e.ok(c))});function d(p){let{opts:y,errSchemaPath:v}=a,h=n.length,_=h===p.minItems&&(h===p.maxItems||p[t]===!1);if(y.strictTuples&&!_){let k=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${v}"`;(0,Er.checkStrictMode)(a,k,y.strictTuples)}}}Ro.validateTuple=hf;Ro.default=lT});var yf=w(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var uT=ka(),dT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,uT.validateTuple)(e,"items")};Ca.default=dT});var _f=w(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});var bf=F(),fT=q(),pT=ze(),mT=Ta(),gT={message:({params:{len:e}})=>(0,bf.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,bf._)`{limit: ${e}}`},hT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gT,code(e){let{schema:t,parentSchema:n,it:o}=e,{prefixItems:r}=n;o.items=!0,!(0,fT.alwaysValidSchema)(o,t)&&(r?(0,mT.validateAdditionalItems)(e,r):e.ok((0,pT.validateArray)(e)))}};wa.default=hT});var vf=w(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});var Ve=F(),Ar=q(),yT={message:({params:{min:e,max:t}})=>t===void 0?(0,Ve.str)`must contain at least ${e} valid item(s)`:(0,Ve.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ve._)`{minContains: ${e}}`:(0,Ve._)`{minContains: ${e}, maxContains: ${t}}`},bT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:yT,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,Ve._)`${r}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ar.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ar.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ar.alwaysValidSchema)(s,n)){let _=(0,Ve._)`${d} >= ${i}`;a!==void 0&&(_=(0,Ve._)`${_} && ${d} <= ${a}`),e.pass(_);return}s.items=!0;let p=t.name("valid");a===void 0&&i===1?v(p,()=>t.if(p,()=>t.break())):i===0?(t.let(p,!0),a!==void 0&&t.if((0,Ve._)`${r}.length > 0`,y)):(t.let(p,!1),y()),e.result(p,()=>e.reset());function y(){let _=t.name("_valid"),k=t.let("count",0);v(_,()=>t.if(_,()=>h(k)))}function v(_,k){t.forRange("i",0,d,C=>{e.subschema({keyword:"contains",dataProp:C,dataPropType:Ar.Type.Num,compositeRule:!0},_),k()})}function h(_){t.code((0,Ve._)`${_}++`),a===void 0?t.if((0,Ve._)`${_} >= ${i}`,()=>t.assign(p,!0).break()):(t.if((0,Ve._)`${_} > ${a}`,()=>t.assign(p,!1).break()),i===1?t.assign(p,!0):t.if((0,Ve._)`${_} >= ${i}`,()=>t.assign(p,!0)))}}};Ra.default=bT});var $r=w(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateSchemaDeps=it.validatePropertyDeps=it.error=void 0;var xa=F(),_T=q(),xo=ze();it.error={message:({params:{property:e,depsCount:t,deps:n}})=>{let o=t===1?"property":"properties";return(0,xa.str)`must have ${o} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:o}})=>(0,xa._)`{property: ${e},
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
6
  missingProperty: ${o},
7
7
  depsCount: ${t},
8
- deps: ${n}}`};var vT={keyword:"dependencies",type:"object",schemaType:"object",error:it.error,code(e){let[t,n]=TT(e);Tf(e,t),kf(e,n)}};function TT({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 Tf(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,xo.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,xo.checkReportMissingProp)(e,l)}):(n.if((0,xa._)`${c} && (${(0,xo.checkMissingProp)(e,a,s)})`),(0,xo.reportMissingProp)(e,s),n.else())}}it.validatePropertyDeps=Tf;function kf(e,t=e.schema){let{gen:n,data:o,keyword:r,it:s}=e,i=n.name("valid");for(let a in t)(0,_T.alwaysValidSchema)(s,t[a])||(n.if((0,xo.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))}it.validateSchemaDeps=kf;it.default=vT});var wf=w(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});var Cf=F(),kT=q(),CT={message:"property name must be valid",params:({params:e})=>(0,Cf._)`{propertyName: ${e.propertyName}}`},wT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:CT,code(e){let{gen:t,schema:n,data:o,it:r}=e;if((0,kT.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,Cf.not)(s),()=>{e.error(!0),r.allErrors||t.break()})}),e.ok(s)}};Sa.default=wT});var Aa=w(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var Pr=ze(),et=F(),RT=Ue(),Mr=q(),xT={message:"must NOT have additional properties",params:({params:e})=>(0,et._)`{additionalProperty: ${e.additionalProperty}}`},ST={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:xT,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,Mr.alwaysValidSchema)(i,n))return;let l=(0,Pr.allSchemaProperties)(o.properties),d=(0,Pr.allSchemaProperties)(o.patternProperties);p(),e.ok((0,et._)`${s} === ${RT.default.errors}`);function p(){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,Mr.schemaRefOrVal)(i,o.properties,"properties");C=(0,Pr.isOwnProperty)(t,E,k)}else l.length?C=(0,et.or)(...l.map(E=>(0,et._)`${k} === ${E}`)):C=et.nil;return d.length&&(C=(0,et.or)(C,...d.map(E=>(0,et._)`${(0,Pr.usePattern)(e,E)}.test(${k})`))),(0,et.not)(C)}function v(k){t.code((0,et._)`delete ${r}[${k}]`)}function h(k){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){v(k);return}if(n===!1){e.setParams({additionalProperty:k}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Mr.alwaysValidSchema)(i,n)){let C=t.name("valid");c.removeAdditional==="failing"?(_(k,C,!1),t.if((0,et.not)(C),()=>{e.reset(),v(k)})):(_(k,C),a||t.if((0,et.not)(C),()=>t.break()))}}function _(k,C,E){let O={keyword:"additionalProperties",dataProp:k,dataPropType:Mr.Type.Str};E===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(O,C)}}};Ea.default=ST});var Sf=w(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});var ET=uo(),Rf=ze(),$a=q(),xf=Aa(),AT={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&&xf.default.code(new ET.KeywordCxt(s,xf.default,"additionalProperties"));let i=(0,Rf.allSchemaProperties)(n);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=$a.mergeEvaluated.props(t,(0,$a.toHash)(i),s.props));let a=i.filter(p=>!(0,$a.alwaysValidSchema)(s,n[p]));if(a.length===0)return;let c=t.name("valid");for(let p of a)l(p)?d(p):(t.if((0,Rf.propertyInData)(t,r,p,s.opts.ownProperties)),d(p),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&n[p].default!==void 0}function d(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Pa.default=AT});var Pf=w(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});var Ef=ze(),Ir=F(),Af=q(),$f=q(),$T={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,Ef.allSchemaProperties)(n),c=a.filter(_=>(0,Af.alwaysValidSchema)(s,n[_]));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 Ir.Name)&&(s.props=(0,$f.evaluatedPropsToName)(t,s.props));let{props:p}=s;y();function y(){for(let _ of a)l&&v(_),s.allErrors?h(_):(t.var(d,!0),h(_),t.if(d))}function v(_){for(let k in l)new RegExp(_).test(k)&&(0,Af.checkStrictMode)(s,`property ${k} matches pattern ${_} (use allowMatchingProperties)`)}function h(_){t.forIn("key",o,k=>{t.if((0,Ir._)`${(0,Ef.usePattern)(e,_)}.test(${k})`,()=>{let C=c.includes(_);C||e.subschema({keyword:"patternProperties",schemaProp:_,dataProp:k,dataPropType:$f.Type.Str},d),s.opts.unevaluated&&p!==!0?t.assign((0,Ir._)`${p}[${k}]`,!0):!C&&!s.allErrors&&t.if((0,Ir.not)(d),()=>t.break())})})}}};Ma.default=$T});var Mf=w(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var PT=q(),MT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:o}=e;if((0,PT.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"}};Ia.default=MT});var If=w(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var IT=ze(),OT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:IT.validateUnion,error:{message:"must match a schema in anyOf"}};Oa.default=OT});var Of=w(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});var Or=F(),NT=q(),FT={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Or._)`{passingSchemas: ${e.passing}}`},LT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:FT,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,p)=>{let y;(0,NT.alwaysValidSchema)(r,d)?t.var(c,!0):y=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,Or._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Or._)`[${a}, ${p}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,p),y&&e.mergeEvaluated(y,Or.Name)})})}}};Na.default=LT});var Nf=w(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var jT=q(),DT={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,jT.alwaysValidSchema)(o,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},r);e.ok(r),e.mergeEvaluated(a)})}};Fa.default=DT});var jf=w(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});var Nr=F(),Lf=q(),BT={message:({params:e})=>(0,Nr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Nr._)`{failingKeyword: ${e.ifClause}}`},qT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:BT,code(e){let{gen:t,parentSchema:n,it:o}=e;n.then===void 0&&n.else===void 0&&(0,Lf.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let r=Ff(o,"then"),s=Ff(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,Nr.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,p){return()=>{let y=e.subschema({keyword:d},a);t.assign(i,a),e.mergeValidEvaluated(y,i),p?t.assign(p,(0,Nr._)`${d}`):e.setParams({ifClause:d})}}}};function Ff(e,t){let n=e.schema[t];return n!==void 0&&!(0,Lf.alwaysValidSchema)(e,n)}La.default=qT});var Df=w(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var UT=q(),zT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,UT.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};ja.default=zT});var Bf=w(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var HT=Ta(),VT=yf(),GT=ka(),WT=_f(),KT=vf(),JT=$r(),XT=wf(),YT=Aa(),ZT=Sf(),QT=Pf(),ek=Mf(),tk=If(),nk=Of(),ok=Nf(),rk=jf(),sk=Df();function ik(e=!1){let t=[ek.default,tk.default,nk.default,ok.default,rk.default,sk.default,XT.default,YT.default,JT.default,ZT.default,QT.default];return e?t.push(VT.default,WT.default):t.push(HT.default,GT.default),t.push(KT.default),t}Da.default=ik});var qa=w(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.dynamicAnchor=void 0;var Ba=F(),ak=Ue(),qf=po(),ck=wr(),lk={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Uf(e,e.schema)};function Uf(e,t){let{gen:n,it:o}=e;o.schemaEnv.root.dynamicAnchors[t]=!0;let r=(0,Ba._)`${ak.default.dynamicAnchors}${(0,Ba.getProperty)(t)}`,s=o.errSchemaPath==="#"?o.validateName:uk(e);n.if((0,Ba._)`!${r}`,()=>n.assign(r,s))}So.dynamicAnchor=Uf;function uk(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 qf.SchemaEnv({schema:n,schemaId:c,root:r,baseId:s,localRefs:i,meta:a});return qf.compileSchema.call(o,l),(0,ck.getValidate)(e,l)}So.default=lk});var Ua=w(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.dynamicRef=void 0;var zf=F(),dk=Ue(),Hf=wr(),fk={keyword:"$dynamicRef",schemaType:"string",code:e=>Vf(e,e.schema)};function Vf(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,zf._)`${dk.default.dynamicAnchors}${(0,zf.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,Hf.callRef)(e,c),n.let(l,!0)}):()=>(0,Hf.callRef)(e,c)}}Eo.dynamicRef=Vf;Eo.default=fk});var Gf=w(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var pk=qa(),mk=q(),gk={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,pk.dynamicAnchor)(e,""):(0,mk.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};za.default=gk});var Wf=w(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var hk=Ua(),yk={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,hk.dynamicRef)(e,e.schema)};Ha.default=yk});var Kf=w(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var bk=qa(),_k=Ua(),vk=Gf(),Tk=Wf(),kk=[bk.default,_k.default,vk.default,Tk.default];Va.default=kk});var Xf=w(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Jf=$r(),Ck={keyword:"dependentRequired",type:"object",schemaType:"object",error:Jf.error,code:e=>(0,Jf.validatePropertyDeps)(e)};Ga.default=Ck});var Yf=w(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var wk=$r(),Rk={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,wk.validateSchemaDeps)(e)};Wa.default=Rk});var Zf=w(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var xk=q(),Sk={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){t.contains===void 0&&(0,xk.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};Ka.default=Sk});var Qf=w(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Ek=Xf(),Ak=Yf(),$k=Zf(),Pk=[Ek.default,Ak.default,$k.default];Ja.default=Pk});var tp=w(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var St=F(),ep=q(),Mk=Ue(),Ik={message:"must NOT have unevaluated properties",params:({params:e})=>(0,St._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},Ok={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Ik,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 St.Name?t.if((0,St._)`${a} !== true`,()=>t.forIn("key",o,p=>t.if(l(a,p),()=>c(p)))):a!==!0&&t.forIn("key",o,p=>a===void 0?c(p):t.if(d(a,p),()=>c(p))),s.props=!0,e.ok((0,St._)`${r} === ${Mk.default.errors}`);function c(p){if(n===!1){e.setParams({unevaluatedProperty:p}),e.error(),i||t.break();return}if(!(0,ep.alwaysValidSchema)(s,n)){let y=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:ep.Type.Str},y),i||t.if((0,St.not)(y),()=>t.break())}}function l(p,y){return(0,St._)`!${p} || !${p}[${y}]`}function d(p,y){let v=[];for(let h in p)p[h]===!0&&v.push((0,St._)`${y} !== ${h}`);return(0,St.and)(...v)}}};Xa.default=Ok});var op=w(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Yt=F(),np=q(),Nk={message:({params:{len:e}})=>(0,Yt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Yt._)`{limit: ${e}}`},Fk={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Nk,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,Yt._)`${o}.length`);if(n===!1)e.setParams({len:s}),e.fail((0,Yt._)`${i} > ${s}`);else if(typeof n=="object"&&!(0,np.alwaysValidSchema)(r,n)){let c=t.var("valid",(0,Yt._)`${i} <= ${s}`);t.if((0,Yt.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:np.Type.Num},c),r.allErrors||t.if((0,Yt.not)(c),()=>t.break())})}}};Ya.default=Fk});var rp=w(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var Lk=tp(),jk=op(),Dk=[Lk.default,jk.default];Za.default=Dk});var sp=w(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var se=F(),Bk={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},qk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Bk,code(e,t){let{gen:n,data:o,$data:r,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:d,self:p}=a;if(!c.validateFormats)return;r?y():v();function y(){let h=n.scopeValue("formats",{ref:p.formats,code:c.code.formats}),_=n.const("fDef",(0,se._)`${h}[${i}]`),k=n.let("fType"),C=n.let("format");n.if((0,se._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>n.assign(k,(0,se._)`${_}.type || "string"`).assign(C,(0,se._)`${_}.validate`),()=>n.assign(k,(0,se._)`"string"`).assign(C,_)),e.fail$data((0,se.or)(E(),O()));function E(){return c.strictSchema===!1?se.nil:(0,se._)`${i} && !${C}`}function O(){let U=d.$async?(0,se._)`(${_}.async ? await ${C}(${o}) : ${C}(${o}))`:(0,se._)`${C}(${o})`,M=(0,se._)`(typeof ${C} == "function" ? ${U} : ${C}.test(${o}))`;return(0,se._)`${C} && ${C} !== true && ${k} === ${t} && !${M}`}}function v(){let h=p.formats[s];if(!h){E();return}if(h===!0)return;let[_,k,C]=O(h);_===t&&e.pass(U());function E(){if(c.strictSchema===!1){p.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function O(M){let Q=M instanceof RegExp?(0,se.regexpCode)(M):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(s)}`:void 0,Ie=n.scopeValue("formats",{key:s,ref:M,code:Q});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,se._)`${Ie}.validate`]:["string",M,Ie]}function U(){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})`}}}};Qa.default=qk});var ip=w(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Uk=sp(),zk=[Uk.default];ec.default=zk});var ap=w(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var lp=w(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Hk=Zd(),Vk=pf(),Gk=Bf(),Wk=Kf(),Kk=Qf(),Jk=rp(),Xk=ip(),cp=ap(),Yk=[Wk.default,Hk.default,Vk.default,(0,Gk.default)(!0),Xk.default,cp.metadataVocabulary,cp.contentVocabulary,Kk.default,Jk.default];tc.default=Yk});var dp=w(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.DiscrError=void 0;var up;(function(e){e.Tag="tag",e.Mapping="mapping"})(up||(Fr.DiscrError=up={}))});var pp=w(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Sn=F(),nc=dp(),fp=po(),Zk=fo(),Qk=q(),eC={message:({params:{discrError:e,tagName:t}})=>e===nc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Sn._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},tC={keyword:"discriminator",type:"object",schemaType:"object",error:eC,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,Sn._)`${n}${(0,Sn.getProperty)(a)}`);t.if((0,Sn._)`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:nc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function d(){let v=y();t.if(!1);for(let h in v)t.elseIf((0,Sn._)`${l} === ${h}`),t.assign(c,p(v[h]));t.else(),e.error(!1,{discrError:nc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function p(v){let h=t.name("valid"),_=e.subschema({keyword:"oneOf",schemaProp:v},h);return e.mergeEvaluated(_,Sn.Name),h}function y(){var v;let h={},_=C(r),k=!0;for(let U=0;U<i.length;U++){let M=i[U];if(M?.$ref&&!(0,Qk.schemaHasRulesButRef)(M,s.self.RULES)){let Ie=M.$ref;if(M=fp.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ie),M instanceof fp.SchemaEnv&&(M=M.schema),M===void 0)throw new Zk.default(s.opts.uriResolver,s.baseId,Ie)}let Q=(v=M?.properties)===null||v===void 0?void 0:v[a];if(typeof Q!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);k=k&&(_||C(M)),E(Q,U)}if(!k)throw new Error(`discriminator: "${a}" must be required`);return h;function C({required:U}){return Array.isArray(U)&&U.includes(a)}function E(U,M){if(U.const)O(U.const,M);else if(U.enum)for(let Q of U.enum)O(Q,M);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function O(U,M){if(typeof U!="string"||U in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[U]=M}}}};oc.default=tC});var mp=w((rA,nC)=>{nC.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 gp=w((sA,oC)=>{oC.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 hp=w((iA,rC)=>{rC.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 yp=w((aA,sC)=>{sC.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 bp=w((cA,iC)=>{iC.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 _p=w((lA,aC)=>{aC.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 vp=w((uA,cC)=>{cC.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 Tp=w((dA,lC)=>{lC.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 kp=w(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var uC=mp(),dC=gp(),fC=hp(),pC=yp(),mC=bp(),gC=_p(),hC=vp(),yC=Tp(),bC=["/properties"];function _C(e){return[uC,dC,fC,pC,mC,t(this,gC),hC,t(this,yC)].forEach(n=>this.addMetaSchema(n,void 0,!1)),this;function t(n,o){return e?n.$dataMetaSchema(o,bC):o}}rc.default=_C});var Cp=w((ne,ic)=>{"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 vC=Wd(),TC=lp(),kC=pp(),CC=kp(),sc="https://json-schema.org/draft/2020-12/schema",En=class extends vC.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),TC.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(kC.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;n&&(CC.default.call(this,t),this.refs["http://json-schema.org/schema"]=sc)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(sc)?sc:void 0)}};ne.Ajv2020=En;ic.exports=ne=En;ic.exports.Ajv2020=En;Object.defineProperty(ne,"__esModule",{value:!0});ne.default=En;var wC=uo();Object.defineProperty(ne,"KeywordCxt",{enumerable:!0,get:function(){return wC.KeywordCxt}});var An=F();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return An._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return An.str}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return An.stringify}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return An.nil}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return An.Name}});Object.defineProperty(ne,"CodeGen",{enumerable:!0,get:function(){return An.CodeGen}});var RC=hr();Object.defineProperty(ne,"ValidationError",{enumerable:!0,get:function(){return RC.default}});var xC=fo();Object.defineProperty(ne,"MissingRefError",{enumerable:!0,get:function(){return xC.default}})});function Fs(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function we(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 Og=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Lt={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]},Ng=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Fg=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Lg=512,jg=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Dg=new Set([500,502,503,504,521,522,523,524,529]),Bg=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],qg=["upgrade your plan","upgrade plan","current plan","subscription"],Ug=["daily","weekly","monthly"],zg=["try again","retry","temporary","cooldown"],Hg=["usage limit","rate limit","organization usage"],Vg=["organization","workspace"],Gg=["billing period","exceeded","reached","exhausted"],Wg=/["']?(?: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,Kg=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function jt(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Jg(e){return jt(e,Lt.format)}function Bl(e){return jt(e,Lt.rateLimit)}function Xg(e){return jt(e,Lt.timeout)}function Yg(e){return Og.test(e)}function Ls(e){let t=e.toLowerCase();return t?e.length>Lg?Fg.test(t):jt(t,Lt.billing)?!0:Ng.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ql(e){return jt(e,Lt.authPermanent)}function Zg(e){return jt(e,Lt.auth)}function Ul(e){return jt(e,Lt.overloaded)}function Ft(e,t){return t.some(n=>e.includes(n))}function Qg(e){return Ft(e,Bg)||Ft(e,qg)&&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=Ft(e,Ug),n=e.includes("spend limit")||e.includes("spending limit"),o=Ft(e,Vg);return Ft(e,zg)&&Ft(e,Hg)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||Ft(e,Gg))}function th(e){return e.trim().toLowerCase().replace(Kg,"").trim()}function zl(e){let t=th(e);return!t||Qg(t)?"billing":Bl(t)||eh(t)?"rate_limit":"billing"}function nh(e){return Wg.test(e)?zl(e):null}function Hl(e){let t=e.match(jg);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function oh(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function rh(e){let t=e.trim();if(!t)return!1;let n=Hl(t);return n?Dg.has(n.code):!1}function Vl(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?zl(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ql(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ul(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ls(t)?"billing":"format":null}function sh(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 ih(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 Gl(e){if(ih(e))return"session_expired";if(sh(e))return"model_not_found";let t=nh(e);return t||(Yg(e)?Ls(e)?"billing":"rate_limit":Bl(e)?"rate_limit":Ul(e)?"overloaded":rh(e)?Hl(e.trim())?.code===529?"overloaded":"timeout":oh(e)?"timeout":Jg(e)?"format":Ls(e)?"billing":Xg(e)?"timeout":ql(e)?"auth_permanent":Zg(e)?"auth":null)}var ah=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Xo(e){return ah.has(e)}var ch={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 dn(e,t){let n=Vl(e,t)??(t?Gl(t):null);return n?ch[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Wl(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"]),Wn=class{constructor(t=20,n=Wl){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??"");if(!d||!lh.has(d)||c.content.length<=200)return c;let p=this.estimateTokens(c);return i+=p,s++,{...c,content:`[result cleared \u2014 ${c.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function js(e,t,n=Wl){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 Ds(){return{stages:[]}}function Bs(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Kl(e,t),i=uh(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Kl(e,t),{messages:s,stagedCount:i.length}}function qs(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:Jl(e,t),committed:n}}function Kl(e,t){return t.stages.filter(o=>o.committed).length===0?e:Jl(e,t)}function Jl(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 uh(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 p=`${i}-${i+a}`;s.has(p)||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 dh(e){return[...new Set(e.map(Yo).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Xl(e){let t=dh(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 fh(e){let t=[...new Set(e.map(Yo).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Xl(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 Yo(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 ph(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function mh(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function gh(e){if(!e.eligibility?.length)return[...e.tools];let t=mh(e.eligibility);return e.tools.filter(n=>{let o=Yo(n);if(!o)return!1;let r=t.get(o);return!r||ph(r.status)})}function hh(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 Us(e){let t=hh({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=gh({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Xl(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:fh(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=>Yo(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 yh=["stop","aborted","timeout","cancelled","interrupted","error"],bh=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Yl(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function _h(e,t){return{...e,content:[...Yl(e.content),...Yl(t.content)]}}function vh(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 Th(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=vh(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 kh(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 Ch(e){return new Set((e??yh).map(t=>t.trim().toLowerCase()))}function wh(e,t){return e?Ch(t).has(e.trim().toLowerCase()):!1}function zs(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=>kh(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,...p}=c;p.content!=null&&p.content!==""&&s.push(p);continue}if(l.length<c.tool_calls.length){s.push({...c,tool_calls:l});continue}}s.push(c)}let i=Th(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]=_h(l,c);continue}a.push(c)}return a}function Hs(e,t){return wh(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of bh)delete o[r];return o}):[...e]}function Vs(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 Gs(e,t){let n=zs(e),o=Hs(n,t);return Vs(o,t)}function Rh(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 xh(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 Sh(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ws(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 Zo(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 Qo(e){let t=[],n=zs(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=Hs(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=Vs(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:Sh({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Rh(r),completedToolCallIds:xh(r)}),recoveryActions:t}}var Eh=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ks(e){return e?Eh.has(e):!0}function Js(e){return e===429||e===529}function er(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 Q0={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function tr(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Kn=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var Zl=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ql=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),eu=3,fn=2,nr=2,tu=128e3,nu=13e3,ou=16384,ru=65536,su=3;var Xs=500,iu=3;var au=3e4,cu=3,Dt=2;var tx=50*1024,nx=500*1024,ox=500*1024*1024,rx=50*1024*1024;function Ys(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Zs(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Qs(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 ei(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 ti(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function ni(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function pn(e){return!e.attemptedThisTurn}import{createHash as Jm}from"node:crypto";import{existsSync as sn,readFileSync as os,statSync as kR}from"node:fs";function oi(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 $h=new Set(["agent","ask_user","edit","exec","patch","read","search","task","tool_schema_load","write"]);function lu(e,t){return t?.owner==="agent"&&t.family==="builtin"?!0:$h.has(e)}function Se(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?e:e.slice(t+2)}function uu(e){let t=e.indexOf("__");if(!(t<=0||t+2>=e.length))return e.slice(0,t)}function ri(e,t){return Se(e)===t}var si="tool_schema_load";function du(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 ae(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 Ph=new Set(["skill_search","skill_load","skill_resource_read","project_instructions","capability_inventory","prompt_read","tool_schema_load"]);function or(e){return e.identity.family!=="skill"&&!Ph.has(e.identity.logicalName)}function fu(e){return e.some(t=>t.status==="succeeded"&&or(t))}function pu(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 Jn(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"&&or(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 mu(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 gu(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(Mh(e,"image",s,n));return o}function Mh(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 Ih=[/<||DSML||tool_calls>/u,/<\|DSML\|>tool_calls/u,/<tool_calls?>[\s\S]*?<\/tool_calls?>/iu,/<function_calls?>[\s\S]*?<\/function_calls?>/iu],hu=["<\uFF5C\uFF5Cdsml\uFF5C\uFF5Ctool_calls>","<|dsml|>tool_calls","<tool_call","<function_call"];function yu(e){return Ih.some(t=>t.test(e))}function bu(){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(hu.some(i=>r.startsWith(i)))return e="",n=!0,"";if(hu.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 Oh=new Set(["write","edit","patch"]);function _u(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=Nh(r.function.arguments);if(!i)return s;if(Oh.has(n.toolName)){let a=Fh(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Lh(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:jh(a)})}return s}function Nh(e){try{return JSON.parse(e)}catch{return null}}function Fh(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 Lh(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 jh(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 Dh={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"},Bh=["type","role","specialization","agentType","agent_type"],qh=["task","objective","instruction","instructions","request","query"],Uh=["async","runInBackground","run_in_background"];function zh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Xn(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function vu(e){let t=e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-agent$/,"");return Dh[t]??t}function ii(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 Tu(e,t){if(e!=="agent")return{rawArguments:t,corrections:[]};let n;try{n=JSON.parse(t)}catch{return{rawArguments:t,corrections:[]}}let o=zh(n);if(!o)return{rawArguments:t,corrections:[]};let r=[],s=Xn(o.agent);if(s){let a=vu(s);a!==s&&(o.agent=a,r.push("agent-value"))}else for(let a of Bh){let c=Xn(o[a]);if(c){o.agent=vu(c),delete o[a],r.push(`${a}->agent`);break}}if(!Xn(o.prompt)){let a;for(let c of qh){let l=Xn(o[c]);if(l){o.prompt=l,delete o[c],a=c;break}}if(a)r.push(`${a}->prompt`);else{let c=Xn(o.description);c&&(o.prompt=c,r.push("description->prompt"))}}let i=ii(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 Uh){let l=ii(o[c]);if(l!==void 0){o.background=l,delete o[c],a=c;break}}if(a)r.push(`${a}->background`);else{let c=ii(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 Rp=Ig(Cp(),1),SC=new Rp.Ajv2020({allErrors:!0,allowUnionTypes:!0,strict:!1,validateFormats:!1}),wp=new WeakMap;function EC(e){let t=wp.get(e);if(t)return t;let n=SC.compile(e);return wp.set(e,n),n}function AC(e){return e.instancePath?`arguments${e.instancePath}`:e.keyword==="required"&&typeof e.params.missingProperty=="string"?`arguments/${e.params.missingProperty}`:"arguments"}function $C(e){return(e??[]).slice(0,4).map(t=>`${AC(t)} ${t.message??`violates ${t.keyword}`}`).join("; ")}function xp(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=EC(t);return r(o)?{ok:!0}:{ok:!1,error:`Tool "${e}" arguments do not match the offered schema: ${$C(r.errors)}.`}}catch(r){return{ok:!1,error:`Tool "${e}" has an invalid offered JSON Schema: ${r instanceof Error?r.message:String(r)}.`}}}var PC=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,MC=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Lr(e){if(!MC.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?IC(e.message.content).trim():"";return t.length>0&&t.length<200&&PC.test(t)}function IC(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var OC=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,NC=/(?:^|[\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,FC=/(?:^|[\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,ac=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|产出|导出|自检)/i;function Dr(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 p=d.function;a=p?.name===t&&(n===void 0||p.arguments===n);break}if(!a)continue}return s.slice(7).trim()}}}var LC=/(?:^|[,。!?;:、,.!?;:()()"'「」『』])(?:我们?)?(?:目前|暂时|现在|当前)?(?:无法|不能|没有办法|做不到|不具备|暂不支持|不支持)[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)|我们?(?:目前|暂时|现在)?没有[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)/,jC=/\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 Sp(e){let t=e.trim();return t.length===0||t.length>600?!1:LC.test(t)||jC.test(t)}function Br(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.round(e):0}function Ep(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(OC))o(i[0]);if(ac.test(s)){for(let i of s.matchAll(NC)){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(FC)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function qr(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 Zl}function Ap(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function cc(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(`
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
9
 
10
- `)):""}function lc(e,t){let n=Dr(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}
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
11
 
12
12
  \u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
13
13
  ${n}
14
14
 
15
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
16
 
17
- \u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function $p(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=uc(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
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
18
 
19
19
  `+(r?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${r}
20
20
  `:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
21
21
  ${n}
22
22
 
23
- `+s}}function Ao(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 DC=/^(?: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 Pp(e){return DC.test(e)}var BC=/^(?:pip3?|pipx|uv|conda|npm|pnpm|yarn|apt(?:-get)?|brew|choco|winget)(?:\.\w+)?$/i,qC=/^(?:[^\s]*[\\/])?(?:python[\d.]*|py)(?:\.exe)?(?:\s+-\S+)?\s+-m\s+pip\s+(?:install|download)\b/i,UC=/^(?:[^\s]*[\\/])?uv(?:\.exe)?\s+pip\s+(?:install|sync)\b/i;function Mp(e){if(!e)return!1;let t=e.replace(/\s+/g," ").trim();if(qC.test(t)||UC.test(t))return!0;let n=Ao(e),[o,r]=n.split(" ");return!o||!BC.test(o)?!1:r==="install"||r==="add"}function uc(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 dc(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 Ip(e){return e==="length"||e==="max_tokens"}function fc(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 Op(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 Np(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*Fp(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:c,sessionId:l,currentModel:d,log:p,recovery:y,onAutocompact:v}=e,h;{let _=await i.enforceToolResultBudget(t,n,l);if(h=_.messages,_.newlyReplacedCount>0){let k=_.newlyPersistedBytes??0,C=k>0?` (~${Math.max(1,Math.round(k/1024))} KB)`:"";p.info(`tool-result-budget: persisted ${_.newlyReplacedCount} oversized tool results${C}`),yield y("tool_result_budget",`${_.newlyReplacedCount} persisted${C}`)}}{let _=js(h,o);if(h=_.messages,_.removedCount>0){if(_.boundaryMessage){let k=h,C=0;for(;C<k.length&&k[C]?.role==="system";)C++;h=[...k.slice(0,C),_.boundaryMessage,...k.slice(C)]}p.info(`snip: removed ${_.removedCount} messages, freed ~${_.tokensFreed} tokens`),yield y("snip",`${_.removedCount} messages`)}}{let k=new Wn().compress(h,0);k.droppedCount>0&&(h=k.messages,p.info(`microcompact: cleared ${k.droppedCount} old tool results`),yield y("microcompact",`${k.droppedCount} old tool results cleared`))}if(h=Bs(h,r).messages,s.contextWindowTokens>0){let _=s.contextWindowTokens*.75,k=i.getActiveContextCompressionEngine(),C;k?C=await k.compressAsync(h,_,{model:d,sessionId:l}):C=i.compressMessages(h,{budget:_,model:d}),C.droppedCount>0&&(h=C.messages,p.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`},v(),ae(a,"context.after_compact",{...c,removedCount:C.droppedCount},p))}if(i.restoreRequiredContextMessages){let _=i.restoreRequiredContextMessages(t,h,n);h=_.messages,_.recoveredCount>0&&(p.info(`typed-context-budget: recovered ${_.recoveredCount} required skill context message(s)`),yield y("typed_context_recovery",`${_.recoveredCount} required skill context message(s)`))}return h=Ap(h),h}async function*Lp(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:c,emitRecovery:l}=t;if(e instanceof Kn&&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),p=typeof e?.status=="number"?e.status:void 0;if(!p&&d&&(d.includes("ECONNRESET")||d.includes("EPIPE"))){let v=(n.consecutiveApiRetries??0)+1;return v>Dt?(c.info(`stale connection retry limit reached (${Dt}), 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:v,transition:void 0}})}let y=Np({status:p,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(Js(p)){n.consecutive529Errors++;let v=2,h=r&&n.currentModel!==r;if(n.consecutive529Errors>v&&!h&&!tr())return c.info(`transient ${p} \xD7 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${p} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=cu&&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(tr()){let _=er(n.consecutive529Errors);c.info(`persistent retry: waiting ${_}ms (attempt ${n.consecutive529Errors})`);let k=_;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 (${p})`};let C=Math.min(k,au);await new Promise(E=>setTimeout(E,C)),k-=C}return{kind:"continue",patch:{transition:void 0}}}if(Ks(i)){let k=Op({status:p,message:d})??er(n.consecutive529Errors);return c.info(`transient ${p}: retry in ${k}ms`),yield l("retry",`${p} retry in ${k}ms`),await new Promise(C=>setTimeout(C,k)),{kind:"continue",patch:{transition:void 0}}}c.info(`background source ${i}: not retrying ${p}`)}return{kind:"streamError",streamError:{status:p,message:d}}}import{readdirSync as Hp,statSync as $o}from"node:fs";import{tmpdir as zC}from"node:os";function jp(e){let t=[],n=[],o=a=>{let c=pc(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,p]=l.split(" -> ");o(d),o(p)}else if(c.startsWith("--- ")){s=!0;let l=pc(c.slice(4).trim());i=l||null,l&&l!=="/dev/null"&&t.push(l)}else if(c.startsWith("+++ ")){s=!0;let l=pc(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 pc(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 HC=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|generate\s+(?:a\s+)?file|new\s+file/i,VC=/\bfix\b|implement|modify|update|repair/i,Po=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Dp=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,GC=/\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,WC=/(?:^|[\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,KC=/(?:^|[\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,JC=/(?:^|[\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,XC=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,mc=/(?: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 Vp(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function Bp(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function qp(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+${Xp(n)}\\b`,"i").test(s)}function Hr(e){return e.replace(/https?:\/\/\S+/gu," ")}var YC=/\b(?:read|analy[sz]e|inspect|review|open|load|parse|consume|input|source)\b|读取|阅读|分析|检查|查看|打开|载入|输入|源文件/gi,ZC=/\b(?:write|create|generate|save|output|produce|deliver|export|update|modify|edit)\b|写入|创建|生成|保存|输出|交付|导出|更新|修改|编辑/gi;function Up(e,t){let n=-1;for(let o of e.matchAll(t))n=o.index??n;return n}function QC(e){let t=new Set;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let o=Hr(n.content);for(let r of o.matchAll(Po)){let s=r[0],i=o.slice(0,r.index??0),a=Up(i,YC),c=Up(i,ZC);a>c&&t.add(re(s))}}return t}function Vr(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=Hr(r.content);for(let i of s.matchAll(Po)){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 p=l.slice(0,d+1);Dp.lastIndex=c;let y;for(;(y=Dp.exec(s))!==null;)o(`${p}${y[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Hr(r.content);if(!ac.test(s))continue;let i=Array.from(s.matchAll(GC)).map(d=>Vp(d[1]??"")).filter(d=>d&&!Bp(d));if(i.length===0)continue;let a=i[i.length-1],c=Array.from(s.matchAll(Po)).map(d=>({start:d.index??0,end:(d.index??0)+d[0].length})),l=d=>c.some(p=>d>=p.start&&d<p.end);for(let d of s.matchAll(WC)){let p=d[1];if(!p)continue;let y=(d.index??0)+d[0].indexOf(p);l(y)||qp(s,d.index??0,p)||o(`${a}/${p}`)}for(let d of s.matchAll(KC)){let p=d[1];if(!p)continue;let y=(d.index??0)+d[0].indexOf(p);l(y)||qp(s,d.index??0,p)||o(`${a}/${p}`)}for(let d of s.matchAll(JC)){let p=d[1];p&&(Bp(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${p}/*`))}XC.test(s)&&o(`${a}/previews/*`)}return n}function en(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function ew(e){if(!en(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 Gp(e){let t=new Set;for(let o of e){let r=o;ew(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=tn(c.arguments);typeof l?.input=="string"&&n.push(...jp(l.input).paths)}}return n}function gc(e){let t=new Set,n=new Map,o=[...Gp(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(en(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 p=JSON.parse(d.arguments);if(d.name==="write"||d.name==="edit"){for(let y of["path","filePath","file_path"]){let v=p[y];typeof v=="string"&&o.push(v)}continue}if(d.name==="exec"){let y=p.command;typeof y=="string"&&o.push(y)}}catch{d.name==="exec"&&o.push(d.arguments)}}}return o.join(`
27
- `).replace(/\\/g,"/").toLowerCase()}function Gr(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return Hp(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return $o(`${n}/${r.name}`).size>0}catch{return!1}})}let t=$o(e);return t.isFile()&&t.size>0}catch{return!1}}function tw(e,t){let n=re(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Wp(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)&&en(o))return!0}return!1}function nw(e){let t=Jp(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 ow(e){let t=Vp(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function rw(e){if(e.length===0)return"";let t=e.map(o=>ow(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 sw(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 hc(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=tn(l.arguments);if(!d)continue;let p=Mo(d);p&&n.set(c,p)}}for(let o of e){let r=o;if(!en(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 iw(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 aw(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function cw(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=tn(l.arguments);if(!d)continue;let p=Mo(d)??"",y=Yp(d);(/\bartifact[-_\s]?index\b/i.test(p)||/\bartifact[-_\s]?index\b/i.test(y))&&n.set(c,y)}}for(let o of e){let r=o;if(!en(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 lw(e){let t=Jp(e.inputMessages);if(!iw(t))return[];let n=cw(Et(e.inputMessages,e.messages)).at(-1);if(!n)return[];let o=[],r=aw(t).filter(i=>!new RegExp(`\\b${Xp(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 uw(e){let t=[],n=o=>{let r;try{r=Hp(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{$o(i).size>0&&t.push(i)}catch{}}};try{if(!$o(e).isDirectory())return[]}catch{return[]}return n(e),t}function Et(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 dw(e,t){if(!nw(e))return[];let n=Vr(e),o=n.filter(i=>!re(i).endsWith("/*"));if(o.length<2)return[];let r=rw(o);if(!r||r.split("/").length<3)return[];let s=re(r);return[...new Set([...hc(Et(e,t)),...uw(r)])].filter(i=>re(i).startsWith(`${s}/`)&&!sw(i,n)&&Gr(i))}function Kp(e,t){let n=Vr(e);if(n.length===0)return[];let o=QC(e),r=Et(e,t),s=gc(r),i=fw(r),a=pw(r);return n.filter(c=>{if(o.has(re(c))||tw(s,c))return!1;let l=re(c);return!((i.has(l)||a.has(l))&&Gr(c))})}function fw(e){let t=new Set;for(let o of e){let r=o;en(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=tn(c.arguments),d=l?Mo(l):void 0;d&&n.add(re(d))}}return n}function pw(e){let t=new Set;for(let o of e){let r=o;en(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"?Se(c.name):"";if(l!=="image_understand"&&l!=="video_understand"||typeof a.id!="string"||typeof c?.arguments!="string"||!t.has(a.id))continue;let d=tn(c.arguments);if(!d)continue;let p=l==="image_understand"?d.image_url:d.video_url;typeof p=="string"&&p.trim()&&n.add(re(p))}}return n}function Ur(e){return yc(e).fail}function mw(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function zr(e){if(!e)return!1;let t=mw(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function yc(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 Jp(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 Xp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $n(e){let t=Kp(e.inputMessages,e.messages).filter(n=>!Gr(n));if(t.length!==0)return`[Engine notice] ${e.reason}; explicitly requested output files still missing: ${t.join(", ")}.`}function tn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Mo(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Yp(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Zp(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=yc(e.inputMessages);if(!n.done)return;let o=tn(e.toolCall.function.arguments);if(!o)return;let r=Mo(o),s=Yp(o);if(!r||!s.includes(n.done))return;let i=Vr(e.inputMessages);if(i.length<2)return;let a=re(r);if(!i.some(p=>re(p)===a))return;let l=gc(e.messages),d=i.filter(p=>re(p)!==a).filter(p=>!l.includes(re(p)));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 Zt(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Qt(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Qp(e){try{return $o(e).isFile()}catch{return!1}}function gw(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(mc.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 mc.test(c)&&/(?:这个|该|此)文件|\b(?:this|that|the)\s+file\b/i.test(c)}function hw(e,t){let n=new Map;for(let i of e){if(i.role!=="user"||typeof i.content!="string")continue;let a=Hr(i.content);if(mc.test(a))for(let c of a.matchAll(Po)){if(!gw(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=gc(Et(e,t)),r=Wp(Et(e,t)),s=[];for(let[i,a]of n)(o.includes(i)||r&&Qp(a))&&s.push(i);return s}var yw="File not found:",zp=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,bw=/\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 _w(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 p=d;for(;p>0&&!o.test(s[p-1]);)p--;let y=d+c.length;for(;y<s.length&&!o.test(s[y]);)y++;let v=r.content.slice(p,y);if(zp.test(v))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(Po)).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&&zp.test(r.content)&&bw.test(r.content))return!0}return!1}function vw(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=tn(l.arguments),p=d?Mo(d):void 0;p&&t.set(c,p)}}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(yw)&&n.set(re(i),i)}return n}function Tw(e,t){let n=Et(e,t),o=vw(n);if(o.size===0)return[];let r=new Set(hc(n).map(re)),s=[];for(let[i,a]of o)_w(e,i)||(r.has(i)||Qp(a))&&s.push(i);return s}function bc(e){let t=[...e.inputMessages].reverse().find(v=>v.role==="user"),n=typeof t?.content=="string"?t.content:"",o=HC.test(n)||VC.test(n)&&Vr(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit")||Gp(Et(e.inputMessages,e.messages)).length>0,s=yc(e.inputMessages),i=s.fail!==void 0&&e.finalText.includes(s.fail)||/\bFAILED\b/.test(e.finalText),a=hw(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 v=Ur(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 ${v??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Qt("forbidden_file_creation",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let c=Tw(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 v=Ur(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 ${v??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Qt("self_created_read_target",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let l=Wp(e.messages),d=Kp(e.inputMessages,e.messages).filter(v=>!(l&&Gr(v)));if(d.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`explicit required file verification: ${d.length} file(s) missing`);let v=Ur(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 ${v??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Qt("explicit_required_file_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let p=dw(e.inputMessages,e.messages);if(p.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`explicit extra file verification: ${p.length} unexpected file(s)`);let v=Ur(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: ${p.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${v??"FAILED"} and the real reason. Do not claim completion while extra deliverables remain.`};return Qt("explicit_extra_file_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let y=lw({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 v={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 Qt("artifact_index_evidence_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),v)}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 v={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 Qt("file_action_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),v)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")){let v=[...new Set(hc(Et(e.inputMessages,e.messages)).map(re))].filter(h=>kw.test(h)&&!Cw(h));if(v.length>=3){e.log.info(`AP3 verification nudge: ${v.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 Qt("multi_file_skeleton_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}}return null}var kw=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|kts|cs|cpp|cc|c|h|hpp|vue|svelte)$/i;function Cw(e){let t=re(zC());return t.length>0&&e.startsWith(`${t}/`)}function ww(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function em(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,ww(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var _c="```final-status",Rw=/\r?\n[ \t]*```/;function xw(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 tm(){let e="",t=!1;function n(){let o="";for(;;){if(t){let s=Rw.exec(e);if(!s)return o;e=e.slice(s.index+s[0].length),t=!1;continue}let r=e.indexOf(_c);if(r===-1){let s=xw(e,_c);return o+=e.slice(0,e.length-s),e=e.slice(e.length-s),o}o+=e.slice(0,r),e=e.slice(r+_c.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 nm=5;function Sw(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Ew(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function vc(e,t){let n=e.recoveryTrace;if(!n)return;let o=`budget_continuation_stop:${t}`;n.set(o,(n.get(o)??0)+1)}function om(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=Sw(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=nm)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${nm}) at ${Math.round(n)}% used`),vc(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=iu&&o<Xs&&e.lastBudgetDeltaTokens<Xs)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),vc(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`),vc(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,Ew(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 rm}from"node:crypto";function sm(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 Mn="*";function im(e,t,n){let o=[],r=[];for(let s of e){let i=Tc(s.function.name,s.function.arguments),a=dm(s.function.name,Mn),c=Math.max(t.get(i)??0,t.get(a)??0);if(c>=nr){let l=Aw(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 Aw(e){return`${e.function.name}::${e.function.arguments}`}function am(){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 cm(e){if(e.ok){e.toolFailureCounts.delete(Tc(e.toolName,e.toolArguments));return}let t=Tc(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function lm(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=nr&&(e.snapshot.get(n)??0)<nr){let{toolName:r,target:s}=qw(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 Tc(e,t){return dm(e,$w(e,t))}function $w(e,t){let n=Bw(t);if(e==="read"||e==="write"||e==="edit"||e==="patch")return Pn(n?.path??n?.file_path??n?.filePath);if(e==="search")return Pn([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 Pn(o?Ao(o):void 0)}return Iw(n)}var Pw=["runtime_id","runtimeId","operation","action","method","resource_type","resourceType"],Mw=["kind","interactionIntent","targetRole"];function Iw(e){if(!e)return Mn;let t=Pw.flatMap(i=>typeof e[i]=="string"&&e[i].trim()?[`${i}=${Pn(e[i])}`]:[]),n=Dw(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(!um(a))continue;let c=Mw.flatMap(l=>typeof a[l]=="string"&&a[l].trim()?[`${i}.${l}=${Pn(a[l])}`]:[]);t.push(...c)}let r=Array.isArray(e.args)?jw(e.args):"";r&&t.push(`argv=${r}`);let s=Fw(e);return s&&t.push(`payloadShape=${s}`),t.push(`arguments=${Ow(e)}`),t.length>0?t.join("|"):Mn}function Ow(e){return rm("sha256").update(JSON.stringify(kc(e))).digest("hex").slice(0,24)}function kc(e){return Array.isArray(e)?e.map(kc):um(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,kc(e[t])])):e}var Nw=["stdin","input","payload","body","request","data"];function Fw(e){let t=[];for(let n of Nw)n in e&&t.push(`${n}:${Cc(Lw(e[n]))}`);if(t.length!==0)return rm("sha256").update(t.join("|")).digest("hex").slice(0,24)}function Lw(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Cc(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=>Cc(o,t+1)))].sort().join(",")}]`;if(typeof e=="object"){let n=e;return`object{${Object.keys(n).sort().map(o=>`${o}:${Cc(n[o],t+1)}`).join(",")}}`}return typeof e}function jw(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 Dw(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}=${Pn(n)}`}}function um(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Bw(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Pn(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Mn}function dm(e,t){return`${e}::${t}`}function qw(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Mn}:{toolName:e.slice(0,t),target:e.slice(t+2)||Mn}}var Ec=new Set(["write","edit","patch"]),Ac=new Set(["image_generate"]),gm=new Set(["cad_design","industrial_runtime","solidworks_create"]),Uw=/\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,zw=/\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,Hw=/\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,$c=/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,Gw=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,fm=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i,Ww=new Set(["browser_automation","frontend_test","user_confirmation","external_benchmark","fork_verify"]),Kw=/\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,Jw=/\b(?:vitest|jest|cypress|playwright|storybook|testing-library)\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|test:ui|test:component)\b/i,Xw=/\.(?:tsx|jsx)\b|testing-library|(?:render(?:ed|ing)?|screen|dom|component|dashboard|navigation|heading|button|dialog|page|ui)\b|(?:渲染|页面|界面|组件|导航|标题|按钮)/i,Yw=/\bPASS\b|(?:test files?|tests?)\s+\d+\s+passed|\b\d+\s+passed\b|(?:^|\n)\s*[✓✔]\s|(?:测试|用例).{0,12}(?:通过|成功)/i;function Zw(e){let t=Fc(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"||!Kw.test(r.content))continue;let s=(r.imageUrls?.length??0)>0||/(?:screenshot|截图)/i.test(r.content),i=`${r.content.trim()}${s?" [screenshot-backed]":""}`;Io(n,{source:"user_confirmation",status:"passed",summary:i})}return n}function Kr(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(zw.test(t.content)||Uw.test(t.content)))}var Qw=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 hm(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Qw.test(t.content))}var wc=/```final-status[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```/g,eR=new Set([...Ec,...Ac,...gm,"exec","bash","shell","powershell","terminal","playwright","browser","computer"]);function ym(e){for(let t of e)if(eR.has(Se(t)))return!0;return!1}var bm=["## 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 _m(e){wc.lastIndex=0;let t=null;for(let o=wc.exec(e);o;o=wc.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 pm(e){return"```final-status\n"+JSON.stringify(e,null,2)+"\n```"}function Pc(e,t){let n=Nc(t);if(!n)return null;let o=Se(e);if(Ec.has(o))return Wr(n.path,n.file_path,n.filePath,n.filename,n.file);if(Ac.has(o))return Wr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0);if(In(o)&&typeof n.command=="string"){let r=n.command.match(/^\s*agent-browser(?:\.exe)?\b[\s\S]*?\bscreenshot\s+(?:"([^"]+)"|'([^']+)'|(\S+))/i);return Wr(r?.[1],r?.[2],r?.[3])}return null}function vm(e){let t=Pc(e.toolName,e.rawArguments);if(!t||!Kr(e.inputMessages))return null;if(!e.state.artifactRoot){let r=Fc(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Am(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Pm(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 Tm(e){let t=Pc(e.toolName,e.rawArguments);return!t||!bR(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 Mc(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 tR(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"]),mm=/\b(?:Remove-Item|rm|del|erase|unlink)\b/i;function nR(e,t,n){if(!km.has(e)||n.length===0)return[];let o=No(t);if(!o||!mm.test(o))return[];let r=o.split(/(?:;|&&|\|\||\r?\n)/u),s=r.filter(l=>mm.test(l)).map(l=>ie(l));if(s.length===0)return[];let i=Nc(t),a=i?Wr(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 p=ie(Sc(l)),y=d.slice(d.lastIndexOf("/")+1);if(!p||!y||!c.some(h=>h.includes(p)))return!1;let v=new RegExp(`(?:^|[\\s"'=])${vR(y)}(?:$|[\\s"',])`,"i");return s.some(h=>v.test(h))})}function Cm(e){let t=Se(e.toolName),n=Pc(e.toolName,e.rawArguments),o=e.ok?tR(e.details):[],r=e.ok?[...new Set([...n?[n]:[],...o])]:[];for(let a of r){if(Ec.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=Fc(e.inputMessages);e.state.artifactRoot=c??Am(a),e.state.rootSource=c?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(a)||e.state.writePaths.push(a),Kr(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Pm(a,e.state.artifactRoot)&&Mc(e.state,{path:a,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}if(e.ok)for(let a of nR(t,e.rawArguments,e.state.writePaths))e.state.deletedPaths.some(c=>ie(c)===ie(a))||e.state.deletedPaths.push(a);if(dR(e.toolName,e.inputMessages)){let a=`${e.rawArguments}
29
- ${e.content}`;for(let c of a.matchAll($c)){let l=Oo(c[0]);l&&(e.state.devServerUrls.includes(l)||e.state.devServerUrls.push(l))}}let s=No(e.rawArguments);!(e.ok&&/^\s*agent-browser(?:\.exe)?\b[\s\S]*?\bclose\s*$/i.test(s)&&/\bbrowser closed\b/i.test(e.content))&&mR(e.toolName,e.rawArguments,e.content)&&Lc(e.content)&&Io(e.state,{source:"browser_automation",status:"failed",summary:e.content}),e.ok&&uR(e.toolName,e.rawArguments,e.content)&&Io(e.state,{source:"browser_automation",status:"passed",summary:e.content}),e.ok&&fR(e.toolName,e.rawArguments,e.content)&&Io(e.state,{source:"frontend_test",status:"passed",summary:e.content});for(let a of pR(e.details))!e.ok&&a.status==="passed"||Io(e.state,a);if(hR(e.toolName,e.rawArguments))if(!e.ok||$m(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 Io(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 Ic(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:Kr(t)}}function wm(e){let t=Zw(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Oc(t,n.content);return t.recoveredBaseline={writePaths:t.writePaths.length,devServerUrls:t.devServerUrls.length,artifactRoot:!!t.artifactRoot},t}function Oc(e,t){let n=_m(t)?.claim?.artifacts;if(n){typeof n.root=="string"&&n.root&&!e.artifactRoot&&(e.artifactRoot=mt(n.root),e.rootSource="inferred");for(let o of n.files??[]){if(typeof o!="string")continue;let r=mt(o.trim());r&&!e.writePaths.includes(r)&&e.writePaths.push(r)}for(let o of n.urls??[]){if(typeof o!="string")continue;let r=Oo(o);r&&!e.devServerUrls.includes(r)&&e.devServerUrls.push(r)}}for(let o of t.matchAll($c)){let r=Oo(o[0]);r&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(r)&&(e.devServerUrls.includes(r)||e.devServerUrls.push(r))}}var oR=/[一-鿿]/;function Rm(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(!(n.role!=="user"||typeof n.content!="string"))return oR.test(n.content)?"zh":"en"}return"en"}var rR={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 xm(e){let t=e.content.trim();if(!e.contractActive)return{content:t,malformedBlock:!1,notices:[]};let n=_m(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}=sR(n.claim,c,e);return{content:[i,pm(l),a].filter(Boolean).join(`
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
31
 
32
- `),malformedBlock:!1,notices:d}}let o=n!==null;if(_R(t)&&e.totalToolCallCount===0)return{content:t,malformedBlock:o,notices:[]};let r=iR(e);if(!r)return{content:t,malformedBlock:o,notices:[]};let s=pm(r);return{content:t?`${t}
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
33
 
34
- ${s}`:s,malformedBlock:o,notices:[]}}function sR(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=Sm(n.activeTasks??[]);if(i.length>0&&(s.done?.length??0)>0){let l=[...s.notDone??[]];for(let d of i){let p=`Task ${Em(d)} is unresolved.`;l.includes(p)||l.push(p)}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=>!Rc(l)&&!xc(o,l));if((s.artifacts?.files?.length??0)>0||c.length>0){let l=o.writePaths.filter(C=>!Rc(C)&&!xc(o,C)).map(ie),d=typeof s.artifacts?.root=="string"&&s.artifacts.root?s.artifacts.root:o.artifactRoot,p=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??[],v=y.filter(C=>typeof C=="string"&&p(C)),h=y.length-v.length;h>0&&(s.artifacts={...s.artifacts,files:v},r.push(`${h} artifact file claim(s) removed \u2014 not present in the active write ledger.`));let _=0;for(let C of c){let E=mt(C),O=ie(E);v.some(M=>{let Q=ie(M);return Q===O||d&&ie(`${d}/${M}`)===O?!0:O.endsWith(`/${Q}`)})||(v.push(E),_+=1)}let k={...s.artifacts??{},files:v};!k.root&&o.artifactRoot&&(k.root=mt(o.artifactRoot)),s.artifacts=k,_>0&&r.push(`${_} artifact file(s) added from this turn's write ledger.`)}if(s.sources?.cited?.length){let l=new Set([...lR(t),...o.devServerUrls]),d=[];for(let y of s.sources.cited){if(typeof y!="string")continue;let v=Oo(y);v&&l.has(v)&&!d.includes(v)&&d.push(v)}let p=s.sources.cited.length-d.length;p>0&&(s.sources={...s.sources,cited:d},r.push(`${p} cited source(s) removed \u2014 not seen in this turn's response or tool results.`))}return{claim:s,notices:r}}function iR(e){let t=e.artifactContract,n=rR[e.locale??"en"],o=Sm(e.activeTasks??[]),r=e.forcedStop?cR(e.blockedToolCalls??[]):[],s=t.recoveredBaseline??{writePaths:0,devServerUrls:0,artifactRoot:!1},i=t.writePaths.slice(s.writePaths).filter(k=>!Rc(k)&&!xc(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(Em).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 p=e.visibleToolCallCount??e.totalToolCallCount,y=[...e.visibleToolNames??e.distinctToolNames],h={schema:1,author:"engine",done:[p>0?n.doneRan(p,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 _={};return t.artifactRoot&&(_.root=mt(t.artifactRoot)),i.length>0&&(_.files=i.slice(0,8).map(mt)),a.length>0&&(_.urls=[...a]),Object.keys(_).length>0&&(h.artifacts=_),h}function Sm(e){return e.filter(t=>t.status!=="completed")}function Em(e){return`#${e.id} ${e.title} (${e.status})`}var aR=new Set(["artifact-root-contract","identical-repeat-policy","invalid-arguments","not-offered","read-only-context-pack","tool-call-budget","variant-failure-policy"]);function cR(e){return e.filter(t=>aR.has(t.reason))}function lR(e){let t=[];for(let n of e.matchAll($c)){let o=Oo(n[0]);o&&!t.includes(o)&&t.push(o)}return t}function Nc(e){try{return JSON.parse(e)}catch{return null}}function Wr(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function Fc(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(Hw)){let o=n[1]??n[2],r=Jr(o??"");if(r&&!yR(r))return mt(r)}}function Am(e){let t=mt(Jr(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Sc(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 Sc(t)}function uR(e,t,n){let o=Se(e);if(!(In(o)||/^(?:preview_browser|computer_(?:act|observe)|browser(?:_.+)?)$/i.test(o))||/^read$/i.test(o)||n.includes("<persisted-output>")||Lc(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=No(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=fm.test(n),a=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
35
- ${n}`),c=In(e)&&fm.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)||Gw.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function dR(e,t){let n=Se(e);return km.has(n)||Ac.has(n)||gm.has(n)||n==="send_file"?!0:Kr(t)&&/^(?:playwright|browser|computer|preview_browser|computer_(?:act|observe)|browser_.+)$/i.test(n)}function fR(e,t,n){if(!In(e))return!1;let o=No(t)||t;return!Jw.test(o)||!Xw.test(`${o}
36
- ${n}`)||$m(n)||Lc(n)?!1:Yw.test(n)}function pR(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"||!Ww.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 mR(e,t,n){return/^read$/i.test(e)||!In(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 Lc(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 In(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var gR=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 No(e){let t=Nc(e);return t&&typeof t.command=="string"?t.command:""}function hR(e,t){return In(e)?gR.test(No(t)):!1}function $m(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function yR(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Pm(e,t){let n=ie(e),o=ie(t);return n===o||n.startsWith(`${o}/`)}function bR(e){return ie(e).split("/").includes("context-pack")}function Rc(e){return ie(e).split("/").includes(".qla-tmp")}function xc(e,t){let n=ie(t);return e.deletedPaths.some(o=>ie(o)===n)}function ie(e){return Jr(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function mt(e){return Jr(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function Oo(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 Jr(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function _R(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Sc(e){let t=mt(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function vR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function CR(e,t){if(e.length!==1||!ri(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 wR(e,t){let n=RR(t);if(!n)return null;let o=xR(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]
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
37
  AUDIO_STT_RESULT ${i[1]} ${o}`:`[transcription]
38
- ${o}`}function RR(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 xR(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function I(e){return[...new Set(e.map(t=>t.function.name))].sort()}function Xr(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 SR(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>Mm(i.reason)-Mm(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 Mm(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 Im(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=Qm(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 ER(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 Qr(e){return lu(e.function.name,e.meta?.identity)}function nn(e,t){let n=new Map(e.map(o=>[o.function.name,o]));for(let o of t)Qr(o)&&n.set(o.function.name,o);return[...n.values()]}function gt(e,...t){return e.filter(n=>Qr(n)||t.every(o=>!o.has(n.function.name)))}function Om(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function AR(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 $R(e){let n=tt(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var es=5174;function Nm(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 PR(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 Xm(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function MR(e){if(Xm(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 Fm(e,t){let n=tt(e)??{};return JSON.stringify({...n,command:t})}function IR(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function OR(e){return Nm(e,es)?{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."}:PR(e)&&Nm(e,es-1)&&!Xm(e)?{action:"rewrite",command:MR(e)}:null}function NR(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:
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
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 Ym(e){let n=tt(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var Lm=4;function FR(e,t){if(/^(?:write|edit|patch)$/i.test(e)){let n=tt(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=Ym(t);if(!n||Mp(n))return null;let o=Ao(n);return Pp(o)?null:`exec:${o}`}return null}function jm(e){let t=Ym(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function LR(){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 jR(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 DR(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function Dm(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=>SR(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
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}
41
42
 
42
43
  Tool availability diagnostics:
43
44
  availableToolNames: ${t.availableToolNames.join(", ")}
44
45
  enabledToolNames: ${t.enabledToolNames.join(", ")}
45
46
  toolCallNames: ${t.toolCallNames.join(", ")||"none"}
46
47
  blockedToolCalls: ${n}
47
- attribution: ${r}`}function Me(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Bc(e,t){if(!e)return null;let n=Me(e.function.parameters),o=Me(n?.properties)??{},r=Array.isArray(n?.required)?n.required.filter(a=>typeof a=="string"&&a.trim().length>0):[],s=tt(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.${qR(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=xp(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 Bm(e,t){let n=Me(e.function.parameters),o=Me(n?.properties),r=tt(t);if(!n||!o||!r||Bc(e,t)||Object.keys(r).some(s=>!Object.hasOwn(o,s)))return!1;for(let[s,i]of Object.entries(r)){let a=Me(o[s]);if(!a)continue;let c=a.type;if(c==="string"&&typeof i!="string"||c==="array"&&!Array.isArray(i)||c==="object"&&Me(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 BR(e,t){let n=t.find(r=>r.function.name===e.function.name);if(!n||Bm(n,e.function.arguments))return{call:e};let o=t.filter(r=>r.function.name!==e.function.name&&Bm(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 qR(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 UR=new Set(["astraclaw","astraclaw_developer","astraclaw_media","astraclaw_memory","astraclaw_workflow"]);function qm(e,t){let n=e?.meta?.identity;if(n?.schemaVersion===1&&n.wireName===t)return n;let o=e?.meta?.category,r=Se(t),s=uu(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&&UR.has(s)?"host":"agent";return{schemaVersion:1,wireName:t,logicalName:r,family:a,owner:c,...s?{serverId:s}:{},capabilityId:`${c}:${s??"native"}:${r}`}}function Zr(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function zR(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Zm(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 Qm(e){for(let t of Zm(e)){let n=t.outcome??t.status;if(n==="committed"||n==="not-applied"||n==="indeterminate")return n}}function HR(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e.mcpExecutionControl;if((!n||typeof n!="object"||Array.isArray(n))&&(n=Zm(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=>Gc(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 Gc(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]/gu,"_")}function jc(e,t){return t.allowedNextTools.includes(Gc(Se(e)))}function Um(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.
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.
48
49
  `+e.join(`
49
- `)}}function zm(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 Hm(e,t){if(e.function.name!=="task")return!1;let n=tt(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&rn(t).has(o)}function VR(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"&&Zr(e.details,"running")===!0}var GR=180,WR=12,Vm=12;function KR(e){return Math.min(5e3,250*2**Math.max(0,e))}function JR(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function XR(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 rn(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function YR(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 qc=new Set(["read","search"]),ZR=new Set(["write","edit","patch","image_generate"]),QR=18e4,e0=3,Fo=1,t0=1,n0=1,o0=4,r0=2,Fe=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),Wc=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),eg=[{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}],Uc=new Set(["write","edit","patch"]),s0=new Set(["read","search","exec"]);function tg(e){let t=Te(e),n=At(t);return t.split("/").includes("context-pack")&&Fe.has(n)?Fo:t.split("/").includes("benchmark-state")&&Wc.has(n)?n0:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?t0:e0}function Gm(e){try{let t=kR(e);return t.isFile()?{mtimeMs:t.mtimeMs,sizeBytes:t.size}:null}catch{return null}}function Dc(e){let t=Te(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")&&Wc.has(At(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 Kc(e){let t=Te(e);return t.split("/").includes("context-pack")&&Fe.has(At(t))}function ng(e){let t=Te(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function i0(e){let t=[...e].filter(Kc).map(ng).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 og(e){return[...Fe.keys()].every(t=>e.has(t))}function Jc(e){for(let t of e.values()){if(!t.path)continue;let n=ng(t.path);if(n)return`${n}/benchmark-state`}return null}function rg(e){if(!og(e))return[];let t=Jc(e);return t?[...Wc].map(n=>`${t}/${n}`).filter(n=>{try{return!sn(n)}catch{return!0}}):[]}function a0(e,t){let n=rg(e);if(n.length===0)return null;let o=Jc(e);if(!o)return null;let s=[...Fe.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(`
50
- `),i=eg.map(a=>`${a.id}: ${a.decision}`).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(`
51
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(`
52
- `)}function Wm(e){return Uc.has(e)}function c0(e){return e.longHorizonStateMaintenanceRequiredFiles.size>0&&[...e.longHorizonStateMaintenanceRequiredFiles].every(t=>l0(e,t))}function l0(e,t){if(e.longHorizonStateMaintenanceWrittenFiles.has(t))return!0;try{if(!sn(t))return!1;let n=At(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=os(t,"utf8");return Xc(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function Xc(e,t,n){let o=At(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=R0(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=tt(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=Me(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let c of Fe.keys()){let l=e.get(c),d=Me(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=Me(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Fe.keys()){let c=e.get(a),l=Me(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 u0(e){if(!og(e))return[];let t=Jc(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=os(r,"utf8")}catch{continue}let i=Xc(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function d0(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(Kc).map(At));return[...Fe.keys()].every(a=>s.has(a))?[...Fe.keys()].every(a=>o.has(a))||n||i0(t):!1}function sg(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=ns(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 ts=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*f0(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 ts(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function zc(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 ns(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 p0(e){return e.flatMap(t=>{if(m0(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 m0(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=tt(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 tt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Te(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 At(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Yc(e){return`sha256:${Jm("sha256").update(e).digest("hex")}`}function h0(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 y0(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function b0(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=eg.map(c=>({...c,evidence:`read:long-horizon-documents:${Yc(`${c.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Fo,observedReadsByPath:y0(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function _0(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Yr(e,t){return e.get(t)??null}function v0(e){let t=Yr(e,"requirements.md"),n=Yr(e,"decisions.md"),o=Yr(e,"defects.md"),r=Yr(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:_0(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 T0(e,t){let n=v0(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 k0(e,t,n,o,r){let s=Hc(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function Hc(e,t,n,o){let r=At(e);if(!Fe.has(r))return null;let s=S0(t)??t,i=x0(o,"contentHash"),a=On(o??null,"fileSizeBytes"),c=i??Yc(s);return{name:r,path:Te(e),indexed:!0,maintained:!0,indexVersion:c,contentHash:c,summary:h0(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:ig(s)}}function C0(e,t){return sg(e.function.name,e.function.arguments,t)!==null}function w0(e,t){let n=ns(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 R0(e){let n=tt(e)?.content;return typeof n=="string"?n:void 0}function x0(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function ig(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function S0(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)?os(n,"utf8"):null}catch{return null}}function E0(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=zc(i.function.arguments);if(!a)continue;let c=Te(a);tg(c)===Fo&&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=Hc(i.path,a,0);c?.name&&o.set(c.name,c)}for(let s of I0(e)){r=!0;for(let i of Fe.keys()){let a=Te(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,Fo)),!o.has(i)){let c=Hc(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 A0(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Fo)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedLongHorizonStateRecovered:r}}function A0(e){let t=[];for(let n of $0(e)){let o=Km(`${n}/document-index.json`),r=Km(`${n}/context-pack-evidence.json`),s=Nn(o,"contextPackPath")??P0(r);if(!s)continue;let i=M0(s,o,r);i.length===Fe.size&&t.push({documents:i})}return t}function $0(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=Te(s[1]??"");i&&t.add(i)}}return[...t]}function Km(e){try{if(!sn(e))return null;let t=JSON.parse(os(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Nn(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?Te(n):void 0}function P0(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of Fe.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=Nn(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function M0(e,t,n){let o=Me(t?.documents),r=Me(n?.fileVerification),s=[];for(let i of Fe.keys()){let a=Me(o?.[i]),c=Me(r?.[i]);if(!a&&!c)return[];let l=Nn(a,"path"),p=Nn(c,"path")??(l?.includes("/context-pack/")?l:Te(`${e}/${i}`)),y=Nn(a,"contentHash")??Nn(c,"contentHash")??Yc(`${i}:${p}`),v=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:Te(p),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??y),contentHash:y,summary:v,lastReviewedTurn:Vc(a,"lastReviewedTurn")??Vc(n,"turn")??0,fileSizeBytes:On(a,"fileSizeBytes")??On(c,"fileSizeBytes")??On(c,"sizeBytes")??Buffer.byteLength(v,"utf8"),recordCount:On(a,"recordCount")??On(c,"recordCount")??ig(v)})}return s}function Vc(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function On(e,t){let n=Vc(e,t);return n&&n>0?n:void 0}function I0(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=Te(i[1]??"");a&&n.add(a)}}return[...n]}function O0(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));qc.has(n)&&(e.identicalCallCounts.delete(t),e.identicalFailureCounts.delete(t))}}async function*ag(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:c,model:l,apiKey:d,temperature:p=0,hooks:y,signal:v}=e,h=(b,H)=>{b.push(H)},_={sessionId:s,turnId:r},k=e.maxTurns??0,C=e.querySource,E=a??c,O=e.runtimePorts.resolveToolEligibility(E,e.toolEligibilityContext),U=new Set(c.map(b=>b.function.name)),M=nn(O.eligibleTools,E),Q=new Map(M.map(b=>[b.function.name,b])),Ie=nn(O.eligibleTools.filter(b=>U.has(b.function.name)),E),ee=[];for(let b of O.blockedTools){let H=E.find(oe=>oe.function.name===b.toolName);H&&Qr(H)||(ee.push({name:b.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:b.toolName,reason:"blocked-by-policy"})}let Ge=Br(e.maxRounds,i),nt=qr(e.maxToolCalls),an=Ep(i),at={contextWindowTokens:e.contextWindowTokens??tu,responseBufferTokens:nu,maxOutputTokens:e.maxOutputTokens??ou,abortSignal:v,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},Oe=new Set,ct=[],Zc=new Map,$t=0,Qc=new Set,el=0,rs=new Map,tl=new Set,We,Fn=!1,Ln=!1,ss=new Set,Le=new Set,Lo=new Set(e.deferredToolNames??[]),cn=new Set;for(let b of e.loadedDeferredToolNames??[])Lo.has(b)&&Q.has(b)?cn.add(b):e.loadedDeferredToolNames?.delete(b);let Ke=()=>{let b=new Map(Ie.map(H=>[H.function.name,H]));for(let H of cn){let oe=Q.get(H);oe&&b.set(H,oe)}return[...b.values()]},nl=(b,H)=>H?b.filter(oe=>H.has(oe.function.name)):[...b],x=Ke(),jn=!1,is,as=()=>I(x),ug=CR(Ie,i),cs=!1,ol=0,rl=0,ls=0,sl=0,il=0,al=new Set,Dn=new Map,ge=!1,Bn=!1,us=E0(i),f={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ys(at),reactiveCompactState:ni(),toolLoopState:Qo({maxRounds:Ge,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ds(),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:us.fileReadCounts,fileReadSignatures:new Map,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:us.maintainedDocuments,persistedLongHorizonStateRecovered:us.persistedLongHorizonStateRecovered,longHorizonStateMaintenanceRequiredFiles:new Set,longHorizonStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:wm(i),buildVerificationRecoveryCount:0,longHorizonStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentPollCounts:new Map,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},dg=4,fg=4,cl=0,ds=!1,ll=new Map,fs,z=(b,H)=>{let oe=`${b}:${H??""}`,ue=(ll.get(oe)??0)+1;if(ll.set(oe,ue),b==="autocompact"){let J=f.recoveryTrace.get("autocompact")??0;if(ue>dg||J>=fg){let De=`Repeated context compression made no forward progress: ${H??"autocompact"}`;return fs=De,f.recoveryTrace.set("compression_loop_guard",(f.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:De}}}return f.recoveryTrace.set(b,(f.recoveryTrace.get(b)??0)+1),{type:"recovery",turnId:r,action:b,detail:H}},Pt={roleAlias:0,promptAlias:0,backgroundAlias:0,agentValue:0,backgroundValue:0},ul=b=>({type:"tool_use_summary",turnId:r,ledgerSchemaVersion:4,toolCalls:ct.map(H=>({...H})),finalAnswerEvidence:b,availableToolNames:I(a??c),enabledToolNames:as(),toolCallNames:[...Oe].sort(),blockedToolCalls:Xr(ee),...Object.values(Pt).some(H=>H>0)?{argumentCorrections:{...Pt}}:{}}),dl=ym((a??c).map(b=>b.function.name)),ps=!1,jo=Rm(i),pg=b=>({type:"end",turnId:r,content:b,usage:f.totalUsage,model:f.currentModel,...f.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(f.recoveryTrace)}:{}});function*je(b,H){let oe=Jn(e.freshEvidenceRequired===!0,ct,[]),ue=oe.disposition.startsWith("blocked-")?ER(oe,jo):b,J=xm({content:ue,contractActive:dl,totalToolCallCount:$t,distinctToolNames:Oe,visibleToolCallCount:el,visibleToolNames:Qc,artifactContract:f.artifactContract,blockedToolCalls:Xr(ee),activeTasks:f.lastTaskList,forcedStop:H?.forcedStop??ps,locale:jo});J.malformedBlock&&(yield z("final_status_block_malformed","final-status block was not valid schema-1 JSON; treated as absent")),Oc(f.artifactContract,J.content),gs()&&(yield ms()),yield ul(oe),yield pg(J.content)}function*Je(b,H){let oe=Jn(e.freshEvidenceRequired===!0,ct,[]);yield ul(oe),yield{type:"error",turnId:r,error:b,code:H,usage:f.totalUsage}}let ms=()=>({type:"artifact_contract",turnId:r,...Ic(f.artifactContract,i)}),gs=()=>{let b=Ic(f.artifactContract,i);return!!(b.requiresBrowserAcceptance||b.artifactRoot||b.writePaths.length>0||b.outOfRootWrites.length>0||b.devServerUrls.length>0||b.browserVerified)},Do=(b,H,oe)=>{if(oe?.cleanStopWithFinalText&&f.finalText)return f.finalText;ps=!0;let ue=f.finalText||cc(b,o),J=jo==="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 ue?`${J}
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}
53
54
 
54
- ${ue}`:J},mg=(b,H,oe)=>{ps=!0;let ue=b||cc(H,o),J=$n({inputMessages:i,messages:H,reason:oe});return J?ue?`${ue}
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}
55
56
 
56
- ${J}`:J:ue},qn=0,Bo=0;function*gg(b){qn<=Bo||(yield{type:"text_rollback",turnId:r,keepLength:Bo,reason:b},qn=Bo)}for(x=gt(Ke(),Le);;){yield*gg("round_restart"),cl++,ds=!1;let{messages:b,maxOutputTokensRecoveryCount:H,maxOutputTokensOverride:oe,turnCount:ue,guardState:J,reactiveCompactState:De,collapseStore:hs}=f,{toolLoopState:Be}=f;if(e.refreshTools&&cl>1){let u=e.refreshTools(),m=new Set(u.map($=>$.function.name)),T=nl(M.filter($=>!Lo.has($.function.name)||cn.has($.function.name)),m),g=nn(gt(T,Le),Ke());g!==x&&(x=g,o.debug(`tools refreshed within initial turn snapshot: ${T.length}/${M.length} tools`))}if(We&&(x=x.filter(u=>jc(u.function.name,We))),e.drainPendingGuidance)for(let u of e.drainPendingGuidance()){let m=u.trim();m&&(b.push({role:"user",content:m}),o.info(`mid-turn guidance injected (${m.length} chars)`))}if(e.drainPendingTaskNotifications){let u=e.drainPendingTaskNotifications().filter(m=>m.trim());u.length>0&&(zm(f,u),b.push(Um(u)),o.info(`background task result injected (${u.length} item(s))`))}if(ti(J,at)){o.info(`turn aborted by guard at turn ${ue}`),yield*Je("Turn aborted","ABORTED");return}let ys=!1,ht=yield*Fp({messages:b,contentReplacementState:f.contentReplacementState,snipRemovedIds:f.snipRemovedIds,collapseStore:hs,guardState:J,guardConfig:at,runtimePorts:e.runtimePorts,hooks:y,hookCtx:_,sessionId:s,currentModel:f.currentModel,log:o,recovery:(u,m)=>(ys=!0,z(u,m)),onAutocompact:()=>{f.hasAttemptedReactiveCompact=!1}});if(ht.length<b.length&&(ys=!0),ht!==b&&b.splice(0,b.length,...ht),fs){yield*je(`${fs}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`,{forcedStop:!0});return}let Mt=Zs(J,at);if(Mt.level==="blocking")if(Mt.reason==="prompt_too_long"&&ys&&pn(De))De.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,f.hasAttemptedReactiveCompact=!0,b.splice(0,b.length,...ht),o.info("token budget blocking (prompt_too_long), retrying with compacted history"),yield z("reactive_compact","token budget pre-check: history compressed");else{o.info(`token budget blocking (${Mt.reason}), ending tool loop`);let m=Do(f.messages,`token budget exhausted (${Mt.reason}) before the request could be completed`);yield*je(m);return}Mt.level==="warning"&&o.info(`token budget warning: ${Mt.usagePercent}% used, ${Mt.remainingTokens} remaining`);for(let u of Ie)Qr(u)&&Le.delete(u.function.name);x=nn(x,Ke());let fl=ge?"required":e.toolChoice==="required"&&cs?"auto":e.toolChoice??"auto";ge=!1;let yt=Us({tools:x,toolChoice:fl}),pl=Jm("sha256").update(JSON.stringify([...yt.tools].sort((u,m)=>u.function.name.localeCompare(m.function.name)))).digest("hex"),ml=is!==void 0&&is!==pl;ml&&f.lastResponseId&&(yield z("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let gl=Bn||ml?void 0:f.lastResponseId;is=pl;let Un=Qo({maxRounds:Ge,replayMessages:ht,lastStopReason:Be.lastStopReason,options:{stopReason:Be.lastStopReason}}),hl=[yt.extraSystemPrompt,dl?bm:void 0].filter(u=>!!u).join(`
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(`
57
58
 
58
- `),yl=hl?[{role:"system",content:hl},...Un.state.replayMessages]:Un.state.replayMessages;Be=Un.state,Un.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Un.recoveryActions.map(u=>u.detail??u.kind).join("; ")}`),o.debug(`turn ${ue}, messages: ${yl.length}`),ae(y,"turn.before_inference",{..._,model:f.currentModel},o);let qo=!1,bl=[],_l=fl==="required"||e.freshEvidenceRequired===!0&&$t===0&&ls===0,bs=tm(),_s=e.toolChoice==="none"?bu():null,vl=0;function*hg(u){if(_l||!u)return;let m=_s?_s.push(u):u,T=bs.push(m);T&&(vl+=T.length,qn+=T.length,yield{type:"delta",turnId:r,text:T})}function*yg(){if(_l)return;let u=_s?.flush()??"",T=(u?bs.push(u):"")+bs.flush();T&&(vl+=T.length,qn+=T.length,yield{type:"delta",turnId:r,text:T})}let Tl=new Map,kl="stop",he,K=null,Uo=null,bg=performance.now(),vs,zo=!1,Cl=!1,ln=[],ot=[];try{let u=t.stream({model:f.currentModel,messages:yl,...yt.tools.length>0?{tools:yt.tools,toolChoice:yt.normalizedToolChoice??"auto"}:{},temperature:p,maxTokens:(oe??J.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:gl,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:nt,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},d,v);for await(let m of f0(u,e.llmStreamIdleTimeoutMs??QR))switch(vs===void 0&&m.type!=="usage"&&m.type!=="response_id"&&(vs=Math.max(0,Math.round(performance.now()-bg))),m.type){case"delta":bl.push(m.text),yield*hg(m.text);break;case"tool_call_delta":qo=!0,oi(Tl,m);break;case"reasoning_delta":ln.push(m.text);break;case"reasoning_block_complete":m.signature&&ot.push({thinking:ln.join(""),signature:m.signature}),ln.length=0;break;case"usage":he={inputTokens:m.promptTokens,outputTokens:m.completionTokens,reasoningTokens:m.reasoningTokens,cacheRead:m.cacheReadTokens,cacheWrite:m.cacheCreationTokens};break;case"response_id":Bn||(f.lastResponseId=m.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:m.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${m.toolType}: ${m.event}`};break;case"error":Uo=m.message||"LLM provider returned an error chunk";break;case"done":Cl=!0,kl=m.finishReason;break}if(yield*yg(),Uo){ae(y,"stop.failure",{sessionId:s,reason:"PROVIDER_STREAM_ERROR",error:Uo},o),yield*Je(Uo,"PROVIDER_STREAM_ERROR");return}if(qo||ae(y,"turn.after_inference",{..._,model:f.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let m=f.currentModel;for(let T of e.postSamplingHooks)try{T({messages:[...ht],model:m,sessionId:s})}catch{}}}catch(u){if(u instanceof ts){ae(y,"stop.failure",{sessionId:s,reason:u.code,error:u.message},o),yield*Je(u.message,u.code);return}let m=yield*Lp(u,{state:f,guardState:J,fallbackModel:e.fallbackModel,signal:v,querySource:C,turnId:r,log:o,emitRecovery:z});if(m.kind==="return")return;if(m.kind==="continue"){f={...f,...m.patch};continue}K=m.streamError}if(!K&&!Cl){let u="LLM stream closed before a terminal event; the response was likely truncated upstream.";ae(y,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:u},o),yield*Je(u,"RETRYABLE_TRANSIENT");return}if(K&&ae(y,"turn.after_inference",{..._,model:f.currentModel,response:{error:K.message}},o),K){if(!Bn&&f.lastResponseId&&/previous_response_id not found/i.test(K.message)){let u=(f.consecutiveApiRetries??0)+1;if(u<=Dt){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield z("stateless_retry","previous_response_id not found; replaying full history"),Bn=!0,f={...f,lastResponseId:void 0,consecutiveApiRetries:u,transition:void 0};continue}}if(dc(K))zo=!0,o.info(`withheld prompt_too_long error (status=${K.status})`);else if(fc(K))zo=!0,o.info(`withheld media_size error (status=${K.status})`);else{let u=Qs({status:K.status??500,message:K.message},J,at);if(u.action==="reactive_compact"&&pn(De)&&(De.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,yield z("reactive_compact",`API ${K.status??500}: ${K.message}`)),u.action==="retry"){let T=(f.consecutiveApiRetries??0)+1;if(T>Dt){o.info(`API retry limit reached (${Dt}), aborting`);let g=dn(K.status,K.message);yield*Je(K.message,g);return}yield z("retry",u.reason),f={...f,consecutiveApiRetries:T,transition:void 0};continue}let m=dn(K.status,K.message);ae(y,"stop.failure",{sessionId:s,reason:m,error:K.message},o),yield*Je(K.message,m);return}}he&&(f.totalUsage.inputTokens+=he.inputTokens,f.totalUsage.outputTokens+=he.outputTokens,he.reasoningTokens&&(f.totalUsage.reasoningTokens=(f.totalUsage.reasoningTokens??0)+he.reasoningTokens),he.cacheRead&&(f.totalUsage.cacheRead=(f.totalUsage.cacheRead??0)+he.cacheRead),he.cacheWrite&&(f.totalUsage.cacheWrite=(f.totalUsage.cacheWrite??0)+he.cacheWrite)),o.info(`[provider-context] ${JSON.stringify({event:"context_ledger_round",turnId:r,round:ue,ttftMs:vs,inputTokens:he?.inputTokens??0,outputTokens:he?.outputTokens??0,cacheReadTokens:he?.cacheRead??0,cacheWriteTokens:he?.cacheWrite??0,previousResponseIdUsed:gl!==void 0,toolDefinitionCount:x.length})}`),he?.inputTokens&&(J.promptTokens=he.inputTokens);let ye=bl.join(""),ce=[...Tl.values()].map((u,m)=>({id:u.id||`tc_${r}_${ue}_${m}`,type:"function",function:{name:u.name,arguments:u.arguments}}));ce=p0(ce),ce=ce.map(u=>{let m=Tu(u.function.name,u.function.arguments);if(m.corrections.length===0)return u;for(let T of m.corrections)T==="agent-value"?Pt.agentValue+=1:T==="background-value"?Pt.backgroundValue+=1:T.endsWith("->agent")?Pt.roleAlias+=1:T.endsWith("->prompt")?Pt.promptAlias+=1:T.endsWith("->background")&&(Pt.backgroundAlias+=1);return o.info({event:"tool_argument_normalized",toolName:u.function.name,corrections:m.corrections,turnId:r},`host normalized ${u.function.name} arguments`),{...u,function:{...u.function,arguments:m.rawArguments}}});let wl=[];ce=ce.map(u=>{let m=BR(u,yt.tools);return m.originalName&&(wl.push({originalName:m.originalName,reboundName:m.call.function.name,callId:m.call.id}),o.warn({event:"tool_call_schema_rebound",turnId:r,callId:m.call.id,originalName:m.originalName,reboundName:m.call.function.name},"rebound malformed tool call to its unique declared schema")),m.call});for(let u of wl)yield z("unique_schema_tool_rebind",`${u.callId}:${u.originalName}->${u.reboundName}`);let bt=ce.flatMap(u=>{let m=yt.tools.find(g=>g.function.name===u.function.name),T=Bc(m,u.function.arguments);return T?[{call:u,error:T}]:[]});if(bt.length>0){for(let{call:m}of bt){let T=`${m.function.name}::${m.function.arguments}`;Dn.set(T,(Dn.get(T)??0)+1)}let u=bt.map(({call:m,error:T})=>`${m.function.name}:${m.function.arguments}:${T}`).sort().join("\0");if(!al.has(u)){al.add(u),Bn=!0,ge=!0;for(let{call:T}of bt)Oe.add(T.function.name);let m=bt.map(({call:T,error:g})=>`${T.function.name} (${T.id}): ${g}`).join(`
59
- `);o.warn({event:"tool_schema_preflight_rejected",turnId:r,rejectedCallCount:bt.length,rejectedToolNames:bt.map(({call:T})=>T.function.name)},"rejected a malformed tool batch before execution"),yield z("tool_schema_preflight_retry",`${bt.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.
60
- `+m}],finalText:"",transition:{reason:"next_turn"}};continue}}if(e.toolChoice==="none"&&ce.length===0&&yu(ye)){if(il<1){il++,yield z("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.";ae(y,"stop.failure",{sessionId:s,reason:"MODEL_PROTOCOL_VIOLATION",error:u},o),yield*Je(u,"MODEL_PROTOCOL_VIOLATION");return}if(!K&&$t===0&&ce.length===0&&!qo&&ye.trim()===""&&ln.join("").trim()===""&&ot.length===0){if(sl<1){sl++,yield z("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.";ae(y,"stop.failure",{sessionId:s,reason:"EMPTY_MODEL_RESPONSE",error:u},o),yield*Je(u,"EMPTY_MODEL_RESPONSE");return}if(ce.length===0&&!qo){if(e.drainPendingTaskNotifications){let R=e.drainPendingTaskNotifications().filter(P=>P.trim());if(R.length>0){zm(f,R),f={...f,messages:[...b,...ye?[{role:"assistant",content:ye}]:[],Um(R)]},o.info(`late background task result consumed at completion (${R.length} item(s)) \u2014 running another round`);continue}}if(e.drainPendingGuidance){let R=e.drainPendingGuidance().map(P=>P.trim()).filter(Boolean);if(R.length>0){f={...f,messages:[...b,...ye?[{role:"assistant",content:ye}]:[],...R.map(P=>({role:"user",content:P}))]},o.info(`late mid-turn guidance consumed at completion (${R.length} item(s)) \u2014 running another round`);continue}}if(ye){let R=f.transition?.reason==="max_output_tokens_escalate"||f.transition?.reason==="max_output_tokens_recovery";f.finalText=R?`${f.finalText}${ye}`:ye}if(e.toolChoice==="required"&&!cs&&x.length>0&&ol<2){ol++;let R=x.map(P=>P.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: ${R}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(zo&&K&&dc(K)){if(f.transition?.reason!=="collapse_drain_retry"){let R=qs(ht,hs);if(R.committed>0){o.info(`collapse drain: committed ${R.committed} stages`),yield z("collapse_drain",`${R.committed} stages committed`),f={...f,messages:R.messages,transition:{reason:"collapse_drain_retry",committed:R.committed}};continue}}if(pn(De)){De.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield z("reactive_compact","withheld prompt_too_long"),f={...f,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),ae(y,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:K.message},o),yield*Je(K.message,"PROMPT_TOO_LONG");return}if(zo&&K&&fc(K)){if(pn(De)){De.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield z("reactive_compact","media error strip-retry"),f={...f,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),ae(y,"stop.failure",{sessionId:s,reason:"media_error",error:K.message},o),yield*Je(K.message,"IMAGE_ERROR");return}if(Ip(kl)){J.consecutiveTruncations+=1;let R=e.modelMaxOutputTokens??ru,P=ei(J,at,R),Ne={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,...ye?[{role:"assistant",content:ye}]:[],Ne];if(P.shouldEscalate&&oe===void 0){J.currentMaxOutputTokens=P.newMax,o.info(`max_output_tokens escalate: ${P.newMax} tokens`),yield z("output_escalation",`${P.newMax} tokens`),f={...f,messages:de,maxOutputTokensOverride:P.newMax,transition:{reason:"max_output_tokens_escalate"}};continue}if(H<su){o.info(`max_output_tokens recovery #${H+1}`),yield z("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"),ds=!0}else J.consecutiveTruncations=0;Be=Zo(Be,{replayMessages:b,lastStopReason:"completed"});let u=await em({hooks:y,sessionId:s,messages:b,finalText:f.finalText,thinkingBlocks:ot,log:o});if(u?.action==="end"){let R=mg(u.content,b,"stop hook prevented continuation before completing the final status contract");yield*je(R);return}if(u?.action==="continue"){f={...f,messages:u.messages,stopHookActive:u.stopHookActive,transition:u.transition};continue}let m=om({tokenBudget:e.tokenBudget,totalUsage:f.totalUsage,budgetContinuationCount:f.budgetContinuationCount,lastBudgetDeltaTokens:f.lastBudgetDeltaTokens,lastBudgetGlobalTokens:f.lastBudgetGlobalTokens,messages:b,finalText:f.finalText,thinkingBlocks:ot,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o,recoveryTrace:f.recoveryTrace});if(m){yield z("budget_continuation",m.recoveryDetail),f={...f,messages:m.messages,budgetContinuationCount:m.budgetContinuationCount,lastBudgetDeltaTokens:m.lastBudgetDeltaTokens,lastBudgetGlobalTokens:m.lastBudgetGlobalTokens,transition:m.transition};continue}if(f.finalText.trim()&&DR(f.lastTaskList)&&f.taskListReconciliationCount<1){let R=x.find(P=>P.function.name==="task")??(a??c).find(P=>P.function.name==="task");if(R){let P=jR(f.lastTaskList),Ne=I(x),de=gt(Ke(),Le);x=de.some(Is=>Is.function.name==="task")?de:[...de,R],f={...f,taskListReconciliationCount:f.taskListReconciliationCount+1,messages:[...b,{role:"assistant",content:f.finalText},{role:"user",content:P}],transition:{reason:"next_turn"}},ge=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:I(a??c),enabledToolNamesBefore:Ne,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield z("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if((e.buildVerificationGate??!0)&&hm(i)&&!f.artifactContract.buildVerified&&f.artifactContract.buildFailureEvidence.length>0&&x.some(R=>R.function.name==="exec")&&f.buildVerificationRecoveryCount<3){let R=NR(f.artifactContract);f={...f,buildVerificationRecoveryCount:f.buildVerificationRecoveryCount+1,messages:[...b,{role:"assistant",content:f.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},ge=!0,yield z("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let T=bc({inputMessages:i,messages:b,finalText:f.finalText,thinkingBlocks:ot,stopHookActive:f.stopHookActive,totalToolCallCount:$t,distinctToolNames:Oe,log:o});if(T){if(f.stopHookActive&&f.finalText.trim()===""){let R=$n({inputMessages:i,messages:T.messages,reason:"stop hook produced an empty response after tool use"});if(R){yield*je(R,{forcedStop:!0});return}}f={...f,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition};continue}if($t===0&&e.toolChoice!=="none"&&rl<1&&Sp(ye)){rl++;let R=I(a??c).join(", ");yield z("capability_denial_review","unverified capability denial; asking for verification or honest escalation"),f={...f,messages:[...b,{role:"assistant",content:ye},{role:"user",content:`Before declaring a capability missing, verify it. Your full tool list: [${R}]. 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&&!fu(ct)&&x.some(R=>or({identity:qm(R,R.function.name)}))&&e.toolChoice!=="none"&&ls<1&&ye.trim()!==""){ls++,ge=!0,yield z("fresh_evidence_required","evidence turn answered with no tool call; forcing one grounded retry"),f={...f,messages:[...b,{role:"assistant",content:ye},{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=Do(b,"the model ended with an empty response after tool use before completing the final status contract",{cleanStopWithFinalText:!0}),$=ds?jo==="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*je($&&g?`${$}
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}
61
62
 
62
- ${g}`:g);return}let _g=ot.length===0&&ln.length>0?ln.join(""):void 0;Bo=qn,h(b,Fs(ce,ye||void 0,ot.length>0?ot:void 0,_g)),Be=Ws(Be,{replayMessages:b,pendingToolCallIds:ce.map(u=>u.id),completedToolCallIds:Be.completedToolCallIds,lastStopReason:"tool_calls"});let Ts=f.identicalCallCounts,ks=f.identicalFailureCounts,zn=[],lt=[],Rl=[],Hn=[],xl=!1;for(let u of ce){if(Hm(u,f)){zn.push(u);continue}let m=`${u.function.name}::${u.function.arguments}`;if(f.commercialRetryBlocks.has(m)){Rl.push(u);continue}let T=Ts.get(m)??0;Ts.set(m,T+1);let g=ks.get(m)??0,$=Dn.get(m)??0,R=qc.has(u.function.name)||u.function.name==="exec"?f.identicalSuccessfulToolResults.get(m):void 0;g>=fn||$>=fn?(lt.push(u),xl||(xl=!0,o.info($>=fn?`AP4 blocked: ${u.function.name} proposed invalid identical arguments ${$}x`:`AP4 blocked: ${u.function.name} failed ${g}x with identical arguments`))):T+1>fn&&R?Hn.push({call:u,result:R,repeatCount:T+1}):zn.push(u)}let ke=[],vg=new Set(x.map(u=>u.function.name)),Sl=new Set(lt.filter(u=>C0(u,vg)).map(u=>u.id));for(let u of Hn){let m=u.call;ks.delete(`${m.function.name}::${m.function.arguments}`);let T=`Reused previous successful ${m.function.name} result for identical arguments (attempt ${u.repeatCount}); no additional tool execution was performed.
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.
63
64
 
64
- ${u.result.content}`,g=we(m.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),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!0,outputPreview:T.slice(0,2e3),durationMs:0,details:{type:m.function.name,reusedIdenticalCall:!0,repeatCount:u.repeatCount}}}if(Hn.some(u=>u.call.function.name==="exec"&&jm(u.call.function.arguments))){let u=I(x);b.push({role:"user",content:LR()}),yield{type:"tool_selection_policy",turnId:r,policyId:"ui_acceptance_after_preparation_guidance",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:I(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:u,suppressedToolNames:[],nextAction:"reuse-or-collect-reliable-ui-evidence"},yield z("ui_acceptance_after_preparation_guidance","reused successful browser preparation command")}for(let u of lt){let m=`${u.function.name}::${u.function.arguments}`;(Dn.get(m)??0)>=fn&&ee.push({name:u.function.name,reason:"invalid-arguments"}),ee.push({name:u.function.name,reason:"identical-repeat-policy"});let T=Math.max(ks.get(m)??0,Dn.get(m)??0),g=Dr(b,u.function.name,u.function.arguments),$=AR(g),R=Sl.has(u.id)?w0(T,u):$?`This exact tool call has been attempted ${T} times. Last error: ${$}. 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.`,P=we(u.id,{ok:!1,error:R});h(b,P),ke.push(u.id),yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:R}}for(let u of Rl){let m=`${u.function.name}::${u.function.arguments}`,T=f.commercialRetryBlocks.get(m);ee.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,we(u.id,{ok:!1,error:g})),ke.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(lt.length>0&&zn.length===0&&Hn.length===0&&lt.every(u=>Sl.has(u.id))&&f.existingFileUpdateRecoveryCount<2){let u=I(x);x=gt(Ke(),Le);let m=I(x);jn=!0,ge=!0;let T=[...new Set(lt.map(g=>ns(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:I(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:m,suppressedToolNames:[],nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield z("existing_file_update_recovery",T.join(",")||"unknown"),f={...f,messages:b,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(lt.length>0){let u=lt[0],m=Dr(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. "+(m?`The error was: "${m}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};b.push(T)}let Tg=an>=3&&f.repeatedToolFailureRecoveryCount<1;if(lt.length>0&&zn.length===0&&Hn.length===0&&!Tg){let u=Dm(lc(b,1),{availableToolNames:I(a??c),enabledToolNames:as(),toolCallNames:[...Oe].sort(),blockedToolCalls:Xr(ee)});yield*je(u);return}let El=[],Cs=[];for(let u of zn){let m=Tm({toolName:u.function.name,rawArguments:u.function.arguments});m?Cs.push({call:u,...m}):El.push(u)}for(let u of Cs){let m=u.call;ee.push({name:m.function.name,reason:"read-only-context-pack"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.warn(`read-only context-pack blocked: ${m.function.name} ${u.path}`)}Cs.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 kg=new Set(x.map(u=>u.function.name)),ws=[],Ho=[];for(let u of El){let m=sg(u.function.name,u.function.arguments,kg);if(m){let T=`${u.function.name}::${u.function.arguments}`;if(ss.has(T)){ss.delete(T),o.info(`existing-file-update guard: verbatim re-issue admitted once for ${m.path}`),ws.push(u);continue}ss.add(T),Ho.push({call:u,...m})}else ws.push(u)}for(let u of Ho){let m=u.call;ee.push({name:m.function.name,reason:"existing-file-update-tool-required"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.info(`existing file update blocked: ${m.function.name} ${u.path}`)}if(Ho.length>0){let u=I(x);x=gt(Ke(),Le);let m=I(x);jn=!0,ge=!0;let T=[...new Set(Ho.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:I(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:m,suppressedToolNames:[],nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield z("existing_file_update_recovery",T.join(",")||"unknown"),f={...f,messages:b,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Al=[],Rs=[];for(let u of ws){let m=vm({state:f.artifactContract,inputMessages:i,toolName:u.function.name,rawArguments:u.function.arguments});m?Rs.push({call:u,...m}):Al.push(u)}for(let u of Rs){let m=u.call;ee.push({name:m.function.name,reason:"artifact-root-contract"}),Mc(f.artifactContract,{path:u.path,artifactRoot:u.artifactRoot,toolName:m.function.name}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},gs()&&(yield ms()),o.warn(`artifact root contract blocked: ${m.function.name}`)}Rs.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 $l=[],xs=[];for(let u of Al){let m=Zp({inputMessages:i,messages:b,toolCall:u});m?xs.push({call:u,error:m}):$l.push(u)}for(let u of xs){let m=u.call;ee.push({name:m.function.name,reason:"premature-completion-artifact"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.info(`premature completion artifact blocked: ${m.function.name}`)}xs.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 Cg=new Set(x.map(u=>u.function.name)),Pl=[],Vo=[];for(let u of $l)Cg.has(u.function.name)?Pl.push(u):Vo.push(u);for(let u of Vo){let m=`Tool "${u.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;ee.push({name:u.function.name,reason:"not-offered"}),h(b,we(u.id,{ok:!1,error:m})),ke.push(u.id),Oe.add(u.function.name),o.warn(`unoffered tool call suppressed: ${u.function.name}`)}if(Vo.length>0&&f.notOfferedToolRecoveryCount<1){let u=[...new Set(Vo.map(P=>P.function.name))].sort(),m=u.filter(P=>Lo.has(P)&&!cn.has(P)),T=jn&&u.includes("write"),g=u.filter(P=>Le.has(P)),R=(a??c).filter(P=>u.includes(P.function.name));if(m.length>0)f.notOfferedToolRecoveryCount+=1,ge=!0,b.push({role:"user",content:`The full schema for ${m.map(P=>`\`${P}\``).join(", ")} was not loaded. If you still select that capability, call \`${si}\` with the exact name first; do not guess its arguments.`}),yield z("deferred_tool_schema_not_loaded",m.join(","));else if(g.length>0)f.notOfferedToolRecoveryCount+=1,ge=!0,b.push({role:"user",content:`You retried ${g.map(P=>`\`${P}\``).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:I(a??c),enabledToolNamesBefore:I(x),enabledToolNamesAfter:I(x),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield z("policy_suppressed_tool_retry_blocked",g.join(","));else if(!T&&R.length>0){let P=I(x),Ne=new Map(x.map(de=>[de.function.name,de]));for(let de of R)Ne.set(de.function.name,de);x=[...Ne.values()],f.notOfferedToolRecoveryCount+=1,ge=!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:I(a??c),enabledToolNamesBefore:P,enabledToolNamesAfter:I(x),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 z("available_tool_reenabled_after_not_offered_call",u.join(","))}}let Ml=[],Ss=[];for(let u of Pl){let m=yt.tools.find(g=>g.function.name===u.function.name),T=Bc(m,u.function.arguments);T?Ss.push({call:u,error:T}):Ml.push(u)}for(let u of Ss){let m=u.call;ee.push({name:m.function.name,reason:"invalid-arguments"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),Oe.add(m.function.name),o.info(`invalid tool arguments blocked: ${m.function.name}`)}Ss.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 Go=[],Es=[],Il=[],Ol=[],As=new Map,Nl=(u,m)=>{let T=As.get(u);As.set(u,T?`${T}
65
- ${m}`:m)};for(let u of Ml){if(u.function.name!=="exec"){Go.push(u);continue}let m=u,T=$R(m.function.arguments),g=T?IR(T):null;g&&(m={...m,function:{...m.function,arguments:Fm(m.function.arguments,g)}},Ol.push({originalCommand:T??"",rewrittenCommand:g}),Nl(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 $=T?OR(T):null;if($?.action==="block")Es.push({call:m,error:$.error});else if($?.action==="rewrite"){let R={...m,function:{...m.function,arguments:Fm(m.function.arguments,$.command)}};Il.push({call:R,originalCommand:T??"",rewrittenCommand:$.command}),Nl(u.id,`[Engine notice] Adjusted this command before execution: appended --strictPort so a busy port cannot fall back onto reserved frontend port ${es}. Executed: ${$.command}`),Go.push(R)}else Go.push(m)}for(let u of Ol)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:I(a??c),enabledToolNamesBefore:I(x),enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${u.originalCommand} -> ${u.rewrittenCommand}`);for(let u of Il){let m=I(x);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:I(a??c),enabledToolNamesBefore:m,enabledToolNamesAfter:I(x),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 Es){let m=u.call;ee.push({name:m.function.name,reason:"reserved-frontend-port"});let T=I(x);h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error,details:{type:m.function.name,error:"reserved_frontend_port",reservedPort:es}},o.info(`reserved frontend port preflight blocked: ${m.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:I(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}Es.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 Vn=[],un=[];for(let u of Go){if(u.function.name!=="read"){Vn.push(u);continue}let m=zc(u.function.arguments);if(!m){Vn.push(u);continue}let T=Te(m),g=tg(T);if((f.fileReadCounts.get(T)??0)>=g){let $=f.fileReadSignatures.get(T),R=Gm(m);if($&&R&&(R.mtimeMs!==$.mtimeMs||R.sizeBytes!==$.sizeBytes)){o.info(`read cycle exemption: ${T} changed since last counted read, cap reset`),f.fileReadCounts.set(T,0),Vn.push(u);continue}un.push({call:u,filePath:T,maxReads:g})}else Vn.push(u)}for(let u of un){let m=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. ${Dc(u.filePath)}`;ee.push({name:m.function.name,reason:"read-cycle-policy"}),f.fileReadCycleBlockedPaths.add(u.filePath),h(b,we(m.id,{ok:!1,error:T})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:T},o.info(`read cycle blocked: ${u.filePath}`)}if(un.length>0){let u=[...new Set(un.map(g=>`${g.filePath} (max ${g.maxReads})`))].join(", "),m=[...new Set(un.map(g=>Dc(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. ${m} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),x.some(g=>Wm(g.function.name))&&(f.persistedLongHorizonStateRecovered||un.some(g=>Kc(g.filePath)))){let g=I(x),$=g.filter(R=>s0.has(R)).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:I(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:I(x),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: ${$.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 z("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(d0(ee,f.fileReadCycleBlockedPaths,f.persistedLongHorizonStateRecovered,f.maintainedDocuments)){yield*je("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 $s=im(Vn,f.toolFailureCounts,f.variantReassertedSignatures),Fl=$s.allowed,ut=Fl.slice(0,nt);for(let u of ut){if(!Hm(u,f))continue;let m=tt(u.function.arguments),T=typeof m?.taskId=="string"?m.taskId:void 0;!m||!T||typeof m.waitMs=="number"||(u.function.arguments=JSON.stringify({...m,waitMs:KR(f.backgroundAgentPollCounts.get(T)??0)}))}let Ll=Fl.slice(ut.length);if($s.blocked.length>0){for(let u of $s.blocked){let m=u.call;ee.push({name:m.function.name,reason:"variant-failure-policy"});let T=we(m.id,{ok:!1,error:u.error});h(b,T),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.info(`variant tool blocked: ${m.function.name} failed ${u.failCount}x with different args`)}b.push(am())}if(Ll.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 m of Ll){ee.push({name:m.function.name,reason:"per-round-tool-call-limit"});let T=we(m.id,{ok:!1,error:u});h(b,T),ke.push(m.id)}b.push({role:"user",content:u})}for(let u of ut){let m=u.function.arguments,T=x.find($=>$.function.name===u.function.name);if(T?.backfillObservableInput)try{let $=JSON.parse(u.function.arguments),R={...$};T.backfillObservableInput(R),Object.keys(R).some(Ne=>!(Ne in $))&&(m=JSON.stringify(R))}catch{}let g={sequence:ct.length,callId:u.id,name:u.function.name,identity:qm(T,u.function.name),status:"running",arguments:m};ct.push(g),Zc.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:m,inputSummary:uc(m)},Qc.add(u.function.name),el++}let wg=new Map(f.toolFailureCounts),Wo=null,It;try{let u=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:y,sessionId:s,turnId:r,log:o,signal:v,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Ql,executionTimeoutMsByTool:new Map(x.flatMap(g=>{let $=g.meta?.executionTimeoutMs;return typeof $=="number"&&Number.isFinite($)&&$>0?[[g.function.name,$]]:[]})),contextState:f.contentReplacementState});for(let g of ut)u.addTool(g);let m=!1;for await(let g of u.getRemainingResults()){let $=HR(g.details),R=Qm(g.details),P=Zc.get(g.callId);P&&(P.status=g.blocked||R==="not-applied"?"blocked":!g.ok||R==="indeterminate"?"failed":"succeeded",!g.ok&&typeof g.error=="string"&&g.error.trim()&&(P.error=g.error),R==="indeterminate"&&!P.error&&(P.error="MCP action outcome is indeterminate; completion is not verified."),(!g.ok||R==="indeterminate")&&(P.failureKind=pu(g)));let Ne=Im(g);if(Ne){if(ee.push({name:g.toolName,reason:Ne}),g.toolName==="exec"&&Ne==="confirmation-timeout"){let S=I(x);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:I(a??c),enabledToolNamesBefore:S,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"use-an-authorized-approach-or-report-confirmation-blocker"}}if(g.toolName==="exec"&&Ne==="global-process-kill-blocked"){let S=I(x);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:I(a??c),enabledToolNamesBefore:S,enabledToolNamesAfter:I(x),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 de=As.get(g.callId);if(de){let S=g.message;typeof S.content=="string"&&(S.content=`${de}
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}
66
67
 
67
- ${S.content}`)}if(g.ok&&g.toolName===si){let S=du(g.details),j=e.refreshTools?new Set(e.refreshTools().map(fe=>fe.function.name)):void 0,Y=[],le=[],Ce=[];for(let fe of S)!Q.get(fe)||j&&!j.has(fe)?Ce.push(fe):!Lo.has(fe)||cn.has(fe)?le.push(fe):(cn.add(fe),e.loadedDeferredToolNames?.add(fe),Y.push(fe));let Xe=nl(Ke(),j);x=nn(gt(Xe,Le),Ke());let Nt=g.message;Nt.content=JSON.stringify({loaded:Y,alreadyResident:le,unavailable:Ce}),g.details={type:"tool_schema_load",requestedToolNames:S,loaded:Y,alreadyResident:le,unavailable:Ce},o.info({turnId:r,loaded:Y,alreadyResident:le,unavailable:Ce},"tool schemas materialized by Agent selection")}{let S=g.message;e.sanitizeToolResultMedia&&(Array.isArray(S.imageUrls)||Array.isArray(S.audioUrls)||Array.isArray(S.videoUrls))&&await e.sanitizeToolResultMedia(S)}if(h(b,g.message),We&&jc(g.toolName,We)){let S=Gc(Se(g.toolName));We.scope==="interaction-step"?$?.scope==="interaction-step"?(We=$,Fn=!1,Ln=!1):R==="committed"||R===void 0&&(S==="computer_act"||S==="act")?Ln=!0:Fn=!0:Fn=!0}!It&&$&&(It=$,It&&(We=It)),ke.push(g.callId);let Is=VR(g,f);g.blocked||(Oe.add(g.toolName),$t++);let jl=g.ok&&Lr(g);Is||cm({toolFailureCounts:f.toolFailureCounts,toolName:g.toolName,toolArguments:ut.find(S=>S.id===g.callId)?.function.arguments,ok:g.ok,softEmpty:jl});let _t=ce.find(S=>S.id===g.callId);if(!g.ok&&_t){let S=sm(g.details),j=`${_t.function.name}::${_t.function.arguments}`;g.blocked||f.identicalFailureCounts.set(j,(f.identicalFailureCounts.get(j)??0)+1),S&&!(S.retryable&&S.safeToRetry&&S.automaticRetryAuthorized)&&f.commercialRetryBlocks.set(j,{billed:S.billed,retryMode:S.retryMode,...S.stage?{stage:S.stage}:{}})}if(g.ok&&_t&&(f.commercialRetryBlocks.delete(`${_t.function.name}::${_t.function.arguments}`),f.identicalFailureCounts.delete(`${_t.function.name}::${_t.function.arguments}`)),g.ok&&ZR.has(Se(g.toolName))&&O0(f),g.ok&&Wm(g.toolName)){let S=ut.find(Y=>Y.id===g.callId),j=S?ns(S.function.arguments):void 0;if(j){let Y=Te(j);if(f.longHorizonStateMaintenanceRequiredFiles.has(Y)){let le=Xc(f.maintainedDocuments,Y,S?.function.arguments??"");le.ok?f.longHorizonStateMaintenanceWrittenFiles.add(Y):(ee.push({name:g.toolName,reason:"benchmark-state-invalid-content"}),b.push({role:"user",content:`Benchmark-state maintenance write for ${Y} is incomplete: ${le.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(g.ok&&!jl&&(qc.has(g.toolName)||g.toolName==="exec"&&g.details?.type==="exec_background"||g.toolName==="exec"&&jm(ut.find(S=>S.id===g.callId)?.function.arguments??""))){let S=ut.find(Y=>Y.id===g.callId),j=typeof g.message?.content=="string"?g.message.content:"";if(S&&j){let Y=Array.isArray(g.message.imageUrls)?g.message.imageUrls.filter(Gn=>typeof Gn=="string"):void 0,le=Array.isArray(g.message.toolReferences)?g.message.toolReferences.filter(Gn=>typeof Gn=="string"):void 0,Ce=Array.isArray(g.message.contentBlocks)?g.message.contentBlocks:void 0,Xe=g.message.structuredContent,Nt=g.message.mcpMeta,fe=g.message.mcpIsError;f.identicalSuccessfulToolResults.set(`${S.function.name}::${S.function.arguments}`,{content:j,imageUrls:Y,toolReferences:le,contentBlocks:Ce,...Xe!==void 0?{structuredContent:Xe}:{},...Nt!==void 0?{mcpMeta:Nt}:{},...typeof fe=="boolean"?{mcpIsError:fe}:{}})}}if(g.toolName==="agent"){let S=on(g.details,"agentId"),j=on(g.details,"status"),Y=Zr(g.details,"background");g.ok&&S&&Y===!0&&j==="running"&&rn(f).add(S)}if(g.toolName==="task"){let S=YR(g.details);S&&(f.lastTaskList=S);let j=on(g.details,"taskId"),Y=Zr(g.details,"running"),le=on(g.details,"lifecycle"),Ce=on(g.details,"action");if(j&&(Ce==="cancel"||Y===!1||le&&le!=="running"&&le!=="pending"))rn(f).delete(j),f.backgroundAgentPollCounts.delete(j),f.backgroundAgentNoOutputPollCounts.delete(j),f.stalledBackgroundAgentTasks.delete(j);else if(j&&Ce==="output"&&Y===!0&&rn(f).has(j)){let Xe=(f.backgroundAgentPollCounts.get(j)??0)+1;f.backgroundAgentPollCounts.set(j,Xe),Xe>=Vm&&f.stalledBackgroundAgentTasks.set(j,`still running after ${Xe} bounded poll(s)`);let Nt=typeof g.message?.content=="string"?g.message.content:"",fe=Zr(g.details,"hasOutput");if(fe!==void 0?fe===!1:JR(Nt)){let Ns=(f.backgroundAgentNoOutputPollCounts.get(j)??0)+1;f.backgroundAgentNoOutputPollCounts.set(j,Ns);let Jo=zR(g.details,"elapsedSeconds")??XR(Nt);(Jo!==void 0&&Jo>=GR||Jo===void 0&&Ns>=WR)&&f.stalledBackgroundAgentTasks.set(j,`no output after ${Jo??"unknown"}s across ${Ns} poll(s)`)}else f.backgroundAgentNoOutputPollCounts.delete(j),Xe<Vm&&f.stalledBackgroundAgentTasks.delete(j)}}if(g.ok&&g.toolName==="read"){let S=ut.find(j=>j.id===g.callId);if(S){let j=zc(S.function.arguments);if(j){let Y=Te(j),le=f.fileReadCounts.get(Y)??0;f.fileReadCounts.set(Y,le+1);let Ce=Gm(j);Ce&&f.fileReadSignatures.set(Y,Ce);let Xe=typeof g.message?.content=="string"?g.message.content:"";m=k0(f,j,Xe,f.turnCount,g.details)||m}}}yield mu(r,g);for(let S of gu(r,g))yield S;for(let S of _u({turnId:r,result:g,toolCalls:ce}))yield S;let Os=ce.find(S=>S.id===g.callId),xg=typeof g.message?.content=="string"?g.message.content:"";if(Os){Cm({state:f.artifactContract,inputMessages:i,toolName:g.toolName,rawArguments:Os.function.arguments,ok:g.ok,content:xg,details:g.details}),gs()&&(yield ms());let S=FR(g.toolName,Os.function.arguments);if(S){let j=Im(g),Y=g.ok&&!Lr(g);Y&&rs.delete(S);let le=Y||j?0:(rs.get(S)??0)+1;if(le>0&&rs.set(S,le),le===Lm){let Ce=S.startsWith("exec:")?"exec":"edit";f.recoveryTrace.set(`no_progress_observed:${Ce}`,(f.recoveryTrace.get(`no_progress_observed:${Ce}`)??0)+1),tl.has(S)||(tl.add(S),b.push({role:"user",content:`You have now run ${Lm} consecutive failed or empty variations of the same action (${S}) without completing the user's request. 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 z("no_progress_nudge",S))}}}!Wo&&ug&&ri(g.toolName,"stt")&&g.ok&&(Wo=wR(i,g))}if(jn&&(x=gt(Ke(),Le),jn=!1),Ln&&!It){let g=I(x);x=gt(Ke(),Le),ge=!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:I(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"continue-from-grounded-action-result"},yield z("mcp_interaction_step_advanced",We?.reason??"mcp-interaction-step-blocked"),We=void 0,Ln=!1}else if(Fn){let g=I(x);x=nn([],E),ge=!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:I(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:I(x),suppressedToolNames:Om(g,I(x)),nextAction:"report-verified-evidence-and-blocker"},yield z("mcp_turn_cleanup_completed",We?.reason??"mcp-turn-blocked"),We=void 0,Fn=!1}else if(It){let g=It;Ln=!1;let $=I(x),R=x.filter(P=>jc(P.function.name,g));x=nn(R,E),ge=R.length>0,b.push({role:"user",content:g.scope==="interaction-step"?R.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.":x.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:I(a??c),enabledToolNamesBefore:$,enabledToolNamesAfter:I(x),suppressedToolNames:Om($,I(x)),nextAction:R.length>0?g.scope==="interaction-step"?"invoke-grounded-action-or-release":"invoke-bounded-connector-cleanup":"report-verified-evidence-and-blocker"},yield z(g.scope==="interaction-step"?"mcp_interaction_step_execution_block":"mcp_turn_execution_block",g.reason)}if(m){let g=b0(r,f.maintainedDocuments,f.fileReadCounts,f.turnCount);g&&(yield g);for(let P of T0(r,f.maintainedDocuments))yield P;let $=a0(f.maintainedDocuments,f.turnCount),R=x.some(P=>Uc.has(P.function.name));if($&&R){f.longHorizonStateMaintenanceRequiredFiles=new Set(rg(f.maintainedDocuments).map(Te));for(let P of x)Uc.has(P.function.name)||Le.add(P.function.name);x=gt(x,Le),ge=!0,b.push({role:"user",content:$}),yield z("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let T=u0(f.maintainedDocuments);if(T.length>0&&f.longHorizonStateIntegrityRecoveryCount<r0){let g=T.map($=>`${At($.path)}: ${$.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"}},ge=!0,yield z("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(c0(f)){yield*je("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 m=u instanceof Error?u.message:String(u);yield*Je(m,"TOOL_EXECUTION_ERROR");return}if(Wo){yield*je(Wo);return}b.push(...lm({toolFailureCounts:f.toolFailureCounts,snapshot:wg})),Be=Zo(Be,{replayMessages:b,completedToolCallIds:[...Be.completedToolCallIds,...ke],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&ce.length>0&&(cs=!0);let Rg=ce.length>0&&ce.every(u=>{let m=b.find(g=>g?.role==="tool"&&g?.tool_call_id===u.id);if(!m)return!0;let T=m.content;return typeof T=="string"&&T.startsWith("Error: ")}),Ot=f.consecutiveFailedRounds,Ps=f.repeatedToolFailureRecoveryCount;if(Rg){if(Ot+=1,Ot>=eu){if(an>=3&&f.repeatedToolFailureRecoveryCount<1){let R=bc({inputMessages:i,messages:b,finalText:f.finalText,thinkingBlocks:[],stopHookActive:f.stopHookActive,totalToolCallCount:$t,distinctToolNames:Oe,log:o});if(R?.reason==="explicit_required_file_verification"||R?.reason==="explicit_extra_file_verification"){yield z("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),f={...f,messages:R.messages,stopHookActive:R.stopHookActive,transition:R.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:f.repeatedToolFailureRecoveryCount+1};continue}}if(f.repeatedToolFailureRecoveryCount<1){let R=$p(b,ct.at(-1)?.failureKind);if(R){yield z("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),f={...f,messages:[...b,R],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:f.repeatedToolFailureRecoveryCount+1};continue}}let u=`repeated tool failures (${Ot} rounds in a row)`,m=$n({inputMessages:i,messages:b,reason:`${u} before all required files were produced`}),T=f.finalText.trim()?f.finalText:lc(b,Ot),g=m?`${T}
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}
68
69
 
69
- ${m}`:T,$=Dm(g,{availableToolNames:I(a??c),enabledToolNames:as(),toolCallNames:[...Oe].sort(),blockedToolCalls:Xr(ee)});o.info(`early exit: ${Ot} consecutive failed rounds, returning ${f.finalText?"partial":"fallback"} response`),yield*je($,{forcedStop:!0});return}}else Ot=0,Ps>0&&(o.info("tool-failure self-correction re-armed after a successful round"),Ps=0);let Ko=[...f.fileReadCycleBlockedPaths].filter(u=>!f.fileReadCycleNudgedPaths.has(u));if(Ko.length>0){let u=Ko.join(", "),m=[...new Set(Ko.map(Dc))].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}. ${m} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};b.push(T);for(let g of Ko)f.fileReadCycleNudgedPaths.add(g)}let Ms=ue+1;if(k>0&&Ms>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",$={role:"assistant",content:f.finalText,...ot.length>0&&{thinkingBlocks:[...ot]}};f={...f,messages:[...b,$,{role:"user",content:g}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let u=$n({inputMessages:i,messages:b,reason:`tool loop max turns reached (${k}) before completing all required files`}),m=Do(b,`tool loop max turns reached (${k}) before completing the final status contract`);yield*je(u?`${m}
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}
70
71
 
71
- ${u}`:m);return}if(Ge>0&&Ms>Ge){o.info(`tool loop budget exhausted (${Ge} rounds), returning`);let u=$n({inputMessages:i,messages:b,reason:`explicit maxRounds reached (${Ge}) before completing all required files`}),m=Do(b,`explicit maxRounds reached (${Ge}) before completing the final status contract`);yield*je(u?`${m}
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}
72
73
 
73
- ${u}`:m);return}f={messages:b,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Ms,transition:{reason:"next_turn"},guardState:J,reactiveCompactState:De,toolLoopState:Be,consecutiveFailedRounds:Ot,finalText:f.finalText,totalUsage:f.totalUsage,collapseStore:hs,currentModel:f.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:f.stopHookActive,lastResponseId:f.lastResponseId,snipRemovedIds:f.snipRemovedIds,contentReplacementState:f.contentReplacementState,budgetContinuationCount:f.budgetContinuationCount,repeatedToolFailureRecoveryCount:Ps,lastBudgetDeltaTokens:f.lastBudgetDeltaTokens,lastBudgetGlobalTokens:f.lastBudgetGlobalTokens,identicalCallCounts:Ts,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 cg(e){return[...new Set((e??[]).map(t=>t.function.name))].sort()}var lg=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,p=!1,y=()=>({type:"tool_use_summary",turnId:o,telemetrySource:"agent",ledgerSchemaVersion:4,toolCalls:[],finalAnswerEvidence:Jn(c?.freshEvidenceRequired===!0,[]),availableToolNames:cg(s??i),enabledToolNames:cg(i),toolCallNames:[],blockedToolCalls:[]}),v=typeof c?.maxRounds=="number"&&Number.isFinite(c.maxRounds)?c.maxRounds:this.configuredMaxRounds,h=v===void 0?void 0:Math.round(v),k=typeof c?.maxToolCalls=="number"&&Number.isFinite(c.maxToolCalls)?c.maxToolCalls:void 0;yield{type:"start",turnId:o,effectiveMaxRounds:Br(h,r),effectiveMaxToolCalls:qr(k)};try{ae(this.hooks,"turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0},this.log);let C=Gs(r),E=[];a&&E.push({role:"system",content:a}),E.push(...C);let O=c?.model??"",U=c?.reasoning;c?.reasoning?.effort==="auto"&&(U={...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:U,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 Q of ag(M,this.transport,this.toolInvoker,this.log))Q.type==="tool_use_summary"&&(p=!0),Q.type==="end"?ae(this.hooks,"turn.completed",{...l,...d?{prompt:d}:{},response:Q.content},this.log):Q.type==="error"&&ae(this.hooks,"turn.failed",{...l,code:Q.code,error:Q.error},this.log),yield Q}catch(C){if(p||(p=!0,yield y()),n?.aborted)ae(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,U=dn(O,E);this.log.error(`turn ${o} error [${U}, retryable=${Xo(U)}]: ${E}`),ae(this.hooks,"turn.failed",{...l,code:U,error:E},this.log),yield{type:"error",turnId:o,error:E,code:U}}}}};export{lg as Agent};
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};