qlogicagent 2.24.6 → 2.24.8

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