qlogicagent 2.24.5 → 2.24.6
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 +36 -36
- package/dist/cli.js +7 -7
- package/dist/index.js +184 -184
- package/dist/orchestration.js +13 -13
- package/dist/types/orchestration/context/turn-loop-guard.d.ts +13 -0
- package/dist/types/orchestration/index.d.ts +1 -1
- package/dist/types/runtime/context/context-compression-strategies.d.ts +1 -0
- package/dist/types/runtime/ports/model-transport-contracts.d.ts +1 -0
- package/package.json +2 -2
package/dist/agent.js
CHANGED
|
@@ -1,73 +1,73 @@
|
|
|
1
|
-
var Sg=Object.create;var Dl=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var $g=Object.getPrototypeOf,Pg=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Mg=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ag(t))!Pg.call(e,r)&&r!==n&&Dl(e,r,{get:()=>t[r],enumerable:!(o=Eg(t,r))||o.enumerable});return e};var Ig=(e,t,n)=>(n=e!=null?Sg($g(e)):{},Mg(t||!e||!e.__esModule?Dl(n,"default",{value:e,enumerable:!0}):n,e));var Qn=w(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var Yn=class{};W._CodeOrName=Yn;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Bt=class extends Yn{constructor(t){if(super(),!W.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};W.Name=Bt;var qe=class extends Yn{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((n,o)=>`${n}${o}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((n,o)=>(o instanceof Bt&&(n[o.str]=(n[o.str]||0)+1),n),{})}};W._Code=qe;W.nil=new qe("");function ku(e,...t){let n=[e[0]],o=0;for(;o<t.length;)ci(n,t[o]),n.push(e[++o]);return new qe(n)}W._=ku;var ai=new qe("+");function Cu(e,...t){let n=[Zn(e[0])],o=0;for(;o<t.length;)n.push(ai),ci(n,t[o]),n.push(ai,Zn(e[++o]));return Hh(n),new qe(n)}W.str=Cu;function ci(e,t){t instanceof qe?e.push(...t._items):t instanceof Bt?e.push(t):e.push(Wh(t))}W.addCodeArg=ci;function Hh(e){let t=1;for(;t<e.length-1;){if(e[t]===ai){let n=Vh(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function Vh(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Bt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Bt))return`"${e}${t.slice(1)}`}function Gh(e,t){return t.emptyStr()?e:e.emptyStr()?t:Cu`${e}${t}`}W.strConcat=Gh;function Wh(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Zn(Array.isArray(e)?e.join(","):e)}function Kh(e){return new qe(Zn(e))}W.stringify=Kh;function Zn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=Zn;function Jh(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new qe(`.${e}`):ku`[${e}]`}W.getProperty=Jh;function Xh(e){if(typeof e=="string"&&W.IDENTIFIER.test(e))return new qe(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}W.getEsmExportName=Xh;function Yh(e){return new qe(e.toString())}W.regexpCode=Yh});var di=w(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.ValueScope=Ae.ValueScopeName=Ae.Scope=Ae.varKinds=Ae.UsedValueState=void 0;var Ee=Qn(),li=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},rr;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(rr||(Ae.UsedValueState=rr={}));Ae.varKinds={const:new Ee.Name("const"),let:new Ee.Name("let"),var:new Ee.Name("var")};var sr=class{constructor({prefixes:t,parent:n}={}){this._names={},this._prefixes=t,this._parent=n}toName(t){return t instanceof Ee.Name?t:this.name(t)}name(t){return new Ee.Name(this._newName(t))}_newName(t){let n=this._names[t]||this._nameGroup(t);return`${t}${n.index++}`}_nameGroup(t){var n,o;if(!((o=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||o===void 0)&&o.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ae.Scope=sr;var ir=class extends Ee.Name{constructor(t,n){super(n),this.prefix=t}setValue(t,{property:n,itemIndex:o}){this.value=t,this.scopePath=(0,Ee._)`.${new Ee.Name(n)}[${o}]`}};Ae.ValueScopeName=ir;var Zh=(0,Ee._)`\n`,ui=class extends sr{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Zh:Ee.nil}}get(){return this._scope}name(t){return new ir(t,this._newName(t))}value(t,n){var o;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let r=this.toName(t),{prefix:s}=r,i=(o=n.key)!==null&&o!==void 0?o:n.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,r);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=n.ref,r.setValue(n,{property:s,itemIndex:l}),r}getValue(t,n){let o=this._values[t];if(o)return o.get(n)}scopeRefs(t,n=this._values){return this._reduceValues(n,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,Ee._)`${t}${o.scopePath}`})}scopeCode(t=this._values,n,o){return this._reduceValues(t,r=>{if(r.value===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return r.value.code},n,o)}_reduceValues(t,n,o={},r){let s=Ee.nil;for(let i in t){let a=t[i];if(!a)continue;let c=o[i]=o[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,rr.Started);let d=n(l);if(d){let p=this.opts.es5?Ae.varKinds.var:Ae.varKinds.const;s=(0,Ee._)`${s}${p} ${l} = ${d};${this.opts._n}`}else if(d=r?.(l))s=(0,Ee._)`${s}${d}${this.opts._n}`;else throw new li(l);c.set(l,rr.Completed)})}return s}};Ae.ValueScope=ui});var F=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var V=Qn(),Ye=di(),vt=Qn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return vt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return vt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return vt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return vt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return vt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return vt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return vt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return vt.Name}});var ur=di();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return ur.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return ur.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return ur.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return ur.varKinds}});D.operators={GT:new V._Code(">"),GTE:new V._Code(">="),LT:new V._Code("<"),LTE:new V._Code("<="),EQ:new V._Code("==="),NEQ:new V._Code("!=="),NOT:new V._Code("!"),OR:new V._Code("||"),AND:new V._Code("&&"),ADD:new V._Code("+")};var dt=class{optimizeNodes(){return this}optimizeNames(t,n){return this}},fi=class extends dt{constructor(t,n,o){super(),this.varKind=t,this.name=n,this.rhs=o}render({es5:t,_n:n}){let o=t?Ye.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${r};`+n}optimizeNames(t,n){if(t[this.name.str])return this.rhs&&(this.rhs=gn(this.rhs,t,n)),this}get names(){return this.rhs instanceof V._CodeOrName?this.rhs.names:{}}},ar=class extends dt{constructor(t,n,o){super(),this.lhs=t,this.rhs=n,this.sideEffects=o}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,n){if(!(this.lhs instanceof V.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=gn(this.rhs,t,n),this}get names(){let t=this.lhs instanceof V.Name?{}:{...this.lhs.names};return lr(t,this.rhs)}},pi=class extends ar{constructor(t,n,o,r){super(t,o,r),this.op=n}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},mi=class extends dt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},gi=class extends dt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},hi=class extends dt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},yi=class extends dt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,n){return this.code=gn(this.code,t,n),this}get names(){return this.code instanceof V._CodeOrName?this.code.names:{}}},eo=class extends dt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((n,o)=>n+o.render(t),"")}optimizeNodes(){let{nodes:t}=this,n=t.length;for(;n--;){let o=t[n].optimizeNodes();Array.isArray(o)?t.splice(n,1,...o):o?t[n]=o:t.splice(n,1)}return t.length>0?this:void 0}optimizeNames(t,n){let{nodes:o}=this,r=o.length;for(;r--;){let s=o[r];s.optimizeNames(t,n)||(Qh(t,s.names),o.splice(r,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((t,n)=>zt(t,n.names),{})}},ft=class extends eo{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},bi=class extends eo{},mn=class extends ft{};mn.kind="else";var qt=class e extends ft{constructor(t,n){super(n),this.condition=t}render(t){let n=`if(${this.condition})`+super.render(t);return this.else&&(n+="else "+this.else.render(t)),n}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let o=n.optimizeNodes();n=this.else=Array.isArray(o)?new mn(o):o}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(wu(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,n){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(t,n),!!(super.optimizeNames(t,n)||this.else))return this.condition=gn(this.condition,t,n),this}get names(){let t=super.names;return lr(t,this.condition),this.else&&zt(t,this.else.names),t}};qt.kind="if";var Ut=class extends ft{};Ut.kind="for";var _i=class extends Ut{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iteration=gn(this.iteration,t,n),this}get names(){return zt(super.names,this.iteration.names)}},vi=class extends Ut{constructor(t,n,o,r){super(),this.varKind=t,this.name=n,this.from=o,this.to=r}render(t){let n=t.es5?Ye.varKinds.var:this.varKind,{name:o,from:r,to:s}=this;return`for(${n} ${o}=${r}; ${o}<${s}; ${o}++)`+super.render(t)}get names(){let t=lr(super.names,this.from);return lr(t,this.to)}},cr=class extends Ut{constructor(t,n,o,r){super(),this.loop=t,this.varKind=n,this.name=o,this.iterable=r}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iterable=gn(this.iterable,t,n),this}get names(){return zt(super.names,this.iterable.names)}},to=class extends ft{constructor(t,n,o){super(),this.name=t,this.args=n,this.async=o}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};to.kind="func";var no=class extends eo{render(t){return"return "+super.render(t)}};no.kind="return";var Ti=class extends ft{render(t){let n="try"+super.render(t);return this.catch&&(n+=this.catch.render(t)),this.finally&&(n+=this.finally.render(t)),n}optimizeNodes(){var t,n;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(t,n){var o,r;return super.optimizeNames(t,n),(o=this.catch)===null||o===void 0||o.optimizeNames(t,n),(r=this.finally)===null||r===void 0||r.optimizeNames(t,n),this}get names(){let t=super.names;return this.catch&&zt(t,this.catch.names),this.finally&&zt(t,this.finally.names),t}},oo=class extends ft{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};oo.kind="catch";var ro=class extends ft{render(t){return"finally"+super.render(t)}};ro.kind="finally";var ki=class{constructor(t,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
2
|
-
`:""},this._extScope=t,this._scope=new Ye.Scope({parent:t}),this._nodes=[new bi]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,n){let o=this._extScope.value(t,n);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(t,n){return this._extScope.getValue(t,n)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,n,o,r){let s=this._scope.toName(n);return o!==void 0&&r&&(this._constants[s.str]=o),this._leafNode(new fi(t,s,o)),s}const(t,n,o){return this._def(Ye.varKinds.const,t,n,o)}let(t,n,o){return this._def(Ye.varKinds.let,t,n,o)}var(t,n,o){return this._def(Ye.varKinds.var,t,n,o)}assign(t,n,o){return this._leafNode(new ar(t,n,o))}add(t,n){return this._leafNode(new pi(t,D.operators.ADD,n))}code(t){return typeof t=="function"?t():t!==V.nil&&this._leafNode(new yi(t)),this}object(...t){let n=["{"];for(let[o,r]of t)n.length>1&&n.push(","),n.push(o),(o!==r||this.opts.es5)&&(n.push(":"),(0,V.addCodeArg)(n,r));return n.push("}"),new V._Code(n)}if(t,n,o){if(this._blockNode(new qt(t)),n&&o)this.code(n).else().code(o).endIf();else if(n)this.code(n).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new qt(t))}else(){return this._elseNode(new mn)}endIf(){return this._endBlockNode(qt,mn)}_for(t,n){return this._blockNode(t),n&&this.code(n).endFor(),this}for(t,n){return this._for(new _i(t),n)}forRange(t,n,o,r,s=this.opts.es5?Ye.varKinds.var:Ye.varKinds.let){let i=this._scope.toName(t);return this._for(new vi(s,i,n,o),()=>r(i))}forOf(t,n,o,r=Ye.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=n instanceof V.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,V._)`${i}.length`,a=>{this.var(s,(0,V._)`${i}[${a}]`),o(s)})}return this._for(new cr("of",r,s,n),()=>o(s))}forIn(t,n,o,r=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,V._)`Object.keys(${n})`,o);let s=this._scope.toName(t);return this._for(new cr("in",r,s,n),()=>o(s))}endFor(){return this._endBlockNode(Ut)}label(t){return this._leafNode(new mi(t))}break(t){return this._leafNode(new gi(t))}return(t){let n=new no;if(this._blockNode(n),this.code(t),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(no)}try(t,n,o){if(!n&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let r=new Ti;if(this._blockNode(r),this.code(t),n){let s=this.name("e");this._currNode=r.catch=new oo(s),n(s)}return o&&(this._currNode=r.finally=new ro,this.code(o)),this._endBlockNode(oo,ro)}throw(t){return this._leafNode(new hi(t))}block(t,n){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(n),this}endBlock(t){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-n;if(o<0||t!==void 0&&o!==t)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${t} expected`);return this._nodes.length=n,this}func(t,n=V.nil,o,r){return this._blockNode(new to(t,n,o)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(to)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,n){let o=this._currNode;if(o instanceof t||n&&o instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${t.kind}/${n.kind}`:t.kind}"`)}_elseNode(t){let n=this._currNode;if(!(n instanceof qt))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let n=this._nodes;n[n.length-1]=t}};D.CodeGen=ki;function zt(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function lr(e,t){return t instanceof V._CodeOrName?zt(e,t.names):e}function gn(e,t,n){if(e instanceof V.Name)return o(e);if(!r(e))return e;return new V._Code(e._items.reduce((s,i)=>(i instanceof V.Name&&(i=o(i)),i instanceof V._Code?s.push(...i._items):s.push(i),s),[]));function o(s){let i=n[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function r(s){return s instanceof V._Code&&s._items.some(i=>i instanceof V.Name&&t[i.str]===1&&n[i.str]!==void 0)}}function Qh(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function wu(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,V._)`!${Ci(e)}`}D.not=wu;var ey=Ru(D.operators.AND);function ty(...e){return e.reduce(ey)}D.and=ty;var ny=Ru(D.operators.OR);function oy(...e){return e.reduce(ny)}D.or=oy;function Ru(e){return(t,n)=>t===V.nil?n:n===V.nil?t:(0,V._)`${Ci(t)} ${e} ${Ci(n)}`}function Ci(e){return e instanceof V.Name?e:(0,V._)`(${e})`}});var q=w(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.checkStrictMode=B.getErrorPath=B.Type=B.useFunc=B.setEvaluated=B.evaluatedPropsToName=B.mergeEvaluated=B.eachItem=B.unescapeJsonPointer=B.escapeJsonPointer=B.escapeFragment=B.unescapeFragment=B.schemaRefOrVal=B.schemaHasRulesButRef=B.schemaHasRules=B.checkUnknownRules=B.alwaysValidSchema=B.toHash=void 0;var Z=F(),ry=Qn();function sy(e){let t={};for(let n of e)t[n]=!0;return t}B.toHash=sy;function iy(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Eu(e,t),!Au(t,e.self.RULES.all))}B.alwaysValidSchema=iy;function Eu(e,t=e.schema){let{opts:n,self:o}=e;if(!n.strictSchema||typeof t=="boolean")return;let r=o.RULES.keywords;for(let s in t)r[s]||Mu(e,`unknown keyword: "${s}"`)}B.checkUnknownRules=Eu;function Au(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}B.schemaHasRules=Au;function ay(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}B.schemaHasRulesButRef=ay;function cy({topSchemaRef:e,schemaPath:t},n,o,r){if(!r){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Z._)`${n}`}return(0,Z._)`${e}${t}${(0,Z.getProperty)(o)}`}B.schemaRefOrVal=cy;function ly(e){return $u(decodeURIComponent(e))}B.unescapeFragment=ly;function uy(e){return encodeURIComponent(Ri(e))}B.escapeFragment=uy;function Ri(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}B.escapeJsonPointer=Ri;function $u(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}B.unescapeJsonPointer=$u;function dy(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}B.eachItem=dy;function xu({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:o}){return(r,s,i,a)=>{let c=i===void 0?s:i instanceof Z.Name?(s instanceof Z.Name?e(r,s,i):t(r,s,i),i):s instanceof Z.Name?(t(r,i,s),s):n(s,i);return a===Z.Name&&!(c instanceof Z.Name)?o(r,c):c}}B.mergeEvaluated={props:xu({mergeNames:(e,t,n)=>e.if((0,Z._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,Z._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,Z._)`${n} || {}`).code((0,Z._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,Z._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,Z._)`${n} || {}`),xi(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Pu}),items:xu({mergeNames:(e,t,n)=>e.if((0,Z._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,Z._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,Z._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,Z._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Pu(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",(0,Z._)`{}`);return t!==void 0&&xi(e,n,t),n}B.evaluatedPropsToName=Pu;function xi(e,t,n){Object.keys(n).forEach(o=>e.assign((0,Z._)`${t}${(0,Z.getProperty)(o)}`,!0))}B.setEvaluated=xi;var Su={};function fy(e,t){return e.scopeValue("func",{ref:t,code:Su[t.code]||(Su[t.code]=new ry._Code(t.code))})}B.useFunc=fy;var wi;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(wi||(B.Type=wi={}));function py(e,t,n){if(e instanceof Z.Name){let o=t===wi.Num;return n?o?(0,Z._)`"[" + ${e} + "]"`:(0,Z._)`"['" + ${e} + "']"`:o?(0,Z._)`"/" + ${e}`:(0,Z._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Z.getProperty)(e).toString():"/"+Ri(e)}B.getErrorPath=py;function Mu(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}B.checkStrictMode=Mu});var Ue=w(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});var be=F(),my={data:new be.Name("data"),valCxt:new be.Name("valCxt"),instancePath:new be.Name("instancePath"),parentData:new be.Name("parentData"),parentDataProperty:new be.Name("parentDataProperty"),rootData:new be.Name("rootData"),dynamicAnchors:new be.Name("dynamicAnchors"),vErrors:new be.Name("vErrors"),errors:new be.Name("errors"),this:new be.Name("this"),self:new be.Name("self"),scope:new be.Name("scope"),json:new be.Name("json"),jsonPos:new be.Name("jsonPos"),jsonLen:new be.Name("jsonLen"),jsonPart:new be.Name("jsonPart")};Si.default=my});var so=w(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.extendErrors=_e.resetErrorsCount=_e.reportExtraError=_e.reportError=_e.keyword$DataError=_e.keywordError=void 0;var G=F(),dr=q(),Re=Ue();_e.keywordError={message:({keyword:e})=>(0,G.str)`must pass "${e}" keyword validation`};_e.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,G.str)`"${e}" keyword must be ${t} ($data)`:(0,G.str)`"${e}" keyword is invalid ($data)`};function gy(e,t=_e.keywordError,n,o){let{it:r}=e,{gen:s,compositeRule:i,allErrors:a}=r,c=Nu(e,t,n);o??(i||a)?Iu(s,c):Ou(r,(0,G._)`[${c}]`)}_e.reportError=gy;function hy(e,t=_e.keywordError,n){let{it:o}=e,{gen:r,compositeRule:s,allErrors:i}=o,a=Nu(e,t,n);Iu(r,a),s||i||Ou(o,Re.default.vErrors)}_e.reportExtraError=hy;function yy(e,t){e.assign(Re.default.errors,t),e.if((0,G._)`${Re.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,G._)`${Re.default.vErrors}.length`,t),()=>e.assign(Re.default.vErrors,null)))}_e.resetErrorsCount=yy;function by({gen:e,keyword:t,schemaValue:n,data:o,errsCount:r,it:s}){if(r===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",r,Re.default.errors,a=>{e.const(i,(0,G._)`${Re.default.vErrors}[${a}]`),e.if((0,G._)`${i}.instancePath === undefined`,()=>e.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Re.default.instancePath,s.errorPath))),e.assign((0,G._)`${i}.schemaPath`,(0,G.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,G._)`${i}.schema`,n),e.assign((0,G._)`${i}.data`,o))})}_e.extendErrors=by;function Iu(e,t){let n=e.const("err",t);e.if((0,G._)`${Re.default.vErrors} === null`,()=>e.assign(Re.default.vErrors,(0,G._)`[${n}]`),(0,G._)`${Re.default.vErrors}.push(${n})`),e.code((0,G._)`${Re.default.errors}++`)}function Ou(e,t){let{gen:n,validateName:o,schemaEnv:r}=e;r.$async?n.throw((0,G._)`new ${e.ValidationError}(${t})`):(n.assign((0,G._)`${o}.errors`,t),n.return(!1))}var Ht={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function Nu(e,t,n){let{createErrors:o}=e.it;return o===!1?(0,G._)`{}`:_y(e,t,n)}function _y(e,t,n={}){let{gen:o,it:r}=e,s=[vy(r,n),Ty(e,n)];return ky(e,t,s),o.object(...s)}function vy({errorPath:e},{instancePath:t}){let n=t?(0,G.str)`${e}${(0,dr.getErrorPath)(t,dr.Type.Str)}`:e;return[Re.default.instancePath,(0,G.strConcat)(Re.default.instancePath,n)]}function Ty({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:o}){let r=o?t:(0,G.str)`${t}/${e}`;return n&&(r=(0,G.str)`${r}${(0,dr.getErrorPath)(n,dr.Type.Str)}`),[Ht.schemaPath,r]}function ky(e,{params:t,message:n},o){let{keyword:r,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:p}=a;o.push([Ht.keyword,r],[Ht.params,typeof t=="function"?t(e):t||(0,G._)`{}`]),c.messages&&o.push([Ht.message,typeof n=="function"?n(e):n]),c.verbose&&o.push([Ht.schema,i],[Ht.parentSchema,(0,G._)`${d}${p}`],[Re.default.data,s]),l&&o.push([Ht.propertyName,l])}});var Lu=w(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.boolOrEmptySchema=hn.topBoolOrEmptySchema=void 0;var Cy=so(),wy=F(),Ry=Ue(),xy={message:"boolean schema is false"};function Sy(e){let{gen:t,schema:n,validateName:o}=e;n===!1?Fu(e,!1):typeof n=="object"&&n.$async===!0?t.return(Ry.default.data):(t.assign((0,wy._)`${o}.errors`,null),t.return(!0))}hn.topBoolOrEmptySchema=Sy;function Ey(e,t){let{gen:n,schema:o}=e;o===!1?(n.var(t,!1),Fu(e)):n.var(t,!0)}hn.boolOrEmptySchema=Ey;function Fu(e,t){let{gen:n,data:o}=e,r={gen:n,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Cy.reportError)(r,xy,void 0,t)}});var Ei=w(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.getRules=yn.isJSONType=void 0;var Ay=["string","number","integer","boolean","null","object","array"],$y=new Set(Ay);function Py(e){return typeof e=="string"&&$y.has(e)}yn.isJSONType=Py;function My(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}yn.getRules=My});var Ai=w(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.shouldUseRule=Tt.shouldUseGroup=Tt.schemaHasRulesForType=void 0;function Iy({schema:e,self:t},n){let o=t.RULES.types[n];return o&&o!==!0&&ju(e,o)}Tt.schemaHasRulesForType=Iy;function ju(e,t){return t.rules.some(n=>Du(e,n))}Tt.shouldUseGroup=ju;function Du(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(o=>e[o]!==void 0))}Tt.shouldUseRule=Du});var io=w(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.reportTypeError=ve.checkDataTypes=ve.checkDataType=ve.coerceAndCheckDataType=ve.getJSONTypes=ve.getSchemaTypes=ve.DataType=void 0;var Oy=Ei(),Ny=Ai(),Fy=so(),L=F(),Bu=q(),bn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(bn||(ve.DataType=bn={}));function Ly(e){let t=qu(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ve.getSchemaTypes=Ly;function qu(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Oy.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ve.getJSONTypes=qu;function jy(e,t){let{gen:n,data:o,opts:r}=e,s=Dy(t,r.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Ny.schemaHasRulesForType)(e,t[0]));if(i){let a=Pi(t,o,r.strictNumbers,bn.Wrong);n.if(a,()=>{s.length?By(e,t,s):Mi(e)})}return i}ve.coerceAndCheckDataType=jy;var Uu=new Set(["string","number","integer","boolean","null"]);function Dy(e,t){return t?e.filter(n=>Uu.has(n)||t==="array"&&n==="array"):[]}function By(e,t,n){let{gen:o,data:r,opts:s}=e,i=o.let("dataType",(0,L._)`typeof ${r}`),a=o.let("coerced",(0,L._)`undefined`);s.coerceTypes==="array"&&o.if((0,L._)`${i} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>o.assign(r,(0,L._)`${r}[0]`).assign(i,(0,L._)`typeof ${r}`).if(Pi(t,r,s.strictNumbers),()=>o.assign(a,r))),o.if((0,L._)`${a} !== undefined`);for(let l of n)(Uu.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);o.else(),Mi(e),o.endIf(),o.if((0,L._)`${a} !== undefined`,()=>{o.assign(r,a),qy(e,a)});function c(l){switch(l){case"string":o.elseIf((0,L._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,L._)`"" + ${r}`).elseIf((0,L._)`${r} === null`).assign(a,(0,L._)`""`);return;case"number":o.elseIf((0,L._)`${i} == "boolean" || ${r} === null
|
|
1
|
+
var 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
|
|
3
3
|
|| (${i} == "string" && ${r} && ${r} == +${r})`).assign(a,(0,L._)`+${r}`);return;case"integer":o.elseIf((0,L._)`${i} === "boolean" || ${r} === null
|
|
4
4
|
|| (${i} === "string" && ${r} && ${r} == +${r} && !(${r} % 1))`).assign(a,(0,L._)`+${r}`);return;case"boolean":o.elseIf((0,L._)`${r} === "false" || ${r} === 0 || ${r} === null`).assign(a,!1).elseIf((0,L._)`${r} === "true" || ${r} === 1`).assign(a,!0);return;case"null":o.elseIf((0,L._)`${r} === "" || ${r} === 0 || ${r} === false`),o.assign(a,null);return;case"array":o.elseIf((0,L._)`${i} === "string" || ${i} === "number"
|
|
5
|
-
|| ${i} === "boolean" || ${r} === null`).assign(a,(0,L._)`[${r}]`)}}}function qy({gen:e,parentData:t,parentDataProperty:n},o){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${n}]`,o))}function $i(e,t,n,o=bn.Correct){let r=o===bn.Correct?L.operators.EQ:L.operators.NEQ,s;switch(e){case"null":return(0,L._)`${t} ${r} null`;case"array":s=(0,L._)`Array.isArray(${t})`;break;case"object":s=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,L._)`typeof ${t} ${r} ${e}`}return o===bn.Correct?s:(0,L.not)(s);function i(a=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,a,n?(0,L._)`isFinite(${t})`:L.nil)}}ve.checkDataType=$i;function Pi(e,t,n,o){if(e.length===1)return $i(e[0],t,n,o);let r,s=(0,Bu.toHash)(e);if(s.array&&s.object){let i=(0,L._)`typeof ${t} != "object"`;r=s.null?i:(0,L._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else r=L.nil;s.number&&delete s.integer;for(let i in s)r=(0,L.and)(r,$i(i,t,n,o));return r}ve.checkDataTypes=Pi;var Uy={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function Mi(e){let t=zy(e);(0,Fy.reportError)(t,Uy)}ve.reportTypeError=Mi;function zy(e){let{gen:t,data:n,schema:o}=e,r=(0,Bu.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:n,schema:o.type,schemaCode:r,schemaValue:r,parentSchema:o,params:{},it:e}}});var Hu=w(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.assignDefaults=void 0;var _n=F(),Hy=q();function Vy(e,t){let{properties:n,items:o}=e.schema;if(t==="object"&&n)for(let r in n)zu(e,r,n[r].default);else t==="array"&&Array.isArray(o)&&o.forEach((r,s)=>zu(e,s,r.default))}fr.assignDefaults=Vy;function zu(e,t,n){let{gen:o,compositeRule:r,data:s,opts:i}=e;if(n===void 0)return;let a=(0,_n._)`${s}${(0,_n.getProperty)(t)}`;if(r){(0,Hy.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,_n._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,_n._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,_n._)`${a} = ${(0,_n.stringify)(n)}`)}});var ze=w(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.validateUnion=X.validateArray=X.usePattern=X.callValidateCode=X.schemaProperties=X.allSchemaProperties=X.noPropertyInData=X.propertyInData=X.isOwnProperty=X.hasPropFunc=X.reportMissingProp=X.checkMissingProp=X.checkReportMissingProp=void 0;var te=F(),Ii=q(),kt=Ue(),Gy=q();function Wy(e,t){let{gen:n,data:o,it:r}=e;n.if(Ni(n,o,t,r.opts.ownProperties),()=>{e.setParams({missingProperty:(0,te._)`${t}`},!0),e.error()})}X.checkReportMissingProp=Wy;function Ky({gen:e,data:t,it:{opts:n}},o,r){return(0,te.or)(...o.map(s=>(0,te.and)(Ni(e,t,s,n.ownProperties),(0,te._)`${r} = ${s}`)))}X.checkMissingProp=Ky;function Jy(e,t){e.setParams({missingProperty:t},!0),e.error()}X.reportMissingProp=Jy;function Vu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,te._)`Object.prototype.hasOwnProperty`})}X.hasPropFunc=Vu;function Oi(e,t,n){return(0,te._)`${Vu(e)}.call(${t}, ${n})`}X.isOwnProperty=Oi;function Xy(e,t,n,o){let r=(0,te._)`${t}${(0,te.getProperty)(n)} !== undefined`;return o?(0,te._)`${r} && ${Oi(e,t,n)}`:r}X.propertyInData=Xy;function Ni(e,t,n,o){let r=(0,te._)`${t}${(0,te.getProperty)(n)} === undefined`;return o?(0,te.or)(r,(0,te.not)(Oi(e,t,n))):r}X.noPropertyInData=Ni;function Gu(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}X.allSchemaProperties=Gu;function Yy(e,t){return Gu(t).filter(n=>!(0,Ii.alwaysValidSchema)(e,t[n]))}X.schemaProperties=Yy;function Zy({schemaCode:e,data:t,it:{gen:n,topSchemaRef:o,schemaPath:r,errorPath:s},it:i},a,c,l){let d=l?(0,te._)`${e}, ${t}, ${o}${r}`:t,p=[[kt.default.instancePath,(0,te.strConcat)(kt.default.instancePath,s)],[kt.default.parentData,i.parentData],[kt.default.parentDataProperty,i.parentDataProperty],[kt.default.rootData,kt.default.rootData]];i.opts.dynamicRef&&p.push([kt.default.dynamicAnchors,kt.default.dynamicAnchors]);let y=(0,te._)`${d}, ${n.object(...p)}`;return c!==te.nil?(0,te._)`${a}.call(${c}, ${y})`:(0,te._)`${a}(${y})`}X.callValidateCode=Zy;var Qy=(0,te._)`new RegExp`;function eb({gen:e,it:{opts:t}},n){let o=t.unicodeRegExp?"u":"",{regExp:r}=t.code,s=r(n,o);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,te._)`${r.code==="new RegExp"?Qy:(0,Gy.useFunc)(e,r)}(${n}, ${o})`})}X.usePattern=eb;function tb(e){let{gen:t,data:n,keyword:o,it:r}=e,s=t.name("valid");if(r.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,te._)`${n}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:o,dataProp:l,dataPropType:Ii.Type.Num},s),t.if((0,te.not)(s),a)})}}X.validateArray=tb;function nb(e){let{gen:t,schema:n,keyword:o,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Ii.alwaysValidSchema)(r,c))&&!r.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>n.forEach((c,l)=>{let d=e.subschema({keyword:o,schemaProp:l,compositeRule:!0},a);t.assign(i,(0,te._)`${i} || ${a}`),e.mergeValidEvaluated(d,a)||t.if((0,te.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}X.validateUnion=nb});var Ju=w(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.validateKeywordUsage=rt.validSchemaType=rt.funcKeywordCode=rt.macroKeywordCode=void 0;var xe=F(),Vt=Ue(),ob=ze(),rb=so();function sb(e,t){let{gen:n,keyword:o,schema:r,parentSchema:s,it:i}=e,a=t.macro.call(i.self,r,s,i),c=Ku(n,o,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=n.name("valid");e.subschema({schema:a,schemaPath:xe.nil,errSchemaPath:`${i.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}rt.macroKeywordCode=sb;function ib(e,t){var n;let{gen:o,keyword:r,schema:s,parentSchema:i,$data:a,it:c}=e;cb(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,d=Ku(o,r,l),p=o.let("valid");e.block$data(p,y),e.ok((n=t.valid)!==null&&n!==void 0?n:p);function y(){if(t.errors===!1)_(),t.modifying&&Wu(e),k(()=>e.error());else{let C=t.async?v():h();t.modifying&&Wu(e),k(()=>ab(e,C))}}function v(){let C=o.let("ruleErrs",null);return o.try(()=>_((0,xe._)`await `),E=>o.assign(p,!1).if((0,xe._)`${E} instanceof ${c.ValidationError}`,()=>o.assign(C,(0,xe._)`${E}.errors`),()=>o.throw(E))),C}function h(){let C=(0,xe._)`${d}.errors`;return o.assign(C,null),_(xe.nil),C}function _(C=t.async?(0,xe._)`await `:xe.nil){let E=c.opts.passContext?Vt.default.this:Vt.default.self,O=!("compile"in t&&!a||t.schema===!1);o.assign(p,(0,xe._)`${C}${(0,ob.callValidateCode)(e,d,E,O)}`,t.modifying)}function k(C){var E;o.if((0,xe.not)((E=t.valid)!==null&&E!==void 0?E:p),C)}}rt.funcKeywordCode=ib;function Wu(e){let{gen:t,data:n,it:o}=e;t.if(o.parentData,()=>t.assign(n,(0,xe._)`${o.parentData}[${o.parentDataProperty}]`))}function ab(e,t){let{gen:n}=e;n.if((0,xe._)`Array.isArray(${t})`,()=>{n.assign(Vt.default.vErrors,(0,xe._)`${Vt.default.vErrors} === null ? ${t} : ${Vt.default.vErrors}.concat(${t})`).assign(Vt.default.errors,(0,xe._)`${Vt.default.vErrors}.length`),(0,rb.extendErrors)(e)},()=>e.error())}function cb({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Ku(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,xe.stringify)(n)})}function lb(e,t,n=!1){return!t.length||t.some(o=>o==="array"?Array.isArray(e):o==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==o||n&&typeof e>"u")}rt.validSchemaType=lb;function ub({schema:e,opts:t,self:n,errSchemaPath:o},r,s){if(Array.isArray(r.keyword)?!r.keyword.includes(s):r.keyword!==s)throw new Error("ajv implementation error");let i=r.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(r.validateSchema&&!r.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${o}": `+n.errorsText(r.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}rt.validateKeywordUsage=ub});var Yu=w(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.extendSubschemaMode=Ct.extendSubschemaData=Ct.getSubschema=void 0;var st=F(),Xu=q();function db(e,{keyword:t,schemaProp:n,schema:o,schemaPath:r,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,st._)`${e.schemaPath}${(0,st.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,st._)`${e.schemaPath}${(0,st.getProperty)(t)}${(0,st.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Xu.escapeFragment)(n)}`}}if(o!==void 0){if(r===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:r,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Ct.getSubschema=db;function fb(e,t,{dataProp:n,dataPropType:o,data:r,dataTypes:s,propertyName:i}){if(r!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(n!==void 0){let{errorPath:l,dataPathArr:d,opts:p}=t,y=a.let("data",(0,st._)`${t.data}${(0,st.getProperty)(n)}`,!0);c(y),e.errorPath=(0,st.str)`${l}${(0,Xu.getErrorPath)(n,o,p.jsPropertySyntax)}`,e.parentDataProperty=(0,st._)`${n}`,e.dataPathArr=[...d,e.parentDataProperty]}if(r!==void 0){let l=r instanceof st.Name?r:a.let("data",r,!0);c(l),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Ct.extendSubschemaData=fb;function pb(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:o,createErrors:r,allErrors:s}){o!==void 0&&(e.compositeRule=o),r!==void 0&&(e.createErrors=r),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}Ct.extendSubschemaMode=pb});var Fi=w((KS,Zu)=>{"use strict";Zu.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var o,r,s;if(Array.isArray(t)){if(o=t.length,o!=n.length)return!1;for(r=o;r--!==0;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),o=s.length,o!==Object.keys(n).length)return!1;for(r=o;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[r]))return!1;for(r=o;r--!==0;){var i=s[r];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n}});var ed=w((JS,Qu)=>{"use strict";var wt=Qu.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var o=typeof n=="function"?n:n.pre||function(){},r=n.post||function(){};pr(t,o,r,e,"",e)};wt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};wt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function pr(e,t,n,o,r,s,i,a,c,l){if(o&&typeof o=="object"&&!Array.isArray(o)){t(o,r,s,i,a,c,l);for(var d in o){var p=o[d];if(Array.isArray(p)){if(d in wt.arrayKeywords)for(var y=0;y<p.length;y++)pr(e,t,n,p[y],r+"/"+d+"/"+y,s,r,d,o,y)}else if(d in wt.propsKeywords){if(p&&typeof p=="object")for(var v in p)pr(e,t,n,p[v],r+"/"+d+"/"+mb(v),s,r,d,o,v)}else(d in wt.keywords||e.allKeys&&!(d in wt.skipKeywords))&&pr(e,t,n,p,r+"/"+d,s,r,d,o)}n(o,r,s,i,a,c,l)}}function mb(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ao=w($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.getSchemaRefs=$e.resolveUrl=$e.normalizeId=$e._getFullPath=$e.getFullPath=$e.inlineRef=void 0;var gb=q(),hb=Fi(),yb=ed(),bb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _b(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Li(e):t?td(e)<=t:!1}$e.inlineRef=_b;var vb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Li(e){for(let t in e){if(vb.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(Li)||typeof n=="object"&&Li(n))return!0}return!1}function td(e){let t=0;for(let n in e){if(n==="$ref")return 1/0;if(t++,!bb.has(n)&&(typeof e[n]=="object"&&(0,gb.eachItem)(e[n],o=>t+=td(o)),t===1/0))return 1/0}return t}function nd(e,t="",n){n!==!1&&(t=vn(t));let o=e.parse(t);return od(e,o)}$e.getFullPath=nd;function od(e,t){return e.serialize(t).split("#")[0]+"#"}$e._getFullPath=od;var Tb=/#\/?$/;function vn(e){return e?e.replace(Tb,""):""}$e.normalizeId=vn;function kb(e,t,n){return n=vn(n),e.resolve(t,n)}$e.resolveUrl=kb;var Cb=/^[a-z_][-a-z0-9._]*$/i;function wb(e,t){if(typeof e=="boolean")return{};let{schemaId:n,uriResolver:o}=this.opts,r=vn(e[n]||t),s={"":r},i=nd(o,r,!1),a={},c=new Set;return yb(e,{allKeys:!0},(p,y,v,h)=>{if(h===void 0)return;let _=i+y,k=s[h];typeof p[n]=="string"&&(k=C.call(this,p[n])),E.call(this,p.$anchor),E.call(this,p.$dynamicAnchor),s[y]=k;function C(O){let U=this.opts.uriResolver.resolve;if(O=vn(k?U(k,O):O),c.has(O))throw d(O);c.add(O);let M=this.refs[O];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?l(p,M.schema,O):O!==vn(_)&&(O[0]==="#"?(l(p,a[O],O),a[O]=p):this.refs[O]=_),O}function E(O){if(typeof O=="string"){if(!Cb.test(O))throw new Error(`invalid anchor "${O}"`);C.call(this,`#${O}`)}}}),a;function l(p,y,v){if(y!==void 0&&!hb(p,y))throw d(v)}function d(p){return new Error(`reference "${p}" resolves to more than one schema`)}}$e.getSchemaRefs=wb});var uo=w(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.getData=Rt.KeywordCxt=Rt.validateFunctionCode=void 0;var cd=Lu(),rd=io(),Di=Ai(),mr=io(),Rb=Hu(),lo=Ju(),ji=Yu(),A=F(),N=Ue(),xb=ao(),pt=q(),co=so();function Sb(e){if(dd(e)&&(fd(e),ud(e))){$b(e);return}ld(e,()=>(0,cd.topBoolOrEmptySchema)(e))}Rt.validateFunctionCode=Sb;function ld({gen:e,validateName:t,schema:n,schemaEnv:o,opts:r},s){r.code.es5?e.func(t,(0,A._)`${N.default.data}, ${N.default.valCxt}`,o.$async,()=>{e.code((0,A._)`"use strict"; ${sd(n,r)}`),Ab(e,r),e.code(s)}):e.func(t,(0,A._)`${N.default.data}, ${Eb(r)}`,o.$async,()=>e.code(sd(n,r)).code(s))}function Eb(e){return(0,A._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${e.dynamicRef?(0,A._)`, ${N.default.dynamicAnchors}={}`:A.nil}}={}`}function Ab(e,t){e.if(N.default.valCxt,()=>{e.var(N.default.instancePath,(0,A._)`${N.default.valCxt}.${N.default.instancePath}`),e.var(N.default.parentData,(0,A._)`${N.default.valCxt}.${N.default.parentData}`),e.var(N.default.parentDataProperty,(0,A._)`${N.default.valCxt}.${N.default.parentDataProperty}`),e.var(N.default.rootData,(0,A._)`${N.default.valCxt}.${N.default.rootData}`),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,A._)`${N.default.valCxt}.${N.default.dynamicAnchors}`)},()=>{e.var(N.default.instancePath,(0,A._)`""`),e.var(N.default.parentData,(0,A._)`undefined`),e.var(N.default.parentDataProperty,(0,A._)`undefined`),e.var(N.default.rootData,N.default.data),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,A._)`{}`)})}function $b(e){let{schema:t,opts:n,gen:o}=e;ld(e,()=>{n.$comment&&t.$comment&&md(e),Nb(e),o.let(N.default.vErrors,null),o.let(N.default.errors,0),n.unevaluated&&Pb(e),pd(e),jb(e)})}function Pb(e){let{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,A._)`${n}.evaluated`),t.if((0,A._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,A._)`${e.evaluated}.props`,(0,A._)`undefined`)),t.if((0,A._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,A._)`${e.evaluated}.items`,(0,A._)`undefined`))}function sd(e,t){let n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,A._)`/*# sourceURL=${n} */`:A.nil}function Mb(e,t){if(dd(e)&&(fd(e),ud(e))){Ib(e,t);return}(0,cd.boolOrEmptySchema)(e,t)}function ud({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function dd(e){return typeof e.schema!="boolean"}function Ib(e,t){let{schema:n,gen:o,opts:r}=e;r.$comment&&n.$comment&&md(e),Fb(e),Lb(e);let s=o.const("_errs",N.default.errors);pd(e,s),o.var(t,(0,A._)`${s} === ${N.default.errors}`)}function fd(e){(0,pt.checkUnknownRules)(e),Ob(e)}function pd(e,t){if(e.opts.jtd)return id(e,[],!1,t);let n=(0,rd.getSchemaTypes)(e.schema),o=(0,rd.coerceAndCheckDataType)(e,n);id(e,n,!o,t)}function Ob(e){let{schema:t,errSchemaPath:n,opts:o,self:r}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,pt.schemaHasRulesButRef)(t,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Nb(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,pt.checkStrictMode)(e,"default is ignored in the schema root")}function Fb(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,xb.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Lb(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function md({gen:e,schemaEnv:t,schema:n,errSchemaPath:o,opts:r}){let s=n.$comment;if(r.$comment===!0)e.code((0,A._)`${N.default.self}.logger.log(${s})`);else if(typeof r.$comment=="function"){let i=(0,A.str)`${o}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,A._)`${N.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function jb(e){let{gen:t,schemaEnv:n,validateName:o,ValidationError:r,opts:s}=e;n.$async?t.if((0,A._)`${N.default.errors} === 0`,()=>t.return(N.default.data),()=>t.throw((0,A._)`new ${r}(${N.default.vErrors})`)):(t.assign((0,A._)`${o}.errors`,N.default.vErrors),s.unevaluated&&Db(e),t.return((0,A._)`${N.default.errors} === 0`))}function Db({gen:e,evaluated:t,props:n,items:o}){n instanceof A.Name&&e.assign((0,A._)`${t}.props`,n),o instanceof A.Name&&e.assign((0,A._)`${t}.items`,o)}function id(e,t,n,o){let{gen:r,schema:s,data:i,allErrors:a,opts:c,self:l}=e,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,pt.schemaHasRulesButRef)(s,d))){r.block(()=>hd(e,"$ref",d.all.$ref.definition));return}c.jtd||Bb(e,t),r.block(()=>{for(let y of d.rules)p(y);p(d.post)});function p(y){(0,Di.shouldUseGroup)(s,y)&&(y.type?(r.if((0,mr.checkDataType)(y.type,i,c.strictNumbers)),ad(e,y),t.length===1&&t[0]===y.type&&n&&(r.else(),(0,mr.reportTypeError)(e)),r.endIf()):ad(e,y),a||r.if((0,A._)`${N.default.errors} === ${o||0}`))}}function ad(e,t){let{gen:n,schema:o,opts:{useDefaults:r}}=e;r&&(0,Rb.assignDefaults)(e,t.type),n.block(()=>{for(let s of t.rules)(0,Di.shouldUseRule)(o,s)&&hd(e,s.keyword,s.definition,t.type)})}function Bb(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(qb(e,t),e.opts.allowUnionTypes||Ub(e,t),zb(e,e.dataTypes))}function qb(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{gd(e.dataTypes,n)||Bi(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),Vb(e,t)}}function Ub(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Bi(e,"use allowUnionTypes to allow union type keyword")}function zb(e,t){let n=e.self.RULES.all;for(let o in n){let r=n[o];if(typeof r=="object"&&(0,Di.shouldUseRule)(e.schema,r)){let{type:s}=r.definition;s.length&&!s.some(i=>Hb(t,i))&&Bi(e,`missing type "${s.join(",")}" for keyword "${o}"`)}}}function Hb(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function gd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Vb(e,t){let n=[];for(let o of e.dataTypes)gd(t,o)?n.push(o):t.includes("integer")&&o==="number"&&n.push("integer");e.dataTypes=n}function Bi(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,pt.checkStrictMode)(e,t,e.opts.strictTypes)}var gr=class{constructor(t,n,o){if((0,lo.validateKeywordUsage)(t,n,o),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=o,this.data=t.data,this.schema=t.schema[o],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,pt.schemaRefOrVal)(t,this.schema,o,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",yd(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,lo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",N.default.errors))}result(t,n,o){this.failResult((0,A.not)(t),n,o)}failResult(t,n,o){this.gen.if(t),o?o():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,A.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:n}=this;this.fail((0,A._)`${n} !== undefined && (${(0,A.or)(this.invalid$data(),t)})`)}error(t,n,o){if(n){this.setParams(n),this._error(t,o),this.setParams({});return}this._error(t,o)}_error(t,n){(t?co.reportExtraError:co.reportError)(this,this.def.error,n)}$dataError(){(0,co.reportError)(this,this.def.$dataError||co.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,co.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,o=A.nil){this.gen.block(()=>{this.check$data(t,o),n()})}check$data(t=A.nil,n=A.nil){if(!this.$data)return;let{gen:o,schemaCode:r,schemaType:s,def:i}=this;o.if((0,A.or)((0,A._)`${r} === undefined`,n)),t!==A.nil&&o.assign(t,!0),(s.length||i.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),t!==A.nil&&o.assign(t,!1)),o.else()}invalid$data(){let{gen:t,schemaCode:n,schemaType:o,def:r,it:s}=this;return(0,A.or)(i(),a());function i(){if(o.length){if(!(n instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(o)?o:[o];return(0,A._)`${(0,mr.checkDataTypes)(c,n,s.opts.strictNumbers,mr.DataType.Wrong)}`}return A.nil}function a(){if(r.validateSchema){let c=t.scopeValue("validate$data",{ref:r.validateSchema});return(0,A._)`!${c}(${n})`}return A.nil}}subschema(t,n){let o=(0,ji.getSubschema)(this.it,t);(0,ji.extendSubschemaData)(o,this.it,t),(0,ji.extendSubschemaMode)(o,t);let r={...this.it,...o,items:void 0,props:void 0};return Mb(r,n),r}mergeEvaluated(t,n){let{it:o,gen:r}=this;o.opts.unevaluated&&(o.props!==!0&&t.props!==void 0&&(o.props=pt.mergeEvaluated.props(r,t.props,o.props,n)),o.items!==!0&&t.items!==void 0&&(o.items=pt.mergeEvaluated.items(r,t.items,o.items,n)))}mergeValidEvaluated(t,n){let{it:o,gen:r}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return r.if(n,()=>this.mergeEvaluated(t,A.Name)),!0}};Rt.KeywordCxt=gr;function hd(e,t,n,o){let r=new gr(e,n,t);"code"in n?n.code(r,o):r.$data&&n.validate?(0,lo.funcKeywordCode)(r,n):"macro"in n?(0,lo.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,lo.funcKeywordCode)(r,n)}var Gb=/^\/(?:[^~]|~0|~1)*$/,Wb=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function yd(e,{dataLevel:t,dataNames:n,dataPathArr:o}){let r,s;if(e==="")return N.default.rootData;if(e[0]==="/"){if(!Gb.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);r=e,s=N.default.rootData}else{let l=Wb.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let d=+l[1];if(r=l[2],r==="#"){if(d>=t)throw new Error(c("property/index",d));return o[t-d]}if(d>t)throw new Error(c("data",d));if(s=n[t-d],!r)return s}let i=s,a=r.split("/");for(let l of a)l&&(s=(0,A._)`${s}${(0,A.getProperty)((0,pt.unescapeJsonPointer)(l))}`,i=(0,A._)`${i} && ${s}`);return i;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Rt.getData=yd});var hr=w(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var qi=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ui.default=qi});var fo=w(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var zi=ao(),Hi=class extends Error{constructor(t,n,o,r){super(r||`can't resolve reference ${o} from id ${n}`),this.missingRef=(0,zi.resolveUrl)(t,n,o),this.missingSchema=(0,zi.normalizeId)((0,zi.getFullPath)(t,this.missingRef))}};Vi.default=Hi});var po=w(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.resolveSchema=He.getCompilingSchema=He.resolveRef=He.compileSchema=He.SchemaEnv=void 0;var Ze=F(),Kb=hr(),Gt=Ue(),Qe=ao(),bd=q(),Jb=uo(),Tn=class{constructor(t){var n;this.refs={},this.dynamicAnchors={};let o;typeof t.schema=="object"&&(o=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Qe.normalizeId)(o?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=o?.$async,this.refs={}}};He.SchemaEnv=Tn;function Wi(e){let t=_d.call(this,e);if(t)return t;let n=(0,Qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:r}=this.opts.code,{ownProperties:s}=this.opts,i=new Ze.CodeGen(this.scope,{es5:o,lines:r,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:Kb.default,code:(0,Ze._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Gt.default.data,parentData:Gt.default.parentData,parentDataProperty:Gt.default.parentDataProperty,dataNames:[Gt.default.data],dataPathArr:[Ze.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ze.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ze.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ze._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,Jb.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();d=`${i.scopeRefs(Gt.default.scope)}return ${p}`,this.opts.code.process&&(d=this.opts.code.process(d,e));let v=new Function(`${Gt.default.self}`,`${Gt.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:v}),v.errors=null,v.schema=e.schema,v.schemaEnv=e,e.$async&&(v.$async=!0),this.opts.code.source===!0&&(v.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:_}=l;v.evaluated={props:h instanceof Ze.Name?void 0:h,items:_ instanceof Ze.Name?void 0:_,dynamicProps:h instanceof Ze.Name,dynamicItems:_ instanceof Ze.Name},v.source&&(v.source.evaluated=(0,Ze.stringify)(v.evaluated))}return e.validate=v,e}catch(p){throw delete e.validate,delete e.validateName,d&&this.logger.error("Error compiling schema, function code:",d),p}finally{this._compilations.delete(e)}}He.compileSchema=Wi;function Xb(e,t,n){var o;n=(0,Qe.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let s=Qb.call(this,e,n);if(s===void 0){let i=(o=e.localRefs)===null||o===void 0?void 0:o[n],{schemaId:a}=this.opts;i&&(s=new Tn({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=Yb.call(this,s)}He.resolveRef=Xb;function Yb(e){return(0,Qe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Wi.call(this,e)}function _d(e){for(let t of this._compilations)if(Zb(t,e))return t}He.getCompilingSchema=_d;function Zb(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Qb(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||yr.call(this,e,t)}function yr(e,t){let n=this.opts.uriResolver.parse(t),o=(0,Qe._getFullPath)(this.opts.uriResolver,n),r=(0,Qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===r)return Gi.call(this,n,e);let s=(0,Qe.normalizeId)(o),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=yr.call(this,e,i);return typeof a?.schema!="object"?void 0:Gi.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Wi.call(this,i),s===(0,Qe.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(r=(0,Qe.resolveUrl)(this.opts.uriResolver,r,l)),new Tn({schema:a,schemaId:c,root:e,baseId:r})}return Gi.call(this,n,i)}}He.resolveSchema=yr;var e_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gi(e,{baseId:t,schema:n,root:o}){var r;if(((r=e.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,bd.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!e_.has(a)&&l&&(t=(0,Qe.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,bd.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Qe.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=yr.call(this,o,a)}let{schemaId:i}=this.opts;if(s=s||new Tn({schema:n,schemaId:i,root:o,baseId:t}),s.schema!==s.root.schema)return s}});var vd=w((tE,t_)=>{t_.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Xi=w((nE,xd)=>{"use strict";var n_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Ki=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Cd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ji(e){let t="",n=0,o=0;for(o=0;o<e.length;o++)if(n=e[o].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[o];break}for(o+=1;o<e.length;o++){if(n=e[o].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[o]}return t}var r_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Td(e){return e.length=0,!0}function s_(e,t,n){if(e.length){let o=Ji(e);if(o!=="")t.push(o);else return n.error=!0,!1;e.length=0}return!0}function i_(e){let t=0,n={error:!1,address:"",zone:""},o=[],r=[],s=!1,i=!1,a=s_;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(r,o,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),o.push(":");continue}else if(l==="%"){if(!a(r,o,n))break;a=Td}else{r.push(l);continue}}return r.length&&(a===Td?n.zone=r.join(""):i?o.push(r.join("")):o.push(Ji(r))),n.address=o.join(""),n}function wd(e){if(a_(e,":")<2)return{host:e,isIPV6:!1};let t=i_(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,o=t.address;return t.zone&&(n+="%"+t.zone,o+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:o}}}function a_(e,t){let n=0;for(let o=0;o<e.length;o++)e[o]===t&&n++;return n}function c_(e){let t=e,n=[],o=-1,r=0;for(;r=t.length;){if(r===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(r===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(r===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((o=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,o)),t=t.slice(o)}return n.join("")}var l_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},u_=/[@/?#:]/g,d_=/[@/?#]/g;function Rd(e,t){let n=t?d_:u_;return n.lastIndex=0,e.replace(n,o=>l_[o])}function f_(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let o=0;o<e.length;o++){if(e[o]==="%"&&o+2<e.length){let r=e.slice(o+1,o+3);if(Ki(r)){let s=r.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Cd(i)?n+=i:n+="%"+s,o+=2;continue}}n+=e[o]}return n}function p_(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Ki(o)){let r=o.toUpperCase(),s=String.fromCharCode(parseInt(r,16));s!=="."&&Cd(s)?t+=s:t+="%"+r,n+=2;continue}}o_(e[n])?t+=e[n]:t+=escape(e[n])}return t}function m_(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Ki(o)){t+="%"+o.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function g_(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!kd(n)){let o=wd(n);o.isIPV6===!0?n=`[${o.escapedHost}]`:n=Rd(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}xd.exports={nonSimpleDomain:r_,recomposeAuthority:g_,reescapeHostDelimiters:Rd,normalizePercentEncoding:f_,normalizePathEncoding:p_,escapePreservingEscapes:m_,removeDotSegments:c_,isIPv4:kd,isUUID:n_,normalizeIPv6:wd,stringArrayToHexStripped:Ji}});var Pd=w((oE,$d)=>{"use strict";var{isUUID:h_}=Xi(),y_=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,b_=["http","https","ws","wss","urn","urn:uuid"];function __(e){return b_.indexOf(e)!==-1}function Yi(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Sd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Ed(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function v_(e){return e.secure=Yi(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function T_(e){if((e.port===(Yi(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function k_(e,t){if(!e.path)return e.error="URN can not be parsed",e;let n=e.path.match(y_);if(n){let o=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];let r=`${o}:${t.nid||e.nid}`,s=Zi(r);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function C_(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=t.scheme||e.scheme||"urn",o=e.nid.toLowerCase(),r=`${n}:${t.nid||o}`,s=Zi(r);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${o||t.nid}:${a}`,t.skipEscape=!0,i}function w_(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!h_(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function R_(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Ad={scheme:"http",domainHost:!0,parse:Sd,serialize:Ed},x_={scheme:"https",domainHost:Ad.domainHost,parse:Sd,serialize:Ed},br={scheme:"ws",domainHost:!0,parse:v_,serialize:T_},S_={scheme:"wss",domainHost:br.domainHost,parse:br.parse,serialize:br.serialize},E_={scheme:"urn",parse:k_,serialize:C_,skipNormalize:!0},A_={scheme:"urn:uuid",parse:w_,serialize:R_,skipNormalize:!0},_r={http:Ad,https:x_,ws:br,wss:S_,urn:E_,"urn:uuid":A_};Object.setPrototypeOf(_r,null);function Zi(e){return e&&(_r[e]||_r[e.toLowerCase()])||void 0}$d.exports={wsIsSecure:Yi,SCHEMES:_r,isValidSchemeName:__,getSchemeHandler:Zi}});var Ld=w((rE,vr)=>{"use strict";var{normalizeIPv6:$_,removeDotSegments:mo,recomposeAuthority:P_,normalizePercentEncoding:M_,normalizePathEncoding:I_,escapePreservingEscapes:O_,reescapeHostDelimiters:N_,isIPv4:F_,nonSimpleDomain:L_}=Xi(),{SCHEMES:j_,getSchemeHandler:Id}=Pd();function D_(e,t){return typeof e=="string"?e=H_(e,t):typeof e=="object"&&(e=kn(Wt(e,t),t)),e}function B_(e,t,n){let o=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=Od(kn(e,o),kn(t,o),o,!0);return o.skipEscape=!0,Wt(r,o)}function Od(e,t,n,o){let r={};return o||(e=kn(Wt(e,n),n),t=kn(Wt(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(r.scheme=t.scheme,r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=mo(t.path||""),r.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=mo(t.path||""),r.query=t.query):(t.path?(t.path[0]==="/"?r.path=mo(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?r.path="/"+t.path:e.path?r.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:r.path=t.path,r.path=mo(r.path)),r.query=t.query):(r.path=e.path,t.query!==void 0?r.query=t.query:r.query=e.query),r.userinfo=e.userinfo,r.host=e.host,r.port=e.port),r.scheme=e.scheme),r.fragment=t.fragment,r}function q_(e,t,n){let o=Md(e,n),r=Md(t,n);return o!==void 0&&r!==void 0&&o.toLowerCase()===r.toLowerCase()}function Wt(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},o=Object.assign({},t),r=[],s=Id(o.scheme||n.scheme);s&&s.serialize&&s.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=M_(n.path):(n.path=O_(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),o.reference!=="suffix"&&n.scheme&&r.push(n.scheme,":");let i=P_(n);if(i!==void 0&&(o.reference!=="suffix"&&r.push("//"),r.push(i),n.path&&n.path[0]!=="/"&&r.push("/")),n.path!==void 0){let a=n.path;!o.absolutePath&&(!s||!s.absolutePath)&&(a=mo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),r.push(a)}return n.query!==void 0&&r.push("?",n.query),n.fragment!==void 0&&r.push("#",n.fragment),r.join("")}var U_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function z_(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Nd(e,t){let n=Object.assign({},t),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1,s=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);let i=e.match(U_);if(i){o.scheme=i[1],o.userinfo=i[3],o.host=i[4],o.port=parseInt(i[5],10),o.path=i[6]||"",o.query=i[7],o.fragment=i[8],isNaN(o.port)&&(o.port=i[5]);let a=z_(o,i);if(a!==void 0&&(o.error=o.error||a,r=!0),o.host)if(F_(o.host)===!1){let d=$_(o.host);o.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==o.reference&&(o.error=o.error||"URI is not a "+n.reference+" reference.");let c=Id(n.scheme||o.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&o.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&L_(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(l){o.error=o.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=N_(unescape(o.host),s))),o.path&&(o.path=I_(o.path)),o.fragment))try{o.fragment=encodeURI(decodeURIComponent(o.fragment))}catch{o.error=o.error||"URI malformed"}c&&c.parse&&c.parse(o,n)}else o.error=o.error||"URI can not be parsed.";return{parsed:o,malformedAuthorityOrPort:r}}function kn(e,t){return Nd(e,t).parsed}function H_(e,t){return Fd(e,t).normalized}function Fd(e,t){let{parsed:n,malformedAuthorityOrPort:o}=Nd(e,t);return{normalized:o?e:Wt(n,t),malformedAuthorityOrPort:o}}function Md(e,t){if(typeof e=="string"){let{normalized:n,malformedAuthorityOrPort:o}=Fd(e,t);return o?void 0:n}if(typeof e=="object")return Wt(e,t)}var Qi={SCHEMES:j_,normalize:D_,resolve:B_,resolveComponent:Od,equal:q_,serialize:Wt,parse:kn};vr.exports=Qi;vr.exports.default=Qi;vr.exports.fastUri=Qi});var Dd=w(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var jd=Ld();jd.code='require("ajv/dist/runtime/uri").default';ea.default=jd});var Wd=w(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.CodeGen=pe.Name=pe.nil=pe.stringify=pe.str=pe._=pe.KeywordCxt=void 0;var V_=uo();Object.defineProperty(pe,"KeywordCxt",{enumerable:!0,get:function(){return V_.KeywordCxt}});var Cn=F();Object.defineProperty(pe,"_",{enumerable:!0,get:function(){return Cn._}});Object.defineProperty(pe,"str",{enumerable:!0,get:function(){return Cn.str}});Object.defineProperty(pe,"stringify",{enumerable:!0,get:function(){return Cn.stringify}});Object.defineProperty(pe,"nil",{enumerable:!0,get:function(){return Cn.nil}});Object.defineProperty(pe,"Name",{enumerable:!0,get:function(){return Cn.Name}});Object.defineProperty(pe,"CodeGen",{enumerable:!0,get:function(){return Cn.CodeGen}});var G_=hr(),Hd=fo(),W_=Ei(),go=po(),K_=F(),ho=ao(),Tr=io(),na=q(),Bd=vd(),J_=Dd(),Vd=(e,t)=>new RegExp(e,t);Vd.code="new RegExp";var X_=["removeAdditional","useDefaults","coerceTypes"],Y_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Z_={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Q_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},qd=200;function ev(e){var t,n,o,r,s,i,a,c,l,d,p,y,v,h,_,k,C,E,O,U,M,Q,Ie,ee,Ge;let nt=e.strict,an=(t=e.code)===null||t===void 0?void 0:t.optimize,at=an===!0||an===void 0?1:an||0,Oe=(o=(n=e.code)===null||n===void 0?void 0:n.regExp)!==null&&o!==void 0?o:Vd,ct=(r=e.uriResolver)!==null&&r!==void 0?r:J_.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:nt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:nt)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=e.strictTypes)!==null&&l!==void 0?l:nt)!==null&&d!==void 0?d:"log",strictTuples:(y=(p=e.strictTuples)!==null&&p!==void 0?p:nt)!==null&&y!==void 0?y:"log",strictRequired:(h=(v=e.strictRequired)!==null&&v!==void 0?v:nt)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:at,regExp:Oe}:{optimize:at,regExp:Oe},loopRequired:(_=e.loopRequired)!==null&&_!==void 0?_:qd,loopEnum:(k=e.loopEnum)!==null&&k!==void 0?k:qd,meta:(C=e.meta)!==null&&C!==void 0?C:!0,messages:(E=e.messages)!==null&&E!==void 0?E:!0,inlineRefs:(O=e.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(U=e.schemaId)!==null&&U!==void 0?U:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(Q=e.validateSchema)!==null&&Q!==void 0?Q:!0,validateFormats:(Ie=e.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(ee=e.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(Ge=e.int32range)!==null&&Ge!==void 0?Ge:!0,uriResolver:ct}}var yo=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...ev(t)};let{es5:n,lines:o}=this.opts.code;this.scope=new K_.ValueScope({scope:{},prefixes:Y_,es5:n,lines:o}),this.logger=iv(t.logger);let r=t.validateFormats;t.validateFormats=!1,this.RULES=(0,W_.getRules)(),Ud.call(this,Z_,t,"NOT SUPPORTED"),Ud.call(this,Q_,t,"DEPRECATED","warn"),this._metaOpts=rv.call(this),t.formats&&nv.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&ov.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),tv.call(this),t.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:n,schemaId:o}=this.opts,r=Bd;o==="id"&&(r={...Bd},r.id=r.$id,delete r.$id),n&&t&&this.addMetaSchema(r,r[o],!1)}defaultMeta(){let{meta:t,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[n]||t:void 0}validate(t,n){let o;if(typeof t=="string"){if(o=this.getSchema(t),!o)throw new Error(`no schema with key or ref "${t}"`)}else o=this.compile(t);let r=o(n);return"$async"in o||(this.errors=o.errors),r}compile(t,n){let o=this._addSchema(t,n);return o.validate||this._compileSchemaEnv(o)}compileAsync(t,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return r.call(this,t,n);async function r(d,p){await s.call(this,d.$schema);let y=this._addSchema(d,p);return y.validate||i.call(this,y)}async function s(d){d&&!this.getSchema(d)&&await r.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(p){if(!(p instanceof Hd.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:p}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${p} cannot be resolved`)}async function c(d){let p=await l.call(this,d);this.refs[d]||await s.call(this,p.$schema),this.refs[d]||this.addSchema(p,d,n)}async function l(d){let p=this._loading[d];if(p)return p;try{return await(this._loading[d]=o(d))}finally{delete this._loading[d]}}}addSchema(t,n,o,r=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,o,r);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return n=(0,ho.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(t,o,n,r,!0),this}addMetaSchema(t,n,o=this.opts.validateSchema){return this.addSchema(t,n,!0,o),this}validateSchema(t,n){if(typeof t=="boolean")return!0;let o;if(o=t.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(o,t);if(!r&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return r}getSchema(t){let n;for(;typeof(n=zd.call(this,t))=="string";)t=n;if(n===void 0){let{schemaId:o}=this.opts,r=new go.SchemaEnv({schema:{},schemaId:o});if(n=go.resolveSchema.call(this,r,t),!n)return;this.refs[t]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=zd.call(this,t);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let n=t;this._cache.delete(n);let o=t[this.opts.schemaId];return o&&(o=(0,ho.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let n of t)this.addKeyword(n);return this}addKeyword(t,n){let o;if(typeof t=="string")o=t,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=o);else if(typeof t=="object"&&n===void 0){if(n=t,o=n.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(cv.call(this,o,n),!n)return(0,na.eachItem)(o,s=>ta.call(this,s)),this;uv.call(this,n);let r={...n,type:(0,Tr.getJSONTypes)(n.type),schemaType:(0,Tr.getJSONTypes)(n.schemaType)};return(0,na.eachItem)(o,r.type.length===0?s=>ta.call(this,s,r):s=>r.type.forEach(i=>ta.call(this,s,r,i))),this}getKeyword(t){let n=this.RULES.all[t];return typeof n=="object"?n.definition:!!n}removeKeyword(t){let{RULES:n}=this;delete n.keywords[t],delete n.all[t];for(let o of n.rules){let r=o.rules.findIndex(s=>s.keyword===t);r>=0&&o.rules.splice(r,1)}return this}addFormat(t,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[t]=n,this}errorsText(t=this.errors,{separator:n=", ",dataVar:o="data"}={}){return!t||t.length===0?"No errors":t.map(r=>`${o}${r.instancePath} ${r.message}`).reduce((r,s)=>r+n+s)}$dataMetaSchema(t,n){let o=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let r of n){let s=r.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in o){let c=o[a];if(typeof c!="object")continue;let{$data:l}=c.definition,d=i[a];l&&d&&(i[a]=Gd(d))}}return t}_removeAllSchemas(t,n){for(let o in t){let r=t[o];(!n||n.test(o))&&(typeof r=="string"?delete t[o]:r&&!r.meta&&(this._cache.delete(r.schema),delete t[o]))}}_addSchema(t,n,o,r=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;o=(0,ho.normalizeId)(i||o);let l=ho.getSchemaRefs.call(this,t,o);return c=new go.SchemaEnv({schema:t,schemaId:a,meta:n,baseId:o,localRefs:l}),this._cache.set(c.schema,c),s&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=c),r&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):go.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let n=this.opts;this.opts=this._metaOpts;try{go.compileSchema.call(this,t)}finally{this.opts=n}}};yo.ValidationError=G_.default;yo.MissingRefError=Hd.default;pe.default=yo;function Ud(e,t,n,o="error"){for(let r in e){let s=r;s in t&&this.logger[o](`${n}: option ${r}. ${e[s]}`)}}function zd(e){return e=(0,ho.normalizeId)(e),this.schemas[e]||this.refs[e]}function tv(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function nv(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ov(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}function rv(){let e={...this.opts};for(let t of X_)delete e[t];return e}var sv={log(){},warn(){},error(){}};function iv(e){if(e===!1)return sv;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var av=/^[a-z_$][a-z0-9_$:-]*$/i;function cv(e,t){let{RULES:n}=this;if((0,na.eachItem)(e,o=>{if(n.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!av.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ta(e,t,n){var o;let r=t?.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=r?s.post:s.rules.find(({type:c})=>c===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Tr.getJSONTypes)(t.type),schemaType:(0,Tr.getJSONTypes)(t.schemaType)}};t.before?lv.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(o=t.implements)===null||o===void 0||o.forEach(c=>this.addKeyword(c))}function lv(e,t,n){let o=e.rules.findIndex(r=>r.keyword===n);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function uv(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Gd(t)),e.validateSchema=this.compile(t,!0))}var dv={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Gd(e){return{anyOf:[e,dv]}}});var Kd=w(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});var fv={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};oa.default=fv});var wr=w(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.callRef=Kt.getValidate=void 0;var pv=fo(),Jd=ze(),Pe=F(),wn=Ue(),Xd=po(),kr=q(),mv={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:n,it:o}=e,{baseId:r,schemaEnv:s,validateName:i,opts:a,self:c}=o,{root:l}=s;if((n==="#"||n==="#/")&&r===l.baseId)return p();let d=Xd.resolveRef.call(c,l,r,n);if(d===void 0)throw new pv.default(o.opts.uriResolver,r,n);if(d instanceof Xd.SchemaEnv)return y(d);return v(d);function p(){if(s===l)return Cr(e,i,s,s.$async);let h=t.scopeValue("root",{ref:l});return Cr(e,(0,Pe._)`${h}.validate`,l,l.$async)}function y(h){let _=Yd(e,h);Cr(e,_,h,h.$async)}function v(h){let _=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Pe.stringify)(h)}:{ref:h}),k=t.name("valid"),C=e.subschema({schema:h,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:_,errSchemaPath:n},k);e.mergeEvaluated(C),e.ok(k)}}};function Yd(e,t){let{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Kt.getValidate=Yd;function Cr(e,t,n,o){let{gen:r,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?wn.default.this:Pe.nil;o?d():p();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=r.let("valid");r.try(()=>{r.code((0,Pe._)`await ${(0,Jd.callValidateCode)(e,t,l)}`),v(t),i||r.assign(h,!0)},_=>{r.if((0,Pe._)`!(${_} instanceof ${s.ValidationError})`,()=>r.throw(_)),y(_),i||r.assign(h,!1)}),e.ok(h)}function p(){e.result((0,Jd.callValidateCode)(e,t,l),()=>v(t),()=>y(t))}function y(h){let _=(0,Pe._)`${h}.errors`;r.assign(wn.default.vErrors,(0,Pe._)`${wn.default.vErrors} === null ? ${_} : ${wn.default.vErrors}.concat(${_})`),r.assign(wn.default.errors,(0,Pe._)`${wn.default.vErrors}.length`)}function v(h){var _;if(!s.opts.unevaluated)return;let k=(_=n?.validate)===null||_===void 0?void 0:_.evaluated;if(s.props!==!0)if(k&&!k.dynamicProps)k.props!==void 0&&(s.props=kr.mergeEvaluated.props(r,k.props,s.props));else{let C=r.var("props",(0,Pe._)`${h}.evaluated.props`);s.props=kr.mergeEvaluated.props(r,C,s.props,Pe.Name)}if(s.items!==!0)if(k&&!k.dynamicItems)k.items!==void 0&&(s.items=kr.mergeEvaluated.items(r,k.items,s.items));else{let C=r.var("items",(0,Pe._)`${h}.evaluated.items`);s.items=kr.mergeEvaluated.items(r,C,s.items,Pe.Name)}}}Kt.callRef=Cr;Kt.default=mv});var Zd=w(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var gv=Kd(),hv=wr(),yv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gv.default,hv.default];ra.default=yv});var Qd=w(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});var Rr=F(),xt=Rr.operators,xr={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},bv={message:({keyword:e,schemaCode:t})=>(0,Rr.str)`must be ${xr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Rr._)`{comparison: ${xr[e].okStr}, limit: ${t}}`},_v={keyword:Object.keys(xr),type:"number",schemaType:"number",$data:!0,error:bv,code(e){let{keyword:t,data:n,schemaCode:o}=e;e.fail$data((0,Rr._)`${n} ${xr[t].fail} ${o} || isNaN(${n})`)}};sa.default=_v});var ef=w(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});var bo=F(),vv={message:({schemaCode:e})=>(0,bo.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,bo._)`{multipleOf: ${e}}`},Tv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:vv,code(e){let{gen:t,data:n,schemaCode:o,it:r}=e,s=r.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,bo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bo._)`${i} !== parseInt(${i})`;e.fail$data((0,bo._)`(${o} === 0 || (${i} = ${n}/${o}, ${a}))`)}};ia.default=Tv});var nf=w(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});function tf(e){let t=e.length,n=0,o=0,r;for(;o<t;)n++,r=e.charCodeAt(o++),r>=55296&&r<=56319&&o<t&&(r=e.charCodeAt(o),(r&64512)===56320&&o++);return n}aa.default=tf;tf.code='require("ajv/dist/runtime/ucs2length").default'});var of=w(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});var Jt=F(),kv=q(),Cv=nf(),wv={message({keyword:e,schemaCode:t}){let n=e==="maxLength"?"more":"fewer";return(0,Jt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,Jt._)`{limit: ${e}}`},Rv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wv,code(e){let{keyword:t,data:n,schemaCode:o,it:r}=e,s=t==="maxLength"?Jt.operators.GT:Jt.operators.LT,i=r.opts.unicode===!1?(0,Jt._)`${n}.length`:(0,Jt._)`${(0,kv.useFunc)(e.gen,Cv.default)}(${n})`;e.fail$data((0,Jt._)`${i} ${s} ${o}`)}};ca.default=Rv});var rf=w(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});var xv=ze(),Sv=q(),Rn=F(),Ev={message:({schemaCode:e})=>(0,Rn.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Rn._)`{pattern: ${e}}`},Av={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ev,code(e){let{gen:t,data:n,$data:o,schema:r,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(o){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Rn._)`new RegExp`:(0,Sv.useFunc)(t,c),d=t.let("valid");t.try(()=>t.assign(d,(0,Rn._)`${l}(${s}, ${a}).test(${n})`),()=>t.assign(d,!1)),e.fail$data((0,Rn._)`!${d}`)}else{let c=(0,xv.usePattern)(e,r);e.fail$data((0,Rn._)`!${c}.test(${n})`)}}};la.default=Av});var sf=w(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});var _o=F(),$v={message({keyword:e,schemaCode:t}){let n=e==="maxProperties"?"more":"fewer";return(0,_o.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,_o._)`{limit: ${e}}`},Pv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$v,code(e){let{keyword:t,data:n,schemaCode:o}=e,r=t==="maxProperties"?_o.operators.GT:_o.operators.LT;e.fail$data((0,_o._)`Object.keys(${n}).length ${r} ${o}`)}};ua.default=Pv});var af=w(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});var vo=ze(),To=F(),Mv=q(),Iv={message:({params:{missingProperty:e}})=>(0,To.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,To._)`{missingProperty: ${e}}`},Ov={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Iv,code(e){let{gen:t,schema:n,schemaCode:o,data:r,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?l():d(),a.strictRequired){let v=e.parentSchema.properties,{definedProperties:h}=e.it;for(let _ of n)if(v?.[_]===void 0&&!h.has(_)){let k=i.schemaEnv.baseId+i.errSchemaPath,C=`required property "${_}" is not defined at "${k}" (strictRequired)`;(0,Mv.checkStrictMode)(i,C,i.opts.strictRequired)}}function l(){if(c||s)e.block$data(To.nil,p);else for(let v of n)(0,vo.checkReportMissingProp)(e,v)}function d(){let v=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>y(v,h)),e.ok(h)}else t.if((0,vo.checkMissingProp)(e,n,v)),(0,vo.reportMissingProp)(e,v),t.else()}function p(){t.forOf("prop",o,v=>{e.setParams({missingProperty:v}),t.if((0,vo.noPropertyInData)(t,r,v,a.ownProperties),()=>e.error())})}function y(v,h){e.setParams({missingProperty:v}),t.forOf(v,o,()=>{t.assign(h,(0,vo.propertyInData)(t,r,v,a.ownProperties)),t.if((0,To.not)(h),()=>{e.error(),t.break()})},To.nil)}}};da.default=Ov});var cf=w(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});var ko=F(),Nv={message({keyword:e,schemaCode:t}){let n=e==="maxItems"?"more":"fewer";return(0,ko.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,ko._)`{limit: ${e}}`},Fv={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Nv,code(e){let{keyword:t,data:n,schemaCode:o}=e,r=t==="maxItems"?ko.operators.GT:ko.operators.LT;e.fail$data((0,ko._)`${n}.length ${r} ${o}`)}};fa.default=Fv});var Sr=w(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});var lf=Fi();lf.code='require("ajv/dist/runtime/equal").default';pa.default=lf});var uf=w(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});var ma=io(),me=F(),Lv=q(),jv=Sr(),Dv={message:({params:{i:e,j:t}})=>(0,me.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,me._)`{i: ${e}, j: ${t}}`},Bv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Dv,code(e){let{gen:t,data:n,$data:o,schema:r,parentSchema:s,schemaCode:i,it:a}=e;if(!o&&!r)return;let c=t.let("valid"),l=s.items?(0,ma.getSchemaTypes)(s.items):[];e.block$data(c,d,(0,me._)`${i} === false`),e.ok(c);function d(){let h=t.let("i",(0,me._)`${n}.length`),_=t.let("j");e.setParams({i:h,j:_}),t.assign(c,!0),t.if((0,me._)`${h} > 1`,()=>(p()?y:v)(h,_))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function y(h,_){let k=t.name("item"),C=(0,ma.checkDataTypes)(l,k,a.opts.strictNumbers,ma.DataType.Wrong),E=t.const("indices",(0,me._)`{}`);t.for((0,me._)`;${h}--;`,()=>{t.let(k,(0,me._)`${n}[${h}]`),t.if(C,(0,me._)`continue`),l.length>1&&t.if((0,me._)`typeof ${k} == "string"`,(0,me._)`${k} += "_"`),t.if((0,me._)`typeof ${E}[${k}] == "number"`,()=>{t.assign(_,(0,me._)`${E}[${k}]`),e.error(),t.assign(c,!1).break()}).code((0,me._)`${E}[${k}] = ${h}`)})}function v(h,_){let k=(0,Lv.useFunc)(t,jv.default),C=t.name("outer");t.label(C).for((0,me._)`;${h}--;`,()=>t.for((0,me._)`${_} = ${h}; ${_}--;`,()=>t.if((0,me._)`${k}(${n}[${h}], ${n}[${_}])`,()=>{e.error(),t.assign(c,!1).break(C)})))}}};ga.default=Bv});var df=w(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});var ha=F(),qv=q(),Uv=Sr(),zv={message:"must be equal to constant",params:({schemaCode:e})=>(0,ha._)`{allowedValue: ${e}}`},Hv={keyword:"const",$data:!0,error:zv,code(e){let{gen:t,data:n,$data:o,schemaCode:r,schema:s}=e;o||s&&typeof s=="object"?e.fail$data((0,ha._)`!${(0,qv.useFunc)(t,Uv.default)}(${n}, ${r})`):e.fail((0,ha._)`${s} !== ${n}`)}};ya.default=Hv});var ff=w(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});var Co=F(),Vv=q(),Gv=Sr(),Wv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Co._)`{allowedValues: ${e}}`},Kv={keyword:"enum",schemaType:"array",$data:!0,error:Wv,code(e){let{gen:t,data:n,$data:o,schema:r,schemaCode:s,it:i}=e;if(!o&&r.length===0)throw new Error("enum must have non-empty array");let a=r.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,Vv.useFunc)(t,Gv.default)),d;if(a||o)d=t.let("valid"),e.block$data(d,p);else{if(!Array.isArray(r))throw new Error("ajv implementation error");let v=t.const("vSchema",s);d=(0,Co.or)(...r.map((h,_)=>y(v,_)))}e.pass(d);function p(){t.assign(d,!1),t.forOf("v",s,v=>t.if((0,Co._)`${l()}(${n}, ${v})`,()=>t.assign(d,!0).break()))}function y(v,h){let _=r[h];return typeof _=="object"&&_!==null?(0,Co._)`${l()}(${n}, ${v}[${h}])`:(0,Co._)`${n} === ${_}`}}};ba.default=Kv});var pf=w(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});var Jv=Qd(),Xv=ef(),Yv=of(),Zv=rf(),Qv=sf(),eT=af(),tT=cf(),nT=uf(),oT=df(),rT=ff(),sT=[Jv.default,Xv.default,Yv.default,Zv.default,Qv.default,eT.default,tT.default,nT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oT.default,rT.default];_a.default=sT});var Ta=w(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateAdditionalItems=void 0;var Xt=F(),va=q(),iT={message:({params:{len:e}})=>(0,Xt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Xt._)`{limit: ${e}}`},aT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:iT,code(e){let{parentSchema:t,it:n}=e,{items:o}=t;if(!Array.isArray(o)){(0,va.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}mf(e,o)}};function mf(e,t){let{gen:n,schema:o,data:r,keyword:s,it:i}=e;i.items=!0;let a=n.const("len",(0,Xt._)`${r}.length`);if(o===!1)e.setParams({len:t.length}),e.pass((0,Xt._)`${a} <= ${t.length}`);else if(typeof o=="object"&&!(0,va.alwaysValidSchema)(i,o)){let l=n.var("valid",(0,Xt._)`${a} <= ${t.length}`);n.if((0,Xt.not)(l),()=>c(l)),e.ok(l)}function c(l){n.forRange("i",t.length,a,d=>{e.subschema({keyword:s,dataProp:d,dataPropType:va.Type.Num},l),i.allErrors||n.if((0,Xt.not)(l),()=>n.break())})}}wo.validateAdditionalItems=mf;wo.default=aT});var ka=w(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.validateTuple=void 0;var gf=F(),Er=q(),cT=ze(),lT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:n}=e;if(Array.isArray(t))return hf(e,"additionalItems",t);n.items=!0,!(0,Er.alwaysValidSchema)(n,t)&&e.ok((0,cT.validateArray)(e))}};function hf(e,t,n=e.schema){let{gen:o,parentSchema:r,data:s,keyword:i,it:a}=e;d(r),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Er.mergeEvaluated.items(o,n.length,a.items));let c=o.name("valid"),l=o.const("len",(0,gf._)`${s}.length`);n.forEach((p,y)=>{(0,Er.alwaysValidSchema)(a,p)||(o.if((0,gf._)`${l} > ${y}`,()=>e.subschema({keyword:i,schemaProp:y,dataProp:y},c)),e.ok(c))});function d(p){let{opts:y,errSchemaPath:v}=a,h=n.length,_=h===p.minItems&&(h===p.maxItems||p[t]===!1);if(y.strictTuples&&!_){let k=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${v}"`;(0,Er.checkStrictMode)(a,k,y.strictTuples)}}}Ro.validateTuple=hf;Ro.default=lT});var yf=w(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var uT=ka(),dT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,uT.validateTuple)(e,"items")};Ca.default=dT});var _f=w(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});var bf=F(),fT=q(),pT=ze(),mT=Ta(),gT={message:({params:{len:e}})=>(0,bf.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,bf._)`{limit: ${e}}`},hT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gT,code(e){let{schema:t,parentSchema:n,it:o}=e,{prefixItems:r}=n;o.items=!0,!(0,fT.alwaysValidSchema)(o,t)&&(r?(0,mT.validateAdditionalItems)(e,r):e.ok((0,pT.validateArray)(e)))}};wa.default=hT});var vf=w(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});var Ve=F(),Ar=q(),yT={message:({params:{min:e,max:t}})=>t===void 0?(0,Ve.str)`must contain at least ${e} valid item(s)`:(0,Ve.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ve._)`{minContains: ${e}}`:(0,Ve._)`{minContains: ${e}, maxContains: ${t}}`},bT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:yT,code(e){let{gen:t,schema:n,parentSchema:o,data:r,it:s}=e,i,a,{minContains:c,maxContains:l}=o;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let d=t.const("len",(0,Ve._)`${r}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ar.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ar.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ar.alwaysValidSchema)(s,n)){let _=(0,Ve._)`${d} >= ${i}`;a!==void 0&&(_=(0,Ve._)`${_} && ${d} <= ${a}`),e.pass(_);return}s.items=!0;let p=t.name("valid");a===void 0&&i===1?v(p,()=>t.if(p,()=>t.break())):i===0?(t.let(p,!0),a!==void 0&&t.if((0,Ve._)`${r}.length > 0`,y)):(t.let(p,!1),y()),e.result(p,()=>e.reset());function y(){let _=t.name("_valid"),k=t.let("count",0);v(_,()=>t.if(_,()=>h(k)))}function v(_,k){t.forRange("i",0,d,C=>{e.subschema({keyword:"contains",dataProp:C,dataPropType:Ar.Type.Num,compositeRule:!0},_),k()})}function h(_){t.code((0,Ve._)`${_}++`),a===void 0?t.if((0,Ve._)`${_} >= ${i}`,()=>t.assign(p,!0).break()):(t.if((0,Ve._)`${_} > ${a}`,()=>t.assign(p,!1).break()),i===1?t.assign(p,!0):t.if((0,Ve._)`${_} >= ${i}`,()=>t.assign(p,!0)))}}};Ra.default=bT});var $r=w(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateSchemaDeps=it.validatePropertyDeps=it.error=void 0;var xa=F(),_T=q(),xo=ze();it.error={message:({params:{property:e,depsCount:t,deps:n}})=>{let o=t===1?"property":"properties";return(0,xa.str)`must have ${o} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:o}})=>(0,xa._)`{property: ${e},
|
|
5
|
+
|| ${i} === "boolean" || ${r} === null`).assign(a,(0,L._)`[${r}]`)}}}function 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},
|
|
6
6
|
missingProperty: ${o},
|
|
7
7
|
depsCount: ${t},
|
|
8
|
-
deps: ${n}}`};var vT={keyword:"dependencies",type:"object",schemaType:"object",error:it.error,code(e){let[t,n]=TT(e);Tf(e,t),kf(e,n)}};function TT({schema:e}){let t={},n={};for(let o in e){if(o==="__proto__")continue;let r=Array.isArray(e[o])?t:n;r[o]=e[o]}return[t,n]}function Tf(e,t=e.schema){let{gen:n,data:o,it:r}=e;if(Object.keys(t).length===0)return;let s=n.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,xo.propertyInData)(n,o,i,r.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),r.allErrors?n.if(c,()=>{for(let l of a)(0,xo.checkReportMissingProp)(e,l)}):(n.if((0,xa._)`${c} && (${(0,xo.checkMissingProp)(e,a,s)})`),(0,xo.reportMissingProp)(e,s),n.else())}}it.validatePropertyDeps=Tf;function kf(e,t=e.schema){let{gen:n,data:o,keyword:r,it:s}=e,i=n.name("valid");for(let a in t)(0,_T.alwaysValidSchema)(s,t[a])||(n.if((0,xo.propertyInData)(n,o,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:r,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),e.ok(i))}it.validateSchemaDeps=kf;it.default=vT});var wf=w(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});var Cf=F(),kT=q(),CT={message:"property name must be valid",params:({params:e})=>(0,Cf._)`{propertyName: ${e.propertyName}}`},wT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:CT,code(e){let{gen:t,schema:n,data:o,it:r}=e;if((0,kT.alwaysValidSchema)(r,n))return;let s=t.name("valid");t.forIn("key",o,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Cf.not)(s),()=>{e.error(!0),r.allErrors||t.break()})}),e.ok(s)}};Sa.default=wT});var Aa=w(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var Pr=ze(),et=F(),RT=Ue(),Mr=q(),xT={message:"must NOT have additional properties",params:({params:e})=>(0,et._)`{additionalProperty: ${e.additionalProperty}}`},ST={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:xT,code(e){let{gen:t,schema:n,parentSchema:o,data:r,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Mr.alwaysValidSchema)(i,n))return;let l=(0,Pr.allSchemaProperties)(o.properties),d=(0,Pr.allSchemaProperties)(o.patternProperties);p(),e.ok((0,et._)`${s} === ${RT.default.errors}`);function p(){t.forIn("key",r,k=>{!l.length&&!d.length?h(k):t.if(y(k),()=>h(k))})}function y(k){let C;if(l.length>8){let E=(0,Mr.schemaRefOrVal)(i,o.properties,"properties");C=(0,Pr.isOwnProperty)(t,E,k)}else l.length?C=(0,et.or)(...l.map(E=>(0,et._)`${k} === ${E}`)):C=et.nil;return d.length&&(C=(0,et.or)(C,...d.map(E=>(0,et._)`${(0,Pr.usePattern)(e,E)}.test(${k})`))),(0,et.not)(C)}function v(k){t.code((0,et._)`delete ${r}[${k}]`)}function h(k){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){v(k);return}if(n===!1){e.setParams({additionalProperty:k}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Mr.alwaysValidSchema)(i,n)){let C=t.name("valid");c.removeAdditional==="failing"?(_(k,C,!1),t.if((0,et.not)(C),()=>{e.reset(),v(k)})):(_(k,C),a||t.if((0,et.not)(C),()=>t.break()))}}function _(k,C,E){let O={keyword:"additionalProperties",dataProp:k,dataPropType:Mr.Type.Str};E===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(O,C)}}};Ea.default=ST});var Sf=w(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});var ET=uo(),Rf=ze(),$a=q(),xf=Aa(),AT={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,parentSchema:o,data:r,it:s}=e;s.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&xf.default.code(new ET.KeywordCxt(s,xf.default,"additionalProperties"));let i=(0,Rf.allSchemaProperties)(n);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=$a.mergeEvaluated.props(t,(0,$a.toHash)(i),s.props));let a=i.filter(p=>!(0,$a.alwaysValidSchema)(s,n[p]));if(a.length===0)return;let c=t.name("valid");for(let p of a)l(p)?d(p):(t.if((0,Rf.propertyInData)(t,r,p,s.opts.ownProperties)),d(p),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&n[p].default!==void 0}function d(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Pa.default=AT});var Pf=w(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});var Ef=ze(),Ir=F(),Af=q(),$f=q(),$T={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,data:o,parentSchema:r,it:s}=e,{opts:i}=s,a=(0,Ef.allSchemaProperties)(n),c=a.filter(_=>(0,Af.alwaysValidSchema)(s,n[_]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&r.properties,d=t.name("valid");s.props!==!0&&!(s.props instanceof Ir.Name)&&(s.props=(0,$f.evaluatedPropsToName)(t,s.props));let{props:p}=s;y();function y(){for(let _ of a)l&&v(_),s.allErrors?h(_):(t.var(d,!0),h(_),t.if(d))}function v(_){for(let k in l)new RegExp(_).test(k)&&(0,Af.checkStrictMode)(s,`property ${k} matches pattern ${_} (use allowMatchingProperties)`)}function h(_){t.forIn("key",o,k=>{t.if((0,Ir._)`${(0,Ef.usePattern)(e,_)}.test(${k})`,()=>{let C=c.includes(_);C||e.subschema({keyword:"patternProperties",schemaProp:_,dataProp:k,dataPropType:$f.Type.Str},d),s.opts.unevaluated&&p!==!0?t.assign((0,Ir._)`${p}[${k}]`,!0):!C&&!s.allErrors&&t.if((0,Ir.not)(d),()=>t.break())})})}}};Ma.default=$T});var Mf=w(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var PT=q(),MT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:o}=e;if((0,PT.alwaysValidSchema)(o,n)){e.fail();return}let r=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),e.failResult(r,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ia.default=MT});var If=w(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var IT=ze(),OT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:IT.validateUnion,error:{message:"must match a schema in anyOf"}};Oa.default=OT});var Of=w(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});var Or=F(),NT=q(),FT={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Or._)`{passingSchemas: ${e.passing}}`},LT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:FT,code(e){let{gen:t,schema:n,parentSchema:o,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&o.discriminator)return;let s=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(i,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((d,p)=>{let y;(0,NT.alwaysValidSchema)(r,d)?t.var(c,!0):y=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,Or._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Or._)`[${a}, ${p}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,p),y&&e.mergeEvaluated(y,Or.Name)})})}}};Na.default=LT});var Nf=w(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var jT=q(),DT={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:n,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");let r=t.name("valid");n.forEach((s,i)=>{if((0,jT.alwaysValidSchema)(o,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},r);e.ok(r),e.mergeEvaluated(a)})}};Fa.default=DT});var jf=w(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});var Nr=F(),Lf=q(),BT={message:({params:e})=>(0,Nr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Nr._)`{failingKeyword: ${e.ifClause}}`},qT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:BT,code(e){let{gen:t,parentSchema:n,it:o}=e;n.then===void 0&&n.else===void 0&&(0,Lf.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let r=Ff(o,"then"),s=Ff(o,"else");if(!r&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),r&&s){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else r?t.if(a,l("then")):t.if((0,Nr.not)(a),l("else"));e.pass(i,()=>e.error(!0));function c(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,p){return()=>{let y=e.subschema({keyword:d},a);t.assign(i,a),e.mergeValidEvaluated(y,i),p?t.assign(p,(0,Nr._)`${d}`):e.setParams({ifClause:d})}}}};function Ff(e,t){let n=e.schema[t];return n!==void 0&&!(0,Lf.alwaysValidSchema)(e,n)}La.default=qT});var Df=w(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var UT=q(),zT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,UT.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};ja.default=zT});var Bf=w(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var HT=Ta(),VT=yf(),GT=ka(),WT=_f(),KT=vf(),JT=$r(),XT=wf(),YT=Aa(),ZT=Sf(),QT=Pf(),ek=Mf(),tk=If(),nk=Of(),ok=Nf(),rk=jf(),sk=Df();function ik(e=!1){let t=[ek.default,tk.default,nk.default,ok.default,rk.default,sk.default,XT.default,YT.default,JT.default,ZT.default,QT.default];return e?t.push(VT.default,WT.default):t.push(HT.default,GT.default),t.push(KT.default),t}Da.default=ik});var qa=w(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.dynamicAnchor=void 0;var Ba=F(),ak=Ue(),qf=po(),ck=wr(),lk={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Uf(e,e.schema)};function Uf(e,t){let{gen:n,it:o}=e;o.schemaEnv.root.dynamicAnchors[t]=!0;let r=(0,Ba._)`${ak.default.dynamicAnchors}${(0,Ba.getProperty)(t)}`,s=o.errSchemaPath==="#"?o.validateName:uk(e);n.if((0,Ba._)`!${r}`,()=>n.assign(r,s))}So.dynamicAnchor=Uf;function uk(e){let{schemaEnv:t,schema:n,self:o}=e.it,{root:r,baseId:s,localRefs:i,meta:a}=t.root,{schemaId:c}=o.opts,l=new qf.SchemaEnv({schema:n,schemaId:c,root:r,baseId:s,localRefs:i,meta:a});return qf.compileSchema.call(o,l),(0,ck.getValidate)(e,l)}So.default=lk});var Ua=w(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.dynamicRef=void 0;var zf=F(),dk=Ue(),Hf=wr(),fk={keyword:"$dynamicRef",schemaType:"string",code:e=>Vf(e,e.schema)};function Vf(e,t){let{gen:n,keyword:o,it:r}=e;if(t[0]!=="#")throw new Error(`"${o}" only supports hash fragment reference`);let s=t.slice(1);if(r.allErrors)i();else{let c=n.let("valid",!1);i(c),e.ok(c)}function i(c){if(r.schemaEnv.root.dynamicAnchors[s]){let l=n.let("_v",(0,zf._)`${dk.default.dynamicAnchors}${(0,zf.getProperty)(s)}`);n.if(l,a(l,c),a(r.validateName,c))}else a(r.validateName,c)()}function a(c,l){return l?()=>n.block(()=>{(0,Hf.callRef)(e,c),n.let(l,!0)}):()=>(0,Hf.callRef)(e,c)}}Eo.dynamicRef=Vf;Eo.default=fk});var Gf=w(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var pk=qa(),mk=q(),gk={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,pk.dynamicAnchor)(e,""):(0,mk.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};za.default=gk});var Wf=w(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var hk=Ua(),yk={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,hk.dynamicRef)(e,e.schema)};Ha.default=yk});var Kf=w(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var bk=qa(),_k=Ua(),vk=Gf(),Tk=Wf(),kk=[bk.default,_k.default,vk.default,Tk.default];Va.default=kk});var Xf=w(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Jf=$r(),Ck={keyword:"dependentRequired",type:"object",schemaType:"object",error:Jf.error,code:e=>(0,Jf.validatePropertyDeps)(e)};Ga.default=Ck});var Yf=w(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var wk=$r(),Rk={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,wk.validateSchemaDeps)(e)};Wa.default=Rk});var Zf=w(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var xk=q(),Sk={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){t.contains===void 0&&(0,xk.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};Ka.default=Sk});var Qf=w(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Ek=Xf(),Ak=Yf(),$k=Zf(),Pk=[Ek.default,Ak.default,$k.default];Ja.default=Pk});var tp=w(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var St=F(),ep=q(),Mk=Ue(),Ik={message:"must NOT have unevaluated properties",params:({params:e})=>(0,St._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},Ok={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Ik,code(e){let{gen:t,schema:n,data:o,errsCount:r,it:s}=e;if(!r)throw new Error("ajv implementation error");let{allErrors:i,props:a}=s;a instanceof St.Name?t.if((0,St._)`${a} !== true`,()=>t.forIn("key",o,p=>t.if(l(a,p),()=>c(p)))):a!==!0&&t.forIn("key",o,p=>a===void 0?c(p):t.if(d(a,p),()=>c(p))),s.props=!0,e.ok((0,St._)`${r} === ${Mk.default.errors}`);function c(p){if(n===!1){e.setParams({unevaluatedProperty:p}),e.error(),i||t.break();return}if(!(0,ep.alwaysValidSchema)(s,n)){let y=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:ep.Type.Str},y),i||t.if((0,St.not)(y),()=>t.break())}}function l(p,y){return(0,St._)`!${p} || !${p}[${y}]`}function d(p,y){let v=[];for(let h in p)p[h]===!0&&v.push((0,St._)`${y} !== ${h}`);return(0,St.and)(...v)}}};Xa.default=Ok});var op=w(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Yt=F(),np=q(),Nk={message:({params:{len:e}})=>(0,Yt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Yt._)`{limit: ${e}}`},Fk={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Nk,code(e){let{gen:t,schema:n,data:o,it:r}=e,s=r.items||0;if(s===!0)return;let i=t.const("len",(0,Yt._)`${o}.length`);if(n===!1)e.setParams({len:s}),e.fail((0,Yt._)`${i} > ${s}`);else if(typeof n=="object"&&!(0,np.alwaysValidSchema)(r,n)){let c=t.var("valid",(0,Yt._)`${i} <= ${s}`);t.if((0,Yt.not)(c),()=>a(c,s)),e.ok(c)}r.items=!0;function a(c,l){t.forRange("i",l,i,d=>{e.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:np.Type.Num},c),r.allErrors||t.if((0,Yt.not)(c),()=>t.break())})}}};Ya.default=Fk});var rp=w(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var Lk=tp(),jk=op(),Dk=[Lk.default,jk.default];Za.default=Dk});var sp=w(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var se=F(),Bk={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},qk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Bk,code(e,t){let{gen:n,data:o,$data:r,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:d,self:p}=a;if(!c.validateFormats)return;r?y():v();function y(){let h=n.scopeValue("formats",{ref:p.formats,code:c.code.formats}),_=n.const("fDef",(0,se._)`${h}[${i}]`),k=n.let("fType"),C=n.let("format");n.if((0,se._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>n.assign(k,(0,se._)`${_}.type || "string"`).assign(C,(0,se._)`${_}.validate`),()=>n.assign(k,(0,se._)`"string"`).assign(C,_)),e.fail$data((0,se.or)(E(),O()));function E(){return c.strictSchema===!1?se.nil:(0,se._)`${i} && !${C}`}function O(){let U=d.$async?(0,se._)`(${_}.async ? await ${C}(${o}) : ${C}(${o}))`:(0,se._)`${C}(${o})`,M=(0,se._)`(typeof ${C} == "function" ? ${U} : ${C}.test(${o}))`;return(0,se._)`${C} && ${C} !== true && ${k} === ${t} && !${M}`}}function v(){let h=p.formats[s];if(!h){E();return}if(h===!0)return;let[_,k,C]=O(h);_===t&&e.pass(U());function E(){if(c.strictSchema===!1){p.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function O(M){let Q=M instanceof RegExp?(0,se.regexpCode)(M):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(s)}`:void 0,Ie=n.scopeValue("formats",{key:s,ref:M,code:Q});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,se._)`${Ie}.validate`]:["string",M,Ie]}function U(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,se._)`await ${C}(${o})`}return typeof k=="function"?(0,se._)`${C}(${o})`:(0,se._)`${C}.test(${o})`}}}};Qa.default=qk});var ip=w(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Uk=sp(),zk=[Uk.default];ec.default=zk});var ap=w(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var lp=w(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Hk=Zd(),Vk=pf(),Gk=Bf(),Wk=Kf(),Kk=Qf(),Jk=rp(),Xk=ip(),cp=ap(),Yk=[Wk.default,Hk.default,Vk.default,(0,Gk.default)(!0),Xk.default,cp.metadataVocabulary,cp.contentVocabulary,Kk.default,Jk.default];tc.default=Yk});var dp=w(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.DiscrError=void 0;var up;(function(e){e.Tag="tag",e.Mapping="mapping"})(up||(Fr.DiscrError=up={}))});var pp=w(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Sn=F(),nc=dp(),fp=po(),Zk=fo(),Qk=q(),eC={message:({params:{discrError:e,tagName:t}})=>e===nc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Sn._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},tC={keyword:"discriminator",type:"object",schemaType:"object",error:eC,code(e){let{gen:t,data:n,schema:o,parentSchema:r,it:s}=e,{oneOf:i}=r;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Sn._)`${n}${(0,Sn.getProperty)(a)}`);t.if((0,Sn._)`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:nc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function d(){let v=y();t.if(!1);for(let h in v)t.elseIf((0,Sn._)`${l} === ${h}`),t.assign(c,p(v[h]));t.else(),e.error(!1,{discrError:nc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function p(v){let h=t.name("valid"),_=e.subschema({keyword:"oneOf",schemaProp:v},h);return e.mergeEvaluated(_,Sn.Name),h}function y(){var v;let h={},_=C(r),k=!0;for(let U=0;U<i.length;U++){let M=i[U];if(M?.$ref&&!(0,Qk.schemaHasRulesButRef)(M,s.self.RULES)){let Ie=M.$ref;if(M=fp.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ie),M instanceof fp.SchemaEnv&&(M=M.schema),M===void 0)throw new Zk.default(s.opts.uriResolver,s.baseId,Ie)}let Q=(v=M?.properties)===null||v===void 0?void 0:v[a];if(typeof Q!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);k=k&&(_||C(M)),E(Q,U)}if(!k)throw new Error(`discriminator: "${a}" must be required`);return h;function C({required:U}){return Array.isArray(U)&&U.includes(a)}function E(U,M){if(U.const)O(U.const,M);else if(U.enum)for(let Q of U.enum)O(Q,M);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function O(U,M){if(typeof U!="string"||U in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[U]=M}}}};oc.default=tC});var mp=w((rA,nC)=>{nC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var gp=w((sA,oC)=>{oC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hp=w((iA,rC)=>{rC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var yp=w((aA,sC)=>{sC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var bp=w((cA,iC)=>{iC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var _p=w((lA,aC)=>{aC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var vp=w((uA,cC)=>{cC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var Tp=w((dA,lC)=>{lC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var kp=w(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var uC=mp(),dC=gp(),fC=hp(),pC=yp(),mC=bp(),gC=_p(),hC=vp(),yC=Tp(),bC=["/properties"];function _C(e){return[uC,dC,fC,pC,mC,t(this,gC),hC,t(this,yC)].forEach(n=>this.addMetaSchema(n,void 0,!1)),this;function t(n,o){return e?n.$dataMetaSchema(o,bC):o}}rc.default=_C});var Cp=w((ne,ic)=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.MissingRefError=ne.ValidationError=ne.CodeGen=ne.Name=ne.nil=ne.stringify=ne.str=ne._=ne.KeywordCxt=ne.Ajv2020=void 0;var vC=Wd(),TC=lp(),kC=pp(),CC=kp(),sc="https://json-schema.org/draft/2020-12/schema",En=class extends vC.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),TC.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(kC.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;n&&(CC.default.call(this,t),this.refs["http://json-schema.org/schema"]=sc)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(sc)?sc:void 0)}};ne.Ajv2020=En;ic.exports=ne=En;ic.exports.Ajv2020=En;Object.defineProperty(ne,"__esModule",{value:!0});ne.default=En;var wC=uo();Object.defineProperty(ne,"KeywordCxt",{enumerable:!0,get:function(){return wC.KeywordCxt}});var An=F();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return An._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return An.str}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return An.stringify}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return An.nil}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return An.Name}});Object.defineProperty(ne,"CodeGen",{enumerable:!0,get:function(){return An.CodeGen}});var RC=hr();Object.defineProperty(ne,"ValidationError",{enumerable:!0,get:function(){return RC.default}});var xC=fo();Object.defineProperty(ne,"MissingRefError",{enumerable:!0,get:function(){return xC.default}})});function Fs(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function we(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var Og=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Lt={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ng=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Fg=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Lg=512,jg=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Dg=new Set([500,502,503,504,521,522,523,524,529]),Bg=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],qg=["upgrade your plan","upgrade plan","current plan","subscription"],Ug=["daily","weekly","monthly"],zg=["try again","retry","temporary","cooldown"],Hg=["usage limit","rate limit","organization usage"],Vg=["organization","workspace"],Gg=["billing period","exceeded","reached","exhausted"],Wg=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Kg=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function jt(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Jg(e){return jt(e,Lt.format)}function Bl(e){return jt(e,Lt.rateLimit)}function Xg(e){return jt(e,Lt.timeout)}function Yg(e){return Og.test(e)}function Ls(e){let t=e.toLowerCase();return t?e.length>Lg?Fg.test(t):jt(t,Lt.billing)?!0:Ng.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ql(e){return jt(e,Lt.authPermanent)}function Zg(e){return jt(e,Lt.auth)}function Ul(e){return jt(e,Lt.overloaded)}function Ft(e,t){return t.some(n=>e.includes(n))}function Qg(e){return Ft(e,Bg)||Ft(e,qg)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function eh(e){let t=Ft(e,Ug),n=e.includes("spend limit")||e.includes("spending limit"),o=Ft(e,Vg);return Ft(e,zg)&&Ft(e,Hg)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||Ft(e,Gg))}function th(e){return e.trim().toLowerCase().replace(Kg,"").trim()}function zl(e){let t=th(e);return!t||Qg(t)?"billing":Bl(t)||eh(t)?"rate_limit":"billing"}function nh(e){return Wg.test(e)?zl(e):null}function Hl(e){let t=e.match(jg);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function oh(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function rh(e){let t=e.trim();if(!t)return!1;let n=Hl(t);return n?Dg.has(n.code):!1}function Vl(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?zl(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ql(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ul(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ls(t)?"billing":"format":null}function sh(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function ih(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Gl(e){if(ih(e))return"session_expired";if(sh(e))return"model_not_found";let t=nh(e);return t||(Yg(e)?Ls(e)?"billing":"rate_limit":Bl(e)?"rate_limit":Ul(e)?"overloaded":rh(e)?Hl(e.trim())?.code===529?"overloaded":"timeout":oh(e)?"timeout":Jg(e)?"format":Ls(e)?"billing":Xg(e)?"timeout":ql(e)?"auth_permanent":Zg(e)?"auth":null)}var ah=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Xo(e){return ah.has(e)}var ch={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function dn(e,t){let n=Vl(e,t)??(t?Gl(t):null);return n?ch[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Wl(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var lh=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),Wn=class{constructor(t=20,n=Wl){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let c of t){let l=c.tool_calls;if(Array.isArray(l))for(let d of l)d?.id&&d.function?.name&&o.set(d.id,d.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((c,l)=>{if(l>=r||c.role!=="tool"||typeof c.content!="string")return c;let d=c.name??o.get(c.tool_call_id??"");if(!d||!lh.has(d)||c.content.length<=200)return c;let p=this.estimateTokens(c);return i+=p,s++,{...c,content:`[result cleared \u2014 ${c.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function js(e,t,n=Wl){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let c=a.tool_call_id??"";if(c&&t.has(c)){o+=n(a),r++,t.delete(c);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function Ds(){return{stages:[]}}function Bs(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Kl(e,t),i=uh(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Kl(e,t),{messages:s,stagedCount:i.length}}function qs(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:Jl(e,t),committed:n}}function Kl(e,t){return t.stages.filter(o=>o.committed).length===0?e:Jl(e,t)}function Jl(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),c={role:"system",content:r.summary};o.splice(s,a-s,c)}return o}function uh(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<o;c++){let l=e[c];if(l.role==="tool"||l.role==="assistant"&&typeof l.content=="string"&&l.content==="")i<0&&(i=c),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let c=`${i}-${i+a}`;s.has(c)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function dh(e){return[...new Set(e.map(Yo).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Xl(e){let t=dh(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function fh(e){let t=[...new Set(e.map(Yo).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Xl(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function Yo(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function ph(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function mh(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function gh(e){if(!e.eligibility?.length)return[...e.tools];let t=mh(e.eligibility);return e.tools.filter(n=>{let o=Yo(n);if(!o)return!1;let r=t.get(o);return!r||ph(r.status)})}function hh(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Us(e){let t=hh({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=gh({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Xl(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:fh(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(c=>Yo(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var yh=["stop","aborted","timeout","cancelled","interrupted","error"],bh=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Yl(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function _h(e,t){return{...e,content:[...Yl(e.content),...Yl(t.content)]}}function vh(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Th(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=vh(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function kh(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Ch(e){return new Set((e??yh).map(t=>t.trim().toLowerCase()))}function wh(e,t){return e?Ch(t).has(e.trim().toLowerCase()):!1}function zs(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(c=>{if(c.role==="assistant"&&Array.isArray(c.tool_calls)){let l=c.tool_calls.filter(d=>kh(d));return{...c,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...c}}),n=new Set;for(let c of t)if(!(c.role!=="assistant"||!Array.isArray(c.tool_calls)))for(let l of c.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(c=>c.role!=="tool"?!0:!!(c.tool_call_id&&n.has(c.tool_call_id))),r=new Set;for(let c of o)c.role==="tool"&&typeof c.tool_call_id=="string"&&c.tool_call_id&&r.add(c.tool_call_id);let s=[];for(let c of o){if(c.role==="assistant"&&Array.isArray(c.tool_calls)&&c.tool_calls.length>0){let l=c.tool_calls.filter(d=>typeof d.id=="string"&&r.has(d.id));if(l.length===0){let{tool_calls:d,...p}=c;p.content!=null&&p.content!==""&&s.push(p);continue}if(l.length<c.tool_calls.length){s.push({...c,tool_calls:l});continue}}s.push(c)}let i=Th(s),a=[];for(let c of i){let l=a.length>0?a[a.length-1]:void 0;if(c.role==="user"&&l?.role==="user"){a[a.length-1]=_h(l,c);continue}a.push(c)}return a}function Hs(e,t){return wh(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of bh)delete o[r];return o}):[...e]}function Vs(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function Gs(e,t){let n=zs(e),o=Hs(n,t);return Vs(o,t)}function Rh(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function xh(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Sh(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ws(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Zo(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Qo(e){let t=[],n=zs(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=Hs(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Vs(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Sh({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Rh(r),completedToolCallIds:xh(r)}),recoveryActions:t}}var Eh=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ks(e){return e?Eh.has(e):!0}function Js(e){return e===429||e===529}function er(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Q0={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function tr(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Kn=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var Zl=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ql=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),eu=3,fn=2,nr=2,tu=128e3,nu=13e3,ou=16384,ru=65536,su=3;var Xs=500,iu=3;var au=3e4,cu=3,Dt=2;var tx=50*1024,nx=500*1024,ox=500*1024*1024,rx=50*1024*1024;function Ys(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Zs(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Qs(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function ei(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function ti(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function ni(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function pn(e){return!e.attemptedThisTurn}import{createHash as Jm}from"node:crypto";import{existsSync as sn,readFileSync as os,statSync as kR}from"node:fs";function oi(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}var $h=new Set(["agent","ask_user","edit","exec","patch","read","search","task","tool_schema_load","write"]);function lu(e,t){return t?.owner==="agent"&&t.family==="builtin"?!0:$h.has(e)}function Se(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?e:e.slice(t+2)}function uu(e){let t=e.indexOf("__");if(!(t<=0||t+2>=e.length))return e.slice(0,t)}function ri(e,t){return Se(e)===t}var si="tool_schema_load";function du(e){return e?.type!=="tool_schema_load"||!Array.isArray(e.requestedToolNames)?[]:[...new Set(e.requestedToolNames.filter(t=>typeof t=="string"&&t.trim().length>0))]}function ae(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}var Ph=new Set(["skill_search","skill_load","skill_resource_read","project_instructions","capability_inventory","prompt_read","tool_schema_load"]);function or(e){return e.identity.family!=="skill"&&!Ph.has(e.identity.logicalName)}function fu(e){return e.some(t=>t.status==="succeeded"&&or(t))}function pu(e){if(e.blocked)return"policy_blocked";let t=typeof e.details?.error=="string"?e.details.error:"",n=`${t} ${e.error??""}`;return t==="semantic_quality_failed"?"semantic_quality_failed":/MCP_START_FAILED/iu.test(n)?"mcp_start_failed":/mcp_not_connected|mcp_unavailable/iu.test(n)?"mcp_unavailable":/\bTIMEOUT\b|timed out/iu.test(n)?"timeout":"tool_execution_failed"}function Jn(e,t,n=[]){let o=t.filter(c=>c.status==="succeeded").map(c=>c.callId),r=new Set(n),s=e?t.filter(c=>c.status==="succeeded"&&or(c)&&(r.size===0||r.has(c.identity.logicalName))).map(c=>c.callId):o,i=t.filter(c=>c.status==="failed"||c.status==="running").map(c=>c.callId),a=t.filter(c=>c.status==="blocked").map(c=>c.callId);return e?s.length>0?{schemaVersion:1,requirement:"fresh-tool-evidence",disposition:"grounded",successfulCallIds:s,failedCallIds:i,blockedCallIds:a,reason:r.size>0?"at least one Skill-required execution call succeeded":"at least one required evidence call succeeded"}:{schemaVersion:1,requirement:"fresh-tool-evidence",disposition:t.length===0?"blocked-no-tool-evidence":"blocked-no-successful-evidence",successfulCallIds:s,failedCallIds:i,blockedCallIds:a,reason:t.length===0?"fresh evidence was required but no tool call completed":r.size>0&&o.length>0?`fresh evidence required a successful Skill execution call from: ${[...r].join(", ")}`:o.length>0?"fresh evidence was required but successful calls were instruction or capability discovery only":"fresh evidence was required but every tool call failed or was blocked"}:{schemaVersion:1,requirement:"not-required",disposition:"not-required",successfulCallIds:s,failedCallIds:i,blockedCallIds:a,reason:"the turn did not require fresh tool evidence"}}function mu(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function gu(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=[],r=Array.isArray(n.inlineImageUrls)?n.inlineImageUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[];for(let s of r)o.push(Mh(e,"image",s,n));return o}function Mh(e,t,n,o){return{type:"media_result",turnId:e,mediaType:t,url:n,model:typeof o.model=="string"?o.model:void 0,provider:typeof o.provider=="string"?o.provider:void 0,durationSeconds:typeof o.durationMs=="number"?o.durationMs/1e3:void 0,...typeof o.mimeType=="string"?{mimeType:o.mimeType}:{},...typeof o.filename=="string"?{filename:o.filename}:{},...typeof o.size=="number"?{size:o.size}:{},taskId:typeof o.taskId=="string"?o.taskId:void 0}}var Ih=[/<||DSML||tool_calls>/u,/<\|DSML\|>tool_calls/u,/<tool_calls?>[\s\S]*?<\/tool_calls?>/iu,/<function_calls?>[\s\S]*?<\/function_calls?>/iu],hu=["<\uFF5C\uFF5Cdsml\uFF5C\uFF5Ctool_calls>","<|dsml|>tool_calls","<tool_call","<function_call"];function yu(e){return Ih.some(t=>t.test(e))}function bu(){let e="",t=!1,n=!1;return{push(o){if(!o||n)return"";if(t)return o;e+=o;let r=e.trimStart().toLowerCase();if(hu.some(i=>r.startsWith(i)))return e="",n=!0,"";if(hu.some(i=>i.startsWith(r)))return"";t=!0;let s=e;return e="",s},flush(){if(n)return"";let o=e;return e="",t=!0,o}}}var Oh=new Set(["write","edit","patch"]);function _u(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(a=>a.id===n.callId);if(!r)return[];let s=[],i=Nh(r.function.arguments);if(!i)return s;if(Oh.has(n.toolName)){let a=Fh(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Lh(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:jh(a)})}return s}function Nh(e){try{return JSON.parse(e)}catch{return null}}function Fh(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Lh(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function jh(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var Dh={general:"general",generalist:"general",explore:"explore",explorer:"explore",plan:"plan",planner:"plan",planning:"plan",code:"code",coder:"code",coding:"code",research:"research",researcher:"research",verify:"verify",verifier:"verify",verification:"verify"},Bh=["type","role","specialization","agentType","agent_type"],qh=["task","objective","instruction","instructions","request","query"],Uh=["async","runInBackground","run_in_background"];function zh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Xn(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function vu(e){let t=e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-agent$/,"");return Dh[t]??t}function ii(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e===1?!0:e===0?!1:void 0;if(typeof e=="string")switch(e.trim().toLowerCase()){case"true":case"yes":case"1":case"background":case"async":return!0;case"false":case"no":case"0":case"foreground":case"sync":return!1;default:return}}function Tu(e,t){if(e!=="agent")return{rawArguments:t,corrections:[]};let n;try{n=JSON.parse(t)}catch{return{rawArguments:t,corrections:[]}}let o=zh(n);if(!o)return{rawArguments:t,corrections:[]};let r=[],s=Xn(o.agent);if(s){let a=vu(s);a!==s&&(o.agent=a,r.push("agent-value"))}else for(let a of Bh){let c=Xn(o[a]);if(c){o.agent=vu(c),delete o[a],r.push(`${a}->agent`);break}}if(!Xn(o.prompt)){let a;for(let c of qh){let l=Xn(o[c]);if(l){o.prompt=l,delete o[c],a=c;break}}if(a)r.push(`${a}->prompt`);else{let c=Xn(o.description);c&&(o.prompt=c,r.push("description->prompt"))}}let i=ii(o.background);if(o.background!==void 0&&i!==void 0)o.background!==i&&(o.background=i,r.push("background-value"));else if(o.background===void 0){let a;for(let c of Uh){let l=ii(o[c]);if(l!==void 0){o.background=l,delete o[c],a=c;break}}if(a)r.push(`${a}->background`);else{let c=ii(o.foreground);c!==void 0&&(o.background=!c,delete o.foreground,r.push("foreground->background"))}}return r.length>0?{rawArguments:JSON.stringify(o),corrections:r}:{rawArguments:t,corrections:r}}var Rp=Ig(Cp(),1),SC=new Rp.Ajv2020({allErrors:!0,allowUnionTypes:!0,strict:!1,validateFormats:!1}),wp=new WeakMap;function EC(e){let t=wp.get(e);if(t)return t;let n=SC.compile(e);return wp.set(e,n),n}function AC(e){return e.instancePath?`arguments${e.instancePath}`:e.keyword==="required"&&typeof e.params.missingProperty=="string"?`arguments/${e.params.missingProperty}`:"arguments"}function $C(e){return(e??[]).slice(0,4).map(t=>`${AC(t)} ${t.message??`violates ${t.keyword}`}`).join("; ")}function xp(e,t,n){let o;try{o=JSON.parse(n)}catch{return{ok:!1,error:`Tool "${e}" arguments must be valid JSON.`}}if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,error:`Tool "${e}" arguments must be a JSON object.`};if(!t)return{ok:!0};try{let r=EC(t);return r(o)?{ok:!0}:{ok:!1,error:`Tool "${e}" arguments do not match the offered schema: ${$C(r.errors)}.`}}catch(r){return{ok:!1,error:`Tool "${e}" has an invalid offered JSON Schema: ${r instanceof Error?r.message:String(r)}.`}}}var PC=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,MC=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Lr(e){if(!MC.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?IC(e.message.content).trim():"";return t.length>0&&t.length<200&&PC.test(t)}function IC(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var OC=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,NC=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,FC=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,ac=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|产出|导出|自检)/i;function Dr(e,t,n){for(let o=e.length-1;o>=0;o--){let r=e[o];if(!r||r.role!=="tool")continue;let s=typeof r.content=="string"?r.content:"";if(s.startsWith("Error: ")){if(t){let i=typeof r.tool_call_id=="string"?r.tool_call_id:"",a=!1;for(let c=o-1;c>=0&&i;c--){let l=e[c];if(!l||l.role!=="assistant"||!Array.isArray(l.tool_calls))continue;let d=l.tool_calls.find(y=>y?.id===i);if(!d)continue;let p=d.function;a=p?.name===t&&(n===void 0||p.arguments===n);break}if(!a)continue}return s.slice(7).trim()}}}var LC=/(?:^|[,。!?;:、,.!?;:()()"'「」『』])(?:我们?)?(?:目前|暂时|现在|当前)?(?:无法|不能|没有办法|做不到|不具备|暂不支持|不支持)[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)|我们?(?:目前|暂时|现在)?没有[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)/,jC=/\b(?:i\s+(?:can(?:no|')t|cannot|am unable to|don['’]?t have|do not have|lack))\b[^.!?\n]{0,60}\b(?:ability|capability|permission|access|tool|feature|screenshot|support)\b|\bno such (?:tool|capability)\b/i;function Sp(e){let t=e.trim();return t.length===0||t.length>600?!1:LC.test(t)||jC.test(t)}function Br(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.round(e):0}function Ep(e){if(!e)return 0;let t=new Set,n=new Set,o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&n.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(OC))o(i[0]);if(ac.test(s)){for(let i of s.matchAll(NC)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let c=a.replace(/\\/g,"/").split("/").pop();c&&n.add(c)}for(let i of s.matchAll(FC)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function qr(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1){let t=Math.round(e);return t>100&&console.error(`[tool-loop] requested per-round maxToolCalls ${t} exceeds the provider cap ${100} \u2014 clamped to ${100}`),Math.min(t,100)}return Zl}function Ap(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function cc(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
|
|
8
|
+
deps: ${n}}`};var $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(`
|
|
9
9
|
|
|
10
|
-
`)):""}function
|
|
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}
|
|
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
|
|
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
|
|
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
|
|
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=
|
|
25
|
-
`).pop()?.trim();o(c)}return{paths:t,deletes:n}}function
|
|
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+${
|
|
27
|
-
`).replace(/\\/g,"/").toLowerCase()}function Gr(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return Hp(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return $o(`${n}/${r.name}`).size>0}catch{return!1}})}let t=$o(e);return t.isFile()&&t.size>0}catch{return!1}}function tw(e,t){let n=re(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Wp(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,a=i.id,c=i.function;typeof a=="string"&&c?.name==="agent"&&t.add(a)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&en(o))return!0}return!1}function nw(e){let t=Jp(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function ow(e){let t=Vp(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function rw(e){if(e.length===0)return"";let t=e.map(o=>ow(o).split("/")),n=[];for(let o=0;o<t[0].length;o++){let r=t[0][o];if(t.every(s=>s[o]?.toLowerCase()===r.toLowerCase()))n.push(r);else break}return n.join("/")}function sw(e,t){let n=re(e);return t.some(o=>{let r=re(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function hc(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,l=a.function;if(typeof c!="string"||l?.name!=="write"&&l?.name!=="edit"||typeof l.arguments!="string")continue;let d=tn(l.arguments);if(!d)continue;let p=Mo(d);p&&n.set(c,p)}}for(let o of e){let r=o;if(!en(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o)}function iw(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function aw(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function cw(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,l=a.function;if(typeof c!="string"||l?.name!=="write"&&l?.name!=="edit"||typeof l.arguments!="string")continue;let d=tn(l.arguments);if(!d)continue;let p=Mo(d)??"",y=Yp(d);(/\bartifact[-_\s]?index\b/i.test(p)||/\bartifact[-_\s]?index\b/i.test(y))&&n.set(c,y)}}for(let o of e){let r=o;if(!en(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o).filter(o=>o.trim().length>0)}function lw(e){let t=Jp(e.inputMessages);if(!iw(t))return[];let n=cw(Et(e.inputMessages,e.messages)).at(-1);if(!n)return[];let o=[],r=aw(t).filter(i=>!new RegExp(`\\b${Xp(i)}\\b`,"i").test(n));r.length>0&&o.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=n.split(/\r?\n/u).filter(i=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(i)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(i));return s.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${s.slice(0,3).join(" ; ")}`}),o}function uw(e){let t=[],n=o=>{let r;try{r=Hp(o,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${o}/${s.name}`;if(s.isDirectory()){n(i);continue}if(s.isFile())try{$o(i).size>0&&t.push(i)}catch{}}};try{if(!$o(e).isDirectory())return[]}catch{return[]}return n(e),t}function Et(e,t){if(t.length<e.length)return t;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return t;return t.slice(e.length)}function dw(e,t){if(!nw(e))return[];let n=Vr(e),o=n.filter(i=>!re(i).endsWith("/*"));if(o.length<2)return[];let r=rw(o);if(!r||r.split("/").length<3)return[];let s=re(r);return[...new Set([...hc(Et(e,t)),...uw(r)])].filter(i=>re(i).startsWith(`${s}/`)&&!sw(i,n)&&Gr(i))}function Kp(e,t){let n=Vr(e);if(n.length===0)return[];let o=QC(e),r=Et(e,t),s=gc(r),i=fw(r),a=pw(r);return n.filter(c=>{if(o.has(re(c))||tw(s,c))return!1;let l=re(c);return!((i.has(l)||a.has(l))&&Gr(c))})}function fw(e){let t=new Set;for(let o of e){let r=o;en(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.function;if(c?.name!=="read"||typeof a.id!="string"||typeof c.arguments!="string"||!t.has(a.id))continue;let l=tn(c.arguments),d=l?Mo(l):void 0;d&&n.add(re(d))}}return n}function pw(e){let t=new Set;for(let o of e){let r=o;en(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.function,l=typeof c?.name=="string"?Se(c.name):"";if(l!=="image_understand"&&l!=="video_understand"||typeof a.id!="string"||typeof c?.arguments!="string"||!t.has(a.id))continue;let d=tn(c.arguments);if(!d)continue;let p=l==="image_understand"?d.image_url:d.video_url;typeof p=="string"&&p.trim()&&n.add(re(p))}}return n}function Ur(e){return yc(e).fail}function mw(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function zr(e){if(!e)return!1;let t=mw(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function yc(e){let t=r=>r.replace(/[.,;:]+$/u,""),n,o;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))zr(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))zr(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))zr(s[1])&&(n=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))zr(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Jp(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&typeof n.content=="string")return n.content}return""}function Xp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $n(e){let t=Kp(e.inputMessages,e.messages).filter(n=>!Gr(n));if(t.length!==0)return`[Engine notice] ${e.reason}; explicitly requested output files still missing: ${t.join(", ")}.`}function tn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Mo(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Yp(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Zp(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=yc(e.inputMessages);if(!n.done)return;let o=tn(e.toolCall.function.arguments);if(!o)return;let r=Mo(o),s=Yp(o);if(!r||!s.includes(n.done))return;let i=Vr(e.inputMessages);if(i.length<2)return;let a=re(r);if(!i.some(p=>re(p)===a))return;let l=gc(e.messages),d=i.filter(p=>re(p)!==a).filter(p=>!l.includes(re(p)));if(d.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${d.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Zt(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Qt(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Qp(e){try{return $o(e).isFile()}catch{return!1}}function gw(e,t,n){let o=/[,.,。;;!?!?\n]/u,r=t;for(;r>0&&!o.test(e[r-1]);)r--;let s=t+n;for(;s<e.length&&!o.test(e[s]);)s++;if(mc.test(e.slice(r,s)))return!0;let i=s<e.length?s+1:s,a=i;for(;a<e.length&&!o.test(e[a]);)a++;let c=e.slice(i,a);return mc.test(c)&&/(?:这个|该|此)文件|\b(?:this|that|the)\s+file\b/i.test(c)}function hw(e,t){let n=new Map;for(let i of e){if(i.role!=="user"||typeof i.content!="string")continue;let a=Hr(i.content);if(mc.test(a))for(let c of a.matchAll(Po)){if(!gw(a,c.index??0,c[0].length))continue;let l=c[0].replace(/[),.;:,。;]+$/u,""),d=re(l);d&&n.set(d,l)}}if(n.size===0)return[];let o=gc(Et(e,t)),r=Wp(Et(e,t)),s=[];for(let[i,a]of n)(o.includes(i)||r&&Qp(a))&&s.push(i);return s}var yw="File not found:",zp=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,bw=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function _w(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),a=s.includes(t)||n.length<=3||n===t?[t]:[n];for(let c of a){let l=0;for(;;){let d=s.indexOf(c,l);if(d===-1)break;l=d+1;let p=d;for(;p>0&&!o.test(s[p-1]);)p--;let y=d+c.length;for(;y<s.length&&!o.test(s[y]);)y++;let v=r.content.slice(p,y);if(zp.test(v))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),a=Array.from(r.content.matchAll(Po)).map(l=>re(l[0])).some(l=>l!==t),c=s.includes(t)||!a&&n.length>3&&n!==t&&s.includes(n);if(!a&&c&&zp.test(r.content)&&bw.test(r.content))return!0}return!1}function vw(e){let t=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,l=a.function;if(typeof c!="string"||l?.name!=="read"||typeof l.arguments!="string")continue;let d=tn(l.arguments),p=d?Mo(d):void 0;p&&t.set(c,p)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(yw)&&n.set(re(i),i)}return n}function Tw(e,t){let n=Et(e,t),o=vw(n);if(o.size===0)return[];let r=new Set(hc(n).map(re)),s=[];for(let[i,a]of o)_w(e,i)||(r.has(i)||Qp(a))&&s.push(i);return s}function bc(e){let t=[...e.inputMessages].reverse().find(v=>v.role==="user"),n=typeof t?.content=="string"?t.content:"",o=HC.test(n)||VC.test(n)&&Vr(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit")||Gp(Et(e.inputMessages,e.messages)).length>0,s=yc(e.inputMessages),i=s.fail!==void 0&&e.finalText.includes(s.fail)||/\bFAILED\b/.test(e.finalText),a=hw(e.inputMessages,e.messages);if(a.length>0&&!i){e.log.info(`forbidden-file-creation guard: agent wrote ${a.length} file(s) the user forbade creating`);let v=Ur(e.inputMessages),h={role:"user",content:`You created a file the request explicitly forbade creating: ${a.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${v??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Qt("forbidden_file_creation",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let c=Tw(e.inputMessages,e.messages);if(c.length>0&&!i){e.log.info(`self-created-read-target guard: agent created ${c.length} file(s) it had read as not-found`);let v=Ur(e.inputMessages),h={role:"user",content:"You were asked to read "+c.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${v??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Qt("self_created_read_target",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let l=Wp(e.messages),d=Kp(e.inputMessages,e.messages).filter(v=>!(l&&Gr(v)));if(d.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`explicit required file verification: ${d.length} file(s) missing`);let v=Ur(e.inputMessages),h={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${d.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${v??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Qt("explicit_required_file_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let p=dw(e.inputMessages,e.messages);if(p.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`explicit extra file verification: ${p.length} unexpected file(s)`);let v=Ur(e.inputMessages),h={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${p.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${v??"FAILED"} and the real reason. Do not claim completion while extra deliverables remain.`};return Qt("explicit_extra_file_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}let y=lw({inputMessages:e.inputMessages,messages:e.messages});if(y.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`artifact index evidence verification: ${y.length} issue(s)`);let v={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+y.map(h=>h.detail).join(" ")+" Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, finish with the final status contract."};return Qt("artifact_index_evidence_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),v)}if(e.stopHookActive)return null;if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge");let v={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return Qt("file_action_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),v)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")){let v=[...new Set(hc(Et(e.inputMessages,e.messages)).map(re))].filter(h=>kw.test(h)&&!Cw(h));if(v.length>=3){e.log.info(`AP3 verification nudge: ${v.length} code files created, injecting completeness check`);let h={role:"user",content:"You created multiple code files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. Fix anything that fails these checks. Either way, your FINAL message must answer the user's actual request \u2014 do not end on this checklist confirmation."};return Qt("multi_file_skeleton_verification",e.messages,Zt(e.finalText,e.thinkingBlocks),h)}}return null}var kw=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|kts|cs|cpp|cc|c|h|hpp|vue|svelte)$/i;function Cw(e){let t=re(zC());return t.length>0&&e.startsWith(`${t}/`)}function ww(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function em(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,ww(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var _c="```final-status",Rw=/\r?\n[ \t]*```/;function xw(e,t){let n=Math.min(e.length,t.length-1);for(let o=n;o>0;o--)if(e.endsWith(t.slice(0,o)))return o;return 0}function tm(){let e="",t=!1;function n(){let o="";for(;;){if(t){let s=Rw.exec(e);if(!s)return o;e=e.slice(s.index+s[0].length),t=!1;continue}let r=e.indexOf(_c);if(r===-1){let s=xw(e,_c);return o+=e.slice(0,e.length-s),e=e.slice(e.length-s),o}o+=e.slice(0,r),e=e.slice(r+_c.length),t=!0}}return{push(o){return o?(e+=o,n()):""},flush(){if(t)return e="","";let o=e;return e="",o},isSuppressing:()=>t}}var nm=5;function Sw(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Ew(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function vc(e,t){let n=e.recoveryTrace;if(!n)return;let o=`budget_continuation_stop:${t}`;n.set(o,(n.get(o)??0)+1)}function om(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=Sw(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=nm)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${nm}) at ${Math.round(n)}% used`),vc(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=iu&&o<Xs&&e.lastBudgetDeltaTokens<Xs)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),vc(e,"diminishing_returns"),null;if(n>=90)return e.log.info(`token budget continuation stop: ${Math.round(n)}% of ${e.tokenBudget} tokens used (>=90% headroom floor), not nudging further work`),vc(e,"headroom_floor"),null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,Ew(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}import{createHash as rm}from"node:crypto";function sm(e){let t=[{value:e,depth:0}],n=new Set;for(;t.length>0;){let o=t.shift();if(!(!o.value||typeof o.value!="object"||o.depth>8)&&!n.has(o.value)){if(n.add(o.value),!Array.isArray(o.value)){let r=o.value,s=Object.hasOwn(r,"billed")&&(r.billed===null||typeof r.billed=="boolean"),i=["retryable","safeToRetry","retryMode","automaticRetryAuthorized"].some(a=>Object.hasOwn(r,a));if(s&&i)return{billed:r.billed,retryable:r.retryable===!0,safeToRetry:r.safeToRetry===!0,retryMode:typeof r.retryMode=="string"?r.retryMode:"unspecified",automaticRetryAuthorized:r.automaticRetryAuthorized===!0,...typeof r.stage=="string"?{stage:r.stage}:{}}}for(let r of Array.isArray(o.value)?o.value:Object.values(o.value))t.push({value:r,depth:o.depth+1})}}}var Mn="*";function im(e,t,n){let o=[],r=[];for(let s of e){let i=Tc(s.function.name,s.function.arguments),a=dm(s.function.name,Mn),c=Math.max(t.get(i)??0,t.get(a)??0);if(c>=nr){let l=Aw(s);if(n.has(l)){n.delete(l),o.push(s);continue}n.add(l),r.push({call:s,failCount:c,error:`Tool "${s.function.name}" has failed ${c} times this turn with the same canonical arguments. Stop repeating that exact invocation. Correct the declared schema or parameters, switch to a verified target, or report the issue to the user. If you are certain this exact call is a deliberate retry of a transient failure, re-issue exactly the same call once more and it will run.`})}else o.push(s)}return{allowed:o,blocked:r}}function Aw(e){return`${e.function.name}::${e.function.arguments}`}function am(){return{role:"user",content:"Tool calls were blocked because the exact canonical invocation has failed too many times. Correct the arguments, use a different verified operation, or tell the user what happened."}}function cm(e){if(e.ok){e.toolFailureCounts.delete(Tc(e.toolName,e.toolArguments));return}let t=Tc(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function lm(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=nr&&(e.snapshot.get(n)??0)<nr){let{toolName:r,target:s}=qw(n);t.push({role:"user",content:`Tool "${r}" has now failed ${o} times for target "${s}". Do not repeat the same failed invocation unchanged. A call with corrected arguments remains available. If this exact call is a deliberate retry of a transient failure, re-issue it after it is blocked and it will run once. Otherwise report the result to the user immediately.`})}return t}function Tc(e,t){return dm(e,$w(e,t))}function $w(e,t){let n=Bw(t);if(e==="read"||e==="write"||e==="edit"||e==="patch")return Pn(n?.path??n?.file_path??n?.filePath);if(e==="search")return Pn([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|"));if(e==="exec"){let o=typeof n?.command=="string"?n.command:void 0;return Pn(o?Ao(o):void 0)}return Iw(n)}var Pw=["runtime_id","runtimeId","operation","action","method","resource_type","resourceType"],Mw=["kind","interactionIntent","targetRole"];function Iw(e){if(!e)return Mn;let t=Pw.flatMap(i=>typeof e[i]=="string"&&e[i].trim()?[`${i}=${Pn(e[i])}`]:[]),n=Dw(e);n&&t.push(n);let o=Object.keys(e).sort().join(",");o&&t.push(`shape=${o}`);for(let[i,a]of Object.entries(e)){if(!um(a))continue;let c=Mw.flatMap(l=>typeof a[l]=="string"&&a[l].trim()?[`${i}.${l}=${Pn(a[l])}`]:[]);t.push(...c)}let r=Array.isArray(e.args)?jw(e.args):"";r&&t.push(`argv=${r}`);let s=Fw(e);return s&&t.push(`payloadShape=${s}`),t.push(`arguments=${Ow(e)}`),t.length>0?t.join("|"):Mn}function Ow(e){return rm("sha256").update(JSON.stringify(kc(e))).digest("hex").slice(0,24)}function kc(e){return Array.isArray(e)?e.map(kc):um(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,kc(e[t])])):e}var Nw=["stdin","input","payload","body","request","data"];function Fw(e){let t=[];for(let n of Nw)n in e&&t.push(`${n}:${Cc(Lw(e[n]))}`);if(t.length!==0)return rm("sha256").update(t.join("|")).digest("hex").slice(0,24)}function Lw(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Cc(e,t=0){if(t>=12)return"depth-limit";if(e===null)return"null";if(Array.isArray(e))return`array[${[...new Set(e.slice(0,64).map(o=>Cc(o,t+1)))].sort().join(",")}]`;if(typeof e=="object"){let n=e;return`object{${Object.keys(n).sort().map(o=>`${o}:${Cc(n[o],t+1)}`).join(",")}}`}return typeof e}function jw(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(typeof o!="string"||!o.startsWith("-"))continue;let r=o.toLowerCase(),s=e[n+1];if(typeof s=="string"&&!s.startsWith("-")){let i=s.indexOf("="),a=i>0?s.slice(0,i).trim().toLowerCase():"";a&&(r+=`:${a}`)}t.push(r)}return t.join(",")}function Dw(e){for(let t of["url","uri"]){let n=e[t];if(!(typeof n!="string"||!n.trim()))try{let o=new URL(n);return`${t}=${o.origin.toLowerCase()}`}catch{return`${t}=invalid-url`}}for(let t of["path","file_path","filePath","target","resource","resource_id","resourceId"]){let n=e[t];if(typeof n=="string"&&n.trim())return`${t}=${Pn(n)}`}}function um(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Bw(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Pn(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Mn}function dm(e,t){return`${e}::${t}`}function qw(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Mn}:{toolName:e.slice(0,t),target:e.slice(t+2)||Mn}}var Ec=new Set(["write","edit","patch"]),Ac=new Set(["image_generate"]),gm=new Set(["cad_design","industrial_runtime","solidworks_create"]),Uw=/\b(?:verify|test|check|validate)\b[\s\S]{0,48}\b(?:browser|browser-visible|playwright|visible ui)\b|\b(?:browser|browser-visible|playwright|visible ui)\b[\s\S]{0,48}\b(?:verify|test|check|validate)\b/i,zw=/\b(?:build|create|make|develop|implement|scaffold|generate|set ?up)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i,Hw=/\b(?:output\s+to|save\s+to|deliver\s+to|write\s+to|generate\s+into|output\s+(?:directory|folder)\s*(?:[:=]|is)?)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:输出到|保存到|放到|交付到|生成到|输出目录)\s*[::]?\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,$c=/https?:\/\/[^\s"'`<>),;]+/gi,Vw=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|无法访问|(?:发生|出现|报|加载|请求|页面|控制台|连接|断言|验证|测试|检查|等待|打开|访问)[^\n]{0,10}(?:错误|失败|超时)|(?:错误|失败|超时)(?:[::]|码|代码|信息|堆栈)/i,Gw=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,fm=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i,Ww=new Set(["browser_automation","frontend_test","user_confirmation","external_benchmark","fork_verify"]),Kw=/\b(?:i have|i've|i)\s+(?:verified|checked|confirmed|reviewed|tested)\b[\s\S]{0,80}\b(?:ui|page|screen|interface|frontend)\b[\s\S]{0,48}\b(?:works?|correct|passed|looks? good|as expected)\b|(?:我已经|我已|已经|已)(?:查看|检查|确认|验收|测试)[\s\S]{0,36}(?:页面|界面|UI|前端|截图)[\s\S]{0,24}(?:正常|通过|没问题|符合预期|正确)/i,Jw=/\b(?:vitest|jest|cypress|playwright|storybook|testing-library)\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|test:ui|test:component)\b/i,Xw=/\.(?:tsx|jsx)\b|testing-library|(?:render(?:ed|ing)?|screen|dom|component|dashboard|navigation|heading|button|dialog|page|ui)\b|(?:渲染|页面|界面|组件|导航|标题|按钮)/i,Yw=/\bPASS\b|(?:test files?|tests?)\s+\d+\s+passed|\b\d+\s+passed\b|(?:^|\n)\s*[✓✔]\s|(?:测试|用例).{0,12}(?:通过|成功)/i;function Zw(e){let t=Fc(e),n={artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],deletedPaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]},o=[...e].reverse().find(r=>r.role==="user");for(let r of o?[o]:[]){if(r.role!=="user"||typeof r.content!="string"||!Kw.test(r.content))continue;let s=(r.imageUrls?.length??0)>0||/(?:screenshot|截图)/i.test(r.content),i=`${r.content.trim()}${s?" [screenshot-backed]":""}`;Io(n,{source:"user_confirmation",status:"passed",summary:i})}return n}function Kr(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(zw.test(t.content)||Uw.test(t.content)))}var Qw=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function hm(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Qw.test(t.content))}var wc=/```final-status[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```/g,eR=new Set([...Ec,...Ac,...gm,"exec","bash","shell","powershell","terminal","playwright","browser","computer"]);function ym(e){for(let t of e)if(eR.has(Se(t)))return!0;return!1}var bm=["## Final status block","When this turn produced artifacts (files written, apps served), asserted verification (browser/build/tests), left requested work incomplete or blocked, or the user explicitly asked for a final status or an evidence audit, end your final message with exactly one fenced block:","","```final-status",'{"schema":1,"done":["\u2026"],"notDone":["\u2026"],"artifacts":{"root":"\u2026","files":["\u2026"],"urls":["\u2026"]},"verification":{"browser":"verified|failed|not-run","build":"passed|failed|not-run"},"sources":{"cited":["https://\u2026"]},"blockers":["\u2026"],"nextAction":"\u2026"}',"```","","Every field must reflect actual tool activity from this turn; the engine cross-checks the block against its own tool records and strips unsupported claims. Omit fields that do not apply. Omit the whole block for ordinary conversation."].join(`
|
|
28
|
-
`);function
|
|
29
|
-
${e.content}`;for(let c of a.matchAll(
|
|
30
|
-
`),{claim:l,notices:d}=
|
|
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(`
|
|
31
31
|
|
|
32
|
-
`),malformedBlock:!1,notices:d}}let o=n!==null;if(
|
|
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}
|
|
33
33
|
|
|
34
|
-
${s}`:s,malformedBlock:o,notices:[]}}function
|
|
35
|
-
${n}`),c=
|
|
36
|
-
${n}`)
|
|
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]
|
|
37
37
|
AUDIO_STT_RESULT ${i[1]} ${o}`:`[transcription]
|
|
38
|
-
${o}`}function
|
|
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:
|
|
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
|
|
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}
|
|
41
41
|
|
|
42
42
|
Tool availability diagnostics:
|
|
43
43
|
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
44
44
|
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
45
45
|
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
46
46
|
blockedToolCalls: ${n}
|
|
47
|
-
attribution: ${r}`}function
|
|
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
48
|
`+e.join(`
|
|
49
|
-
`)}}function
|
|
50
|
-
`),i=
|
|
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(`
|
|
51
51
|
`);return["You have already read and indexed requirements.md, decisions.md, defects.md, and acceptance.md for this long-horizon benchmark.","Do not read context-pack, persisted tool-result previews, or compact benchmark-state files again in this turn.","Before any more analysis or final answer, maintain the benchmark state files using write/edit/patch only.",`Benchmark-state directory: ${o}.`,`Missing files: ${n.join(", ")}.`,"Create missing files with write. If any target already exists, update it with edit or patch instead of write.","For every contentHash and fileSizeBytes you write, copy the EXACT value from the 'Document evidence already available' section below. Do NOT compute, approximate, or invent a hash \u2014 you must not re-read the large read-only context-pack files to produce one.","The context-pack inputs (requirements.md, decisions.md, defects.md, acceptance.md) are READ-ONLY and immutable: their content and contentHash cannot change between turns. If a hash ever appears to differ from what you recorded, the source did NOT change \u2014 suspect your own recorded value first (stale, or never tool-derived). Never raise a 'source changed' blocker for these files.","Acceptance verdicts are monotonic unless re-derived from primary evidence: do NOT flip a previously-PASSing criterion to FAIL on a derived/secondary signal such as a hash diff. Change a PASS to FAIL only after re-checking the actual acceptance condition against primary evidence, and cite that evidence.","Required files:","- document-index.json: include contextPackPath and a documents object keyed by requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, fileSizeBytes, recordCount, indexVersion, summary, and lastReviewedTurn.","- decision-state-table.json: include D001-D006 with id, decision, status, evidence, and lastConfirmedTurn.","- context-pack-evidence.json: include turn and fileVerification for requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, and fileSizeBytes.",`Current turn: ${t}.`,"Document evidence already available:",s,"Decision records to preserve:",i].join(`
|
|
52
|
-
`)}function Wm(e){return Uc.has(e)}function c0(e){return e.longHorizonStateMaintenanceRequiredFiles.size>0&&[...e.longHorizonStateMaintenanceRequiredFiles].every(t=>l0(e,t))}function l0(e,t){if(e.longHorizonStateMaintenanceWrittenFiles.has(t))return!0;try{if(!sn(t))return!1;let n=At(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=os(t,"utf8");return Xc(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function Xc(e,t,n){let o=At(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=R0(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=tt(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=Me(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let c of Fe.keys()){let l=e.get(c),d=Me(a[c]);if(!l||!d)return{ok:!1,reason:`document-index.json missing ${c}`};if(d.contentHash!==l.contentHash)return{ok:!1,reason:`document-index.json ${c} contentHash does not match read.details`};if(d.fileSizeBytes!==l.fileSizeBytes)return{ok:!1,reason:`document-index.json ${c} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=Me(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Fe.keys()){let c=e.get(a),l=Me(i[a]);if(!c||!l)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(l.contentHash!==c.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(l.fileSizeBytes!==c.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function u0(e){if(!og(e))return[];let t=Jc(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!sn(r))continue;s=os(r,"utf8")}catch{continue}let i=Xc(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function d0(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<o0)return!1;let s=new Set([...t].filter(Kc).map(At));return[...Fe.keys()].every(a=>s.has(a))?[...Fe.keys()].every(a=>o.has(a))||n||i0(t):!1}function sg(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=ns(t);if(!o)return null;try{if(!sn(o))return null}catch{return null}return{path:o,error:`Existing file update blocked for "${o}". Use edit or patch for existing files so the event stream can distinguish file creation from incremental maintenance. If you are certain a full-file write is the right action here (not an incremental edit), re-issue exactly the same write call once write is offered again and it will run once.`}}var ts=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*f0(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let o,r=await Promise.race([n.next(),new Promise(s=>{o=setTimeout(()=>s("timeout"),t)})]);if(o&&clearTimeout(o),r==="timeout")throw new ts(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function zc(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function ns(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function p0(e){return e.flatMap(t=>{if(m0(t.function.arguments))return[t];let n=g0(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function m0(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function g0(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let c=e[a];if(r){s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(c!=="}"||(n-=1,n!==0||o<0))continue;let l=tt(e.slice(o,a+1));if(!l)return[];t.push(l),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function tt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Te(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function At(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Yc(e){return`sha256:${Jm("sha256").update(e).digest("hex")}`}function h0(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function y0(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function b0(e,t,n,o){let r=[...t.values()].sort((c,l)=>(c.name??"").localeCompare(l.name??""));if(r.length===0)return null;let s=r.map(c=>`${c.name??"document"}:${c.contentHash??"unknown"}`).join("|"),i=eg.map(c=>({...c,evidence:`read:long-horizon-documents:${Yc(`${c.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Fo,observedReadsByPath:y0(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function _0(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Yr(e,t){return e.get(t)??null}function v0(e){let t=Yr(e,"requirements.md"),n=Yr(e,"decisions.md"),o=Yr(e,"defects.md"),r=Yr(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:_0(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function T0(e,t){let n=v0(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function k0(e,t,n,o,r){let s=Hc(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function Hc(e,t,n,o){let r=At(e);if(!Fe.has(r))return null;let s=S0(t)??t,i=x0(o,"contentHash"),a=On(o??null,"fileSizeBytes"),c=i??Yc(s);return{name:r,path:Te(e),indexed:!0,maintained:!0,indexVersion:c,contentHash:c,summary:h0(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:ig(s)}}function C0(e,t){return sg(e.function.name,e.function.arguments,t)!==null}function w0(e,t){let n=ns(t.function.arguments);return`This exact write call to an existing file has been attempted ${e} times${n?` for "${n}"`:""}. Do not call write again for this existing file. Use edit or patch for the existing-file update, then continue verification.`}function R0(e){let n=tt(e)?.content;return typeof n=="string"?n:void 0}function x0(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function ig(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function S0(e){if(!e.includes("<persisted-output>"))return null;let n=e.match(/Full output saved to:\s*(.+?)(?:\r?\n|$)/)?.[1]?.trim();if(!n)return null;try{return sn(n)?os(n,"utf8"):null}catch{return null}}function E0(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=zc(i.function.arguments);if(!a)continue;let c=Te(a);tg(c)===Fo&&t.set(i.id,{path:c})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let c=Hc(i.path,a,0);c?.name&&o.set(c.name,c)}for(let s of I0(e)){r=!0;for(let i of Fe.keys()){let a=Te(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,Fo)),!o.has(i)){let c=Hc(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);c?.name&&o.set(c.name,c)}}}for(let s of A0(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Fo)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedLongHorizonStateRecovered:r}}function A0(e){let t=[];for(let n of $0(e)){let o=Km(`${n}/document-index.json`),r=Km(`${n}/context-pack-evidence.json`),s=Nn(o,"contextPackPath")??P0(r);if(!s)continue;let i=M0(s,o,r);i.length===Fe.size&&t.push({documents:i})}return t}function $0(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=Te(s[1]??"");i&&t.add(i)}}return[...t]}function Km(e){try{if(!sn(e))return null;let t=JSON.parse(os(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Nn(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?Te(n):void 0}function P0(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of Fe.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=Nn(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function M0(e,t,n){let o=Me(t?.documents),r=Me(n?.fileVerification),s=[];for(let i of Fe.keys()){let a=Me(o?.[i]),c=Me(r?.[i]);if(!a&&!c)return[];let l=Nn(a,"path"),p=Nn(c,"path")??(l?.includes("/context-pack/")?l:Te(`${e}/${i}`)),y=Nn(a,"contentHash")??Nn(c,"contentHash")??Yc(`${i}:${p}`),v=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:Te(p),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??y),contentHash:y,summary:v,lastReviewedTurn:Vc(a,"lastReviewedTurn")??Vc(n,"turn")??0,fileSizeBytes:On(a,"fileSizeBytes")??On(c,"fileSizeBytes")??On(c,"sizeBytes")??Buffer.byteLength(v,"utf8"),recordCount:On(a,"recordCount")??On(c,"recordCount")??ig(v)})}return s}function Vc(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function On(e,t){let n=Vc(e,t);return n&&n>0?n:void 0}function I0(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=Te(i[1]??"");a&&n.add(a)}}return[...n]}function O0(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));qc.has(n)&&(e.identicalCallCounts.delete(t),e.identicalFailureCounts.delete(t))}}async function*ag(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:c,model:l,apiKey:d,temperature:p=0,hooks:y,signal:v}=e,h=(b,H)=>{b.push(H)},_={sessionId:s,turnId:r},k=e.maxTurns??0,C=e.querySource,E=a??c,O=e.runtimePorts.resolveToolEligibility(E,e.toolEligibilityContext),U=new Set(c.map(b=>b.function.name)),M=nn(O.eligibleTools,E),Q=new Map(M.map(b=>[b.function.name,b])),Ie=nn(O.eligibleTools.filter(b=>U.has(b.function.name)),E),ee=[];for(let b of O.blockedTools){let H=E.find(oe=>oe.function.name===b.toolName);H&&Qr(H)||(ee.push({name:b.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:b.toolName,reason:"blocked-by-policy"})}let Ge=Br(e.maxRounds,i),nt=qr(e.maxToolCalls),an=Ep(i),at={contextWindowTokens:e.contextWindowTokens??tu,responseBufferTokens:nu,maxOutputTokens:e.maxOutputTokens??ou,abortSignal:v,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},Oe=new Set,ct=[],Zc=new Map,$t=0,Qc=new Set,el=0,rs=new Map,tl=new Set,We,Fn=!1,Ln=!1,ss=new Set,Le=new Set,Lo=new Set(e.deferredToolNames??[]),cn=new Set;for(let b of e.loadedDeferredToolNames??[])Lo.has(b)&&Q.has(b)?cn.add(b):e.loadedDeferredToolNames?.delete(b);let Ke=()=>{let b=new Map(Ie.map(H=>[H.function.name,H]));for(let H of cn){let oe=Q.get(H);oe&&b.set(H,oe)}return[...b.values()]},nl=(b,H)=>H?b.filter(oe=>H.has(oe.function.name)):[...b],x=Ke(),jn=!1,is,as=()=>I(x),ug=CR(Ie,i),cs=!1,ol=0,rl=0,ls=0,sl=0,il=0,al=new Set,Dn=new Map,ge=!1,Bn=!1,us=E0(i),f={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ys(at),reactiveCompactState:ni(),toolLoopState:Qo({maxRounds:Ge,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ds(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalFailureCounts:new Map,commercialRetryBlocks:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,variantReassertedSignatures:new Set,fileReadCounts:us.fileReadCounts,fileReadSignatures:new Map,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:us.maintainedDocuments,persistedLongHorizonStateRecovered:us.persistedLongHorizonStateRecovered,longHorizonStateMaintenanceRequiredFiles:new Set,longHorizonStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:wm(i),buildVerificationRecoveryCount:0,longHorizonStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentPollCounts:new Map,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},dg=4,fg=4,cl=0,ds=!1,ll=new Map,fs,z=(b,H)=>{let oe=`${b}:${H??""}`,ue=(ll.get(oe)??0)+1;if(ll.set(oe,ue),b==="autocompact"){let J=f.recoveryTrace.get("autocompact")??0;if(ue>dg||J>=fg){let De=`Repeated context compression made no forward progress: ${H??"autocompact"}`;return fs=De,f.recoveryTrace.set("compression_loop_guard",(f.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:De}}}return f.recoveryTrace.set(b,(f.recoveryTrace.get(b)??0)+1),{type:"recovery",turnId:r,action:b,detail:H}},Pt={roleAlias:0,promptAlias:0,backgroundAlias:0,agentValue:0,backgroundValue:0},ul=b=>({type:"tool_use_summary",turnId:r,ledgerSchemaVersion:4,toolCalls:ct.map(H=>({...H})),finalAnswerEvidence:b,availableToolNames:I(a??c),enabledToolNames:as(),toolCallNames:[...Oe].sort(),blockedToolCalls:Xr(ee),...Object.values(Pt).some(H=>H>0)?{argumentCorrections:{...Pt}}:{}}),dl=ym((a??c).map(b=>b.function.name)),ps=!1,jo=Rm(i),pg=b=>({type:"end",turnId:r,content:b,usage:f.totalUsage,model:f.currentModel,...f.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(f.recoveryTrace)}:{}});function*je(b,H){let oe=Jn(e.freshEvidenceRequired===!0,ct,[]),ue=oe.disposition.startsWith("blocked-")?ER(oe,jo):b,J=xm({content:ue,contractActive:dl,totalToolCallCount:$t,distinctToolNames:Oe,visibleToolCallCount:el,visibleToolNames:Qc,artifactContract:f.artifactContract,blockedToolCalls:Xr(ee),activeTasks:f.lastTaskList,forcedStop:H?.forcedStop??ps,locale:jo});J.malformedBlock&&(yield z("final_status_block_malformed","final-status block was not valid schema-1 JSON; treated as absent")),Oc(f.artifactContract,J.content),gs()&&(yield ms()),yield ul(oe),yield pg(J.content)}function*Je(b,H){let oe=Jn(e.freshEvidenceRequired===!0,ct,[]);yield ul(oe),yield{type:"error",turnId:r,error:b,code:H,usage:f.totalUsage}}let ms=()=>({type:"artifact_contract",turnId:r,...Ic(f.artifactContract,i)}),gs=()=>{let b=Ic(f.artifactContract,i);return!!(b.requiresBrowserAcceptance||b.artifactRoot||b.writePaths.length>0||b.outOfRootWrites.length>0||b.devServerUrls.length>0||b.browserVerified)},Do=(b,H,oe)=>{if(oe?.cleanStopWithFinalText&&f.finalText)return f.finalText;ps=!0;let ue=f.finalText||cc(b,o),J=jo==="zh"?`\u26A0\uFE0F \u672C\u8F6E\u88AB\u5F15\u64CE\u9650\u5236\u63D0\u524D\u4E2D\u6B62,\u4E0B\u9762\u7684\u7ED3\u679C\u53EF\u80FD\u4E0D\u5B8C\u6574\u3002(${H})`:`\u26A0\uFE0F This turn was stopped early by an engine limit; the result below may be incomplete. (${H})`;return ue?`${J}
|
|
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
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
55
|
|
|
56
|
-
${J}`:J:
|
|
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
57
|
|
|
58
|
-
`),
|
|
59
|
-
`);o.warn({event:"tool_schema_preflight_rejected",turnId:r,rejectedCallCount:
|
|
60
|
-
`+m}],finalText:"",transition:{reason:"next_turn"}};continue}}if(e.toolChoice==="none"&&ce.length===0&&yu(ye)){if(il<1){il++,yield z("direct_response_protocol_retry","no-tool answer leaked tool-protocol markup; retrying once"),f={...f,messages:[...b,{role:"user",content:"Your previous response used forbidden tool-call protocol text. This is a direct-response turn: perform the operation mentally and reply with only the requested result. Do not call, describe, or imitate any tool."}],finalText:"",transition:{reason:"next_turn"}};continue}let u="The model repeatedly emitted tool-call protocol during a direct-response turn.";ae(y,"stop.failure",{sessionId:s,reason:"MODEL_PROTOCOL_VIOLATION",error:u},o),yield*Je(u,"MODEL_PROTOCOL_VIOLATION");return}if(!K&&$t===0&&ce.length===0&&!qo&&ye.trim()===""&&ln.join("").trim()===""&&ot.length===0){if(sl<1){sl++,yield z("empty_response_retry","model returned an empty response; retrying once"),f={...f,messages:[...b,{role:"user",content:"Your previous response was empty. Reply with a substantive answer now. If you cannot complete the request, explain the blocker plainly instead of returning no content."}],finalText:"",transition:{reason:"next_turn"}};continue}let u="LLM returned an empty response twice before any tool use.";ae(y,"stop.failure",{sessionId:s,reason:"EMPTY_MODEL_RESPONSE",error:u},o),yield*Je(u,"EMPTY_MODEL_RESPONSE");return}if(ce.length===0&&!qo){if(e.drainPendingTaskNotifications){let R=e.drainPendingTaskNotifications().filter(P=>P.trim());if(R.length>0){zm(f,R),f={...f,messages:[...b,...ye?[{role:"assistant",content:ye}]:[],Um(R)]},o.info(`late background task result consumed at completion (${R.length} item(s)) \u2014 running another round`);continue}}if(e.drainPendingGuidance){let R=e.drainPendingGuidance().map(P=>P.trim()).filter(Boolean);if(R.length>0){f={...f,messages:[...b,...ye?[{role:"assistant",content:ye}]:[],...R.map(P=>({role:"user",content:P}))]},o.info(`late mid-turn guidance consumed at completion (${R.length} item(s)) \u2014 running another round`);continue}}if(ye){let R=f.transition?.reason==="max_output_tokens_escalate"||f.transition?.reason==="max_output_tokens_recovery";f.finalText=R?`${f.finalText}${ye}`:ye}if(e.toolChoice==="required"&&!cs&&x.length>0&&ol<2){ol++;let R=x.map(P=>P.function.name).filter(Boolean).slice(0,8).join(", ");f={...f,messages:[...b,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${R}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(zo&&K&&dc(K)){if(f.transition?.reason!=="collapse_drain_retry"){let R=qs(ht,hs);if(R.committed>0){o.info(`collapse drain: committed ${R.committed} stages`),yield z("collapse_drain",`${R.committed} stages committed`),f={...f,messages:R.messages,transition:{reason:"collapse_drain_retry",committed:R.committed}};continue}}if(pn(De)){De.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield z("reactive_compact","withheld prompt_too_long"),f={...f,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),ae(y,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:K.message},o),yield*Je(K.message,"PROMPT_TOO_LONG");return}if(zo&&K&&fc(K)){if(pn(De)){De.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield z("reactive_compact","media error strip-retry"),f={...f,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),ae(y,"stop.failure",{sessionId:s,reason:"media_error",error:K.message},o),yield*Je(K.message,"IMAGE_ERROR");return}if(Ip(kl)){J.consecutiveTruncations+=1;let R=e.modelMaxOutputTokens??ru,P=ei(J,at,R),Ne={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."},de=[...ht,...ye?[{role:"assistant",content:ye}]:[],Ne];if(P.shouldEscalate&&oe===void 0){J.currentMaxOutputTokens=P.newMax,o.info(`max_output_tokens escalate: ${P.newMax} tokens`),yield z("output_escalation",`${P.newMax} tokens`),f={...f,messages:de,maxOutputTokensOverride:P.newMax,transition:{reason:"max_output_tokens_escalate"}};continue}if(H<su){o.info(`max_output_tokens recovery #${H+1}`),yield z("max_output_tokens_recovery",`attempt ${H+1}`),f={...f,messages:de,maxOutputTokensRecoveryCount:H+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:H+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content"),ds=!0}else J.consecutiveTruncations=0;Be=Zo(Be,{replayMessages:b,lastStopReason:"completed"});let u=await em({hooks:y,sessionId:s,messages:b,finalText:f.finalText,thinkingBlocks:ot,log:o});if(u?.action==="end"){let R=mg(u.content,b,"stop hook prevented continuation before completing the final status contract");yield*je(R);return}if(u?.action==="continue"){f={...f,messages:u.messages,stopHookActive:u.stopHookActive,transition:u.transition};continue}let m=om({tokenBudget:e.tokenBudget,totalUsage:f.totalUsage,budgetContinuationCount:f.budgetContinuationCount,lastBudgetDeltaTokens:f.lastBudgetDeltaTokens,lastBudgetGlobalTokens:f.lastBudgetGlobalTokens,messages:b,finalText:f.finalText,thinkingBlocks:ot,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o,recoveryTrace:f.recoveryTrace});if(m){yield z("budget_continuation",m.recoveryDetail),f={...f,messages:m.messages,budgetContinuationCount:m.budgetContinuationCount,lastBudgetDeltaTokens:m.lastBudgetDeltaTokens,lastBudgetGlobalTokens:m.lastBudgetGlobalTokens,transition:m.transition};continue}if(f.finalText.trim()&&DR(f.lastTaskList)&&f.taskListReconciliationCount<1){let R=x.find(P=>P.function.name==="task")??(a??c).find(P=>P.function.name==="task");if(R){let P=jR(f.lastTaskList),Ne=I(x),de=gt(Ke(),Le);x=de.some(Is=>Is.function.name==="task")?de:[...de,R],f={...f,taskListReconciliationCount:f.taskListReconciliationCount+1,messages:[...b,{role:"assistant",content:f.finalText},{role:"user",content:P}],transition:{reason:"next_turn"}},ge=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:I(a??c),enabledToolNamesBefore:Ne,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield z("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if((e.buildVerificationGate??!0)&&hm(i)&&!f.artifactContract.buildVerified&&f.artifactContract.buildFailureEvidence.length>0&&x.some(R=>R.function.name==="exec")&&f.buildVerificationRecoveryCount<3){let R=NR(f.artifactContract);f={...f,buildVerificationRecoveryCount:f.buildVerificationRecoveryCount+1,messages:[...b,{role:"assistant",content:f.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},ge=!0,yield z("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let T=bc({inputMessages:i,messages:b,finalText:f.finalText,thinkingBlocks:ot,stopHookActive:f.stopHookActive,totalToolCallCount:$t,distinctToolNames:Oe,log:o});if(T){if(f.stopHookActive&&f.finalText.trim()===""){let R=$n({inputMessages:i,messages:T.messages,reason:"stop hook produced an empty response after tool use"});if(R){yield*je(R,{forcedStop:!0});return}}f={...f,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition};continue}if($t===0&&e.toolChoice!=="none"&&rl<1&&Sp(ye)){rl++;let R=I(a??c).join(", ");yield z("capability_denial_review","unverified capability denial; asking for verification or honest escalation"),f={...f,messages:[...b,{role:"assistant",content:ye},{role:"user",content:`Before declaring a capability missing, verify it. Your full tool list: [${R}]. If any tool there can fulfil the request \u2014 including exec running a script or OS command (e.g. PowerShell) \u2014 use it NOW. Only if none of these can work, state plainly WHICH capability is missing and what the user could enable \u2014 do not just refuse.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(e.freshEvidenceRequired&&!fu(ct)&&x.some(R=>or({identity:qm(R,R.function.name)}))&&e.toolChoice!=="none"&&ls<1&&ye.trim()!==""){ls++,ge=!0,yield z("fresh_evidence_required","evidence turn answered with no tool call; forcing one grounded retry"),f={...f,messages:[...b,{role:"assistant",content:ye},{role:"user",content:"This request requires FRESH tool evidence from this turn (reading the actual file, running the actual command, or generating the actual media). Do not answer from memory or invent content. Call the appropriate tool NOW and base your answer on its result."}],finalText:"",transition:{reason:"next_turn"}};continue}let g=Do(b,"the model ended with an empty response after tool use before completing the final status contract",{cleanStopWithFinalText:!0}),$=ds?jo==="zh"?"\u26A0\uFE0F \u8F93\u51FA\u7ECF\u591A\u6B21\u7EED\u5199\u540E\u4ECD\u88AB\u957F\u5EA6\u4E0A\u9650\u622A\u65AD,\u4EE5\u4E0B\u5185\u5BB9\u53EF\u80FD\u4E0D\u5B8C\u6574\u3002":"\u26A0\uFE0F Output was still cut off by the length limit after multiple continuation attempts; the content below may be incomplete.":null;yield*je($&&g?`${$}
|
|
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}
|
|
61
61
|
|
|
62
|
-
${g}`:g);return}let
|
|
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
63
|
|
|
64
|
-
${u.result.content}`,g=we(m.id,{ok:!0,payload:T,imageUrls:u.result.imageUrls,toolReferences:u.result.toolReferences,contentBlocks:u.result.contentBlocks,structuredContent:u.result.structuredContent,mcpMeta:u.result.mcpMeta,mcpIsError:u.result.mcpIsError});h(b,g),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!0,outputPreview:T.slice(0,2e3),durationMs:0,details:{type:m.function.name,reusedIdenticalCall:!0,repeatCount:u.repeatCount}}}if(Hn.some(u=>u.call.function.name==="exec"&&jm(u.call.function.arguments))){let u=I(x);b.push({role:"user",content:LR()}),yield{type:"tool_selection_policy",turnId:r,policyId:"ui_acceptance_after_preparation_guidance",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:I(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:u,suppressedToolNames:[],nextAction:"reuse-or-collect-reliable-ui-evidence"},yield z("ui_acceptance_after_preparation_guidance","reused successful browser preparation command")}for(let u of lt){let m=`${u.function.name}::${u.function.arguments}`;(Dn.get(m)??0)>=fn&&ee.push({name:u.function.name,reason:"invalid-arguments"}),ee.push({name:u.function.name,reason:"identical-repeat-policy"});let T=Math.max(ks.get(m)??0,Dn.get(m)??0),g=Dr(b,u.function.name,u.function.arguments),$=AR(g),R=Sl.has(u.id)?w0(T,u):$?`This exact tool call has been attempted ${T} times. Last error: ${$}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${T} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,P=we(u.id,{ok:!1,error:R});h(b,P),ke.push(u.id),yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:R}}for(let u of Rl){let m=`${u.function.name}::${u.function.arguments}`,T=f.commercialRetryBlocks.get(m);ee.push({name:u.function.name,reason:"commercial-retry-not-authorized"});let g=`This exact commercial tool call was not executed again because its typed failure contract did not authorize an automatic retry${T.stage?` at stage ${T.stage}`:""}. Billing state: ${T.billed===null?"unconfirmed":T.billed?"billed":"not billed"}; retry mode: ${T.retryMode}. Correct the request or prerequisite, obtain a new explicit user action when required, or report the blocker.`;h(b,we(u.id,{ok:!1,error:g})),ke.push(u.id),yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:g,details:{type:"commercial_retry_not_authorized",...T}}}if(lt.length>0&&zn.length===0&&Hn.length===0&<.every(u=>Sl.has(u.id))&&f.existingFileUpdateRecoveryCount<2){let u=I(x);x=gt(Ke(),Le);let m=I(x);jn=!0,ge=!0;let T=[...new Set(lt.map(g=>ns(g.function.arguments)).filter(g=>!!g))];b.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${T.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:I(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:m,suppressedToolNames:[],nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield z("existing_file_update_recovery",T.join(",")||"unknown"),f={...f,messages:b,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(lt.length>0){let u=lt[0],m=Dr(b,u.function.name,u.function.arguments),T={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(m?`The error was: "${m}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};b.push(T)}let Tg=an>=3&&f.repeatedToolFailureRecoveryCount<1;if(lt.length>0&&zn.length===0&&Hn.length===0&&!Tg){let u=Dm(lc(b,1),{availableToolNames:I(a??c),enabledToolNames:as(),toolCallNames:[...Oe].sort(),blockedToolCalls:Xr(ee)});yield*je(u);return}let El=[],Cs=[];for(let u of zn){let m=Tm({toolName:u.function.name,rawArguments:u.function.arguments});m?Cs.push({call:u,...m}):El.push(u)}for(let u of Cs){let m=u.call;ee.push({name:m.function.name,reason:"read-only-context-pack"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.warn(`read-only context-pack blocked: ${m.function.name} ${u.path}`)}Cs.length>0&&b.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let kg=new Set(x.map(u=>u.function.name)),ws=[],Ho=[];for(let u of El){let m=sg(u.function.name,u.function.arguments,kg);if(m){let T=`${u.function.name}::${u.function.arguments}`;if(ss.has(T)){ss.delete(T),o.info(`existing-file-update guard: verbatim re-issue admitted once for ${m.path}`),ws.push(u);continue}ss.add(T),Ho.push({call:u,...m})}else ws.push(u)}for(let u of Ho){let m=u.call;ee.push({name:m.function.name,reason:"existing-file-update-tool-required"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.info(`existing file update blocked: ${m.function.name} ${u.path}`)}if(Ho.length>0){let u=I(x);x=gt(Ke(),Le);let m=I(x);jn=!0,ge=!0;let T=[...new Set(Ho.map(g=>g.path))];b.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${T.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:I(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:m,suppressedToolNames:[],nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield z("existing_file_update_recovery",T.join(",")||"unknown"),f={...f,messages:b,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Al=[],Rs=[];for(let u of ws){let m=vm({state:f.artifactContract,inputMessages:i,toolName:u.function.name,rawArguments:u.function.arguments});m?Rs.push({call:u,...m}):Al.push(u)}for(let u of Rs){let m=u.call;ee.push({name:m.function.name,reason:"artifact-root-contract"}),Mc(f.artifactContract,{path:u.path,artifactRoot:u.artifactRoot,toolName:m.function.name}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},gs()&&(yield ms()),o.warn(`artifact root contract blocked: ${m.function.name}`)}Rs.length>0&&b.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let $l=[],xs=[];for(let u of Al){let m=Zp({inputMessages:i,messages:b,toolCall:u});m?xs.push({call:u,error:m}):$l.push(u)}for(let u of xs){let m=u.call;ee.push({name:m.function.name,reason:"premature-completion-artifact"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.info(`premature completion artifact blocked: ${m.function.name}`)}xs.length>0&&b.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let Cg=new Set(x.map(u=>u.function.name)),Pl=[],Vo=[];for(let u of $l)Cg.has(u.function.name)?Pl.push(u):Vo.push(u);for(let u of Vo){let m=`Tool "${u.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;ee.push({name:u.function.name,reason:"not-offered"}),h(b,we(u.id,{ok:!1,error:m})),ke.push(u.id),Oe.add(u.function.name),o.warn(`unoffered tool call suppressed: ${u.function.name}`)}if(Vo.length>0&&f.notOfferedToolRecoveryCount<1){let u=[...new Set(Vo.map(P=>P.function.name))].sort(),m=u.filter(P=>Lo.has(P)&&!cn.has(P)),T=jn&&u.includes("write"),g=u.filter(P=>Le.has(P)),R=(a??c).filter(P=>u.includes(P.function.name));if(m.length>0)f.notOfferedToolRecoveryCount+=1,ge=!0,b.push({role:"user",content:`The full schema for ${m.map(P=>`\`${P}\``).join(", ")} was not loaded. If you still select that capability, call \`${si}\` with the exact name first; do not guess its arguments.`}),yield z("deferred_tool_schema_not_loaded",m.join(","));else if(g.length>0)f.notOfferedToolRecoveryCount+=1,ge=!0,b.push({role:"user",content:`You retried ${g.map(P=>`\`${P}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:I(a??c),enabledToolNamesBefore:I(x),enabledToolNamesAfter:I(x),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield z("policy_suppressed_tool_retry_blocked",g.join(","));else if(!T&&R.length>0){let P=I(x),Ne=new Map(x.map(de=>[de.function.name,de]));for(let de of R)Ne.set(de.function.name,de);x=[...Ne.values()],f.notOfferedToolRecoveryCount+=1,ge=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:I(a??c),enabledToolNamesBefore:P,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},b.push({role:"user",content:`You called ${u.map(de=>`\`${de}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield z("available_tool_reenabled_after_not_offered_call",u.join(","))}}let Ml=[],Ss=[];for(let u of Pl){let m=yt.tools.find(g=>g.function.name===u.function.name),T=Bc(m,u.function.arguments);T?Ss.push({call:u,error:T}):Ml.push(u)}for(let u of Ss){let m=u.call;ee.push({name:m.function.name,reason:"invalid-arguments"}),h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),Oe.add(m.function.name),o.info(`invalid tool arguments blocked: ${m.function.name}`)}Ss.length>0&&b.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let Go=[],Es=[],Il=[],Ol=[],As=new Map,Nl=(u,m)=>{let T=As.get(u);As.set(u,T?`${T}
|
|
65
|
-
${m}`:m)};for(let u of Ml){if(u.function.name!=="exec"){Go.push(u);continue}let m=u,T=$R(m.function.arguments),g=T?IR(T):null;g&&(m={...m,function:{...m.function,arguments:Fm(m.function.arguments,g)}},Ol.push({originalCommand:T??"",rewrittenCommand:g}),Nl(u.id,`[Engine notice] Adjusted this command before execution: removed the blocking sleep prefix (a foreground sleep stalls the turn). Executed: ${g}`),T=g);let $=T?OR(T):null;if($?.action==="block")Es.push({call:m,error:$.error});else if($?.action==="rewrite"){let R={...m,function:{...m.function,arguments:Fm(m.function.arguments,$.command)}};Il.push({call:R,originalCommand:T??"",rewrittenCommand:$.command}),Nl(u.id,`[Engine notice] Adjusted this command before execution: appended --strictPort so a busy port cannot fall back onto reserved frontend port ${es}. Executed: ${$.command}`),Go.push(R)}else Go.push(m)}for(let u of Ol)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:I(a??c),enabledToolNamesBefore:I(x),enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${u.originalCommand} -> ${u.rewrittenCommand}`);for(let u of Il){let m=I(x);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:I(a??c),enabledToolNamesBefore:m,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${u.originalCommand} -> ${u.rewrittenCommand}`)}for(let u of Es){let m=u.call;ee.push({name:m.function.name,reason:"reserved-frontend-port"});let T=I(x);h(b,we(m.id,{ok:!1,error:u.error})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error,details:{type:m.function.name,error:"reserved_frontend_port",reservedPort:es}},o.info(`reserved frontend port preflight blocked: ${m.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:I(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}Es.length>0&&b.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let Vn=[],un=[];for(let u of Go){if(u.function.name!=="read"){Vn.push(u);continue}let m=zc(u.function.arguments);if(!m){Vn.push(u);continue}let T=Te(m),g=tg(T);if((f.fileReadCounts.get(T)??0)>=g){let $=f.fileReadSignatures.get(T),R=Gm(m);if($&&R&&(R.mtimeMs!==$.mtimeMs||R.sizeBytes!==$.sizeBytes)){o.info(`read cycle exemption: ${T} changed since last counted read, cap reset`),f.fileReadCounts.set(T,0),Vn.push(u);continue}un.push({call:u,filePath:T,maxReads:g})}else Vn.push(u)}for(let u of un){let m=u.call,T=`Read cycle policy blocked another read of "${u.filePath}" after ${u.maxReads} successful reads in this turn. Stop rereading the same large document. ${Dc(u.filePath)}`;ee.push({name:m.function.name,reason:"read-cycle-policy"}),f.fileReadCycleBlockedPaths.add(u.filePath),h(b,we(m.id,{ok:!1,error:T})),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:T},o.info(`read cycle blocked: ${u.filePath}`)}if(un.length>0){let u=[...new Set(un.map(g=>`${g.filePath} (max ${g.maxReads})`))].join(", "),m=[...new Set(un.map(g=>Dc(g.filePath)))].join(" ");if(b.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${u}. Do not retry the read with a different path spelling. ${m} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),x.some(g=>Wm(g.function.name))&&(f.persistedLongHorizonStateRecovered||un.some(g=>Kc(g.filePath)))){let g=I(x),$=g.filter(R=>s0.has(R)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:I(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},b.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${$.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield z("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(d0(ee,f.fileReadCycleBlockedPaths,f.persistedLongHorizonStateRecovered,f.maintainedDocuments)){yield*je("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let $s=im(Vn,f.toolFailureCounts,f.variantReassertedSignatures),Fl=$s.allowed,ut=Fl.slice(0,nt);for(let u of ut){if(!Hm(u,f))continue;let m=tt(u.function.arguments),T=typeof m?.taskId=="string"?m.taskId:void 0;!m||!T||typeof m.waitMs=="number"||(u.function.arguments=JSON.stringify({...m,waitMs:KR(f.backgroundAgentPollCounts.get(T)??0)}))}let Ll=Fl.slice(ut.length);if($s.blocked.length>0){for(let u of $s.blocked){let m=u.call;ee.push({name:m.function.name,reason:"variant-failure-policy"});let T=we(m.id,{ok:!1,error:u.error});h(b,T),ke.push(m.id),yield{type:"tool_result",turnId:r,callId:m.id,name:m.function.name,ok:!1,error:u.error},o.info(`variant tool blocked: ${m.function.name} failed ${u.failCount}x with different args`)}b.push(am())}if(Ll.length>0){let u=`This model round proposed more than ${nt} tool calls. Only the first ${nt} were executed; re-issue any still-needed calls in the next round.`;for(let m of Ll){ee.push({name:m.function.name,reason:"per-round-tool-call-limit"});let T=we(m.id,{ok:!1,error:u});h(b,T),ke.push(m.id)}b.push({role:"user",content:u})}for(let u of ut){let m=u.function.arguments,T=x.find($=>$.function.name===u.function.name);if(T?.backfillObservableInput)try{let $=JSON.parse(u.function.arguments),R={...$};T.backfillObservableInput(R),Object.keys(R).some(Ne=>!(Ne in $))&&(m=JSON.stringify(R))}catch{}let g={sequence:ct.length,callId:u.id,name:u.function.name,identity:qm(T,u.function.name),status:"running",arguments:m};ct.push(g),Zc.set(u.id,g),yield{type:"tool_call",turnId:r,callId:u.id,name:u.function.name,...T?.meta?.displayName?.fallback?.trim()?{displayName:T.meta.displayName.fallback.trim()}:{},arguments:m,inputSummary:uc(m)},Qc.add(u.function.name),el++}let wg=new Map(f.toolFailureCounts),Wo=null,It;try{let u=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:y,sessionId:s,turnId:r,log:o,signal:v,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Ql,executionTimeoutMsByTool:new Map(x.flatMap(g=>{let $=g.meta?.executionTimeoutMs;return typeof $=="number"&&Number.isFinite($)&&$>0?[[g.function.name,$]]:[]})),contextState:f.contentReplacementState});for(let g of ut)u.addTool(g);let m=!1;for await(let g of u.getRemainingResults()){let $=HR(g.details),R=Qm(g.details),P=Zc.get(g.callId);P&&(P.status=g.blocked||R==="not-applied"?"blocked":!g.ok||R==="indeterminate"?"failed":"succeeded",!g.ok&&typeof g.error=="string"&&g.error.trim()&&(P.error=g.error),R==="indeterminate"&&!P.error&&(P.error="MCP action outcome is indeterminate; completion is not verified."),(!g.ok||R==="indeterminate")&&(P.failureKind=pu(g)));let Ne=Im(g);if(Ne){if(ee.push({name:g.toolName,reason:Ne}),g.toolName==="exec"&&Ne==="confirmation-timeout"){let S=I(x);b.push({role:"user",content:"Exec confirmation timed out. The built-in tool remains available, but this exact action did not receive approval. Do not claim it succeeded. Continue with another authorized approach only when it can genuinely complete the same user goal, ask_user when approval is required, or report the confirmation blocker."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:I(a??c),enabledToolNamesBefore:S,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"use-an-authorized-approach-or-report-confirmation-blocker"}}if(g.toolName==="exec"&&Ne==="global-process-kill-blocked"){let S=I(x);b.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:I(a??c),enabledToolNamesBefore:S,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}g.blocked&&(yield{type:"tool_blocked",turnId:r,callId:g.callId,name:g.toolName,reason:g.blockReason??"blocked"});let de=As.get(g.callId);if(de){let S=g.message;typeof S.content=="string"&&(S.content=`${de}
|
|
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&<.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}
|
|
66
66
|
|
|
67
|
-
${S.content}`)}if(g.ok&&g.toolName===si){let S=du(g.details),j=e.refreshTools?new Set(e.refreshTools().map(fe=>fe.function.name)):void 0,Y=[],le=[],Ce=[];for(let fe of S)!Q.get(fe)||j&&!j.has(fe)?Ce.push(fe):!Lo.has(fe)||cn.has(fe)?le.push(fe):(cn.add(fe),e.loadedDeferredToolNames?.add(fe),Y.push(fe));let Xe=nl(Ke(),j);x=nn(gt(Xe,Le),Ke());let Nt=g.message;Nt.content=JSON.stringify({loaded:Y,alreadyResident:le,unavailable:Ce}),g.details={type:"tool_schema_load",requestedToolNames:S,loaded:Y,alreadyResident:le,unavailable:Ce},o.info({turnId:r,loaded:Y,alreadyResident:le,unavailable:Ce},"tool schemas materialized by Agent selection")}{let S=g.message;e.sanitizeToolResultMedia&&(Array.isArray(S.imageUrls)||Array.isArray(S.audioUrls)||Array.isArray(S.videoUrls))&&await e.sanitizeToolResultMedia(S)}if(h(b,g.message),We&&jc(g.toolName,We)){let S=Gc(Se(g.toolName));We.scope==="interaction-step"?$?.scope==="interaction-step"?(We=$,Fn=!1,Ln=!1):R==="committed"||R===void 0&&(S==="computer_act"||S==="act")?Ln=!0:Fn=!0:Fn=!0}!It&&$&&(It=$,It&&(We=It)),ke.push(g.callId);let Is=VR(g,f);g.blocked||(Oe.add(g.toolName),$t++);let jl=g.ok&&Lr(g);Is||cm({toolFailureCounts:f.toolFailureCounts,toolName:g.toolName,toolArguments:ut.find(S=>S.id===g.callId)?.function.arguments,ok:g.ok,softEmpty:jl});let _t=ce.find(S=>S.id===g.callId);if(!g.ok&&_t){let S=sm(g.details),j=`${_t.function.name}::${_t.function.arguments}`;g.blocked||f.identicalFailureCounts.set(j,(f.identicalFailureCounts.get(j)??0)+1),S&&!(S.retryable&&S.safeToRetry&&S.automaticRetryAuthorized)&&f.commercialRetryBlocks.set(j,{billed:S.billed,retryMode:S.retryMode,...S.stage?{stage:S.stage}:{}})}if(g.ok&&_t&&(f.commercialRetryBlocks.delete(`${_t.function.name}::${_t.function.arguments}`),f.identicalFailureCounts.delete(`${_t.function.name}::${_t.function.arguments}`)),g.ok&&ZR.has(Se(g.toolName))&&O0(f),g.ok&&Wm(g.toolName)){let S=ut.find(Y=>Y.id===g.callId),j=S?ns(S.function.arguments):void 0;if(j){let Y=Te(j);if(f.longHorizonStateMaintenanceRequiredFiles.has(Y)){let le=Xc(f.maintainedDocuments,Y,S?.function.arguments??"");le.ok?f.longHorizonStateMaintenanceWrittenFiles.add(Y):(ee.push({name:g.toolName,reason:"benchmark-state-invalid-content"}),b.push({role:"user",content:`Benchmark-state maintenance write for ${Y} is incomplete: ${le.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(g.ok&&!jl&&(qc.has(g.toolName)||g.toolName==="exec"&&g.details?.type==="exec_background"||g.toolName==="exec"&&jm(ut.find(S=>S.id===g.callId)?.function.arguments??""))){let S=ut.find(Y=>Y.id===g.callId),j=typeof g.message?.content=="string"?g.message.content:"";if(S&&j){let Y=Array.isArray(g.message.imageUrls)?g.message.imageUrls.filter(Gn=>typeof Gn=="string"):void 0,le=Array.isArray(g.message.toolReferences)?g.message.toolReferences.filter(Gn=>typeof Gn=="string"):void 0,Ce=Array.isArray(g.message.contentBlocks)?g.message.contentBlocks:void 0,Xe=g.message.structuredContent,Nt=g.message.mcpMeta,fe=g.message.mcpIsError;f.identicalSuccessfulToolResults.set(`${S.function.name}::${S.function.arguments}`,{content:j,imageUrls:Y,toolReferences:le,contentBlocks:Ce,...Xe!==void 0?{structuredContent:Xe}:{},...Nt!==void 0?{mcpMeta:Nt}:{},...typeof fe=="boolean"?{mcpIsError:fe}:{}})}}if(g.toolName==="agent"){let S=on(g.details,"agentId"),j=on(g.details,"status"),Y=Zr(g.details,"background");g.ok&&S&&Y===!0&&j==="running"&&rn(f).add(S)}if(g.toolName==="task"){let S=YR(g.details);S&&(f.lastTaskList=S);let j=on(g.details,"taskId"),Y=Zr(g.details,"running"),le=on(g.details,"lifecycle"),Ce=on(g.details,"action");if(j&&(Ce==="cancel"||Y===!1||le&&le!=="running"&&le!=="pending"))rn(f).delete(j),f.backgroundAgentPollCounts.delete(j),f.backgroundAgentNoOutputPollCounts.delete(j),f.stalledBackgroundAgentTasks.delete(j);else if(j&&Ce==="output"&&Y===!0&&rn(f).has(j)){let Xe=(f.backgroundAgentPollCounts.get(j)??0)+1;f.backgroundAgentPollCounts.set(j,Xe),Xe>=Vm&&f.stalledBackgroundAgentTasks.set(j,`still running after ${Xe} bounded poll(s)`);let Nt=typeof g.message?.content=="string"?g.message.content:"",fe=Zr(g.details,"hasOutput");if(fe!==void 0?fe===!1:JR(Nt)){let Ns=(f.backgroundAgentNoOutputPollCounts.get(j)??0)+1;f.backgroundAgentNoOutputPollCounts.set(j,Ns);let Jo=zR(g.details,"elapsedSeconds")??XR(Nt);(Jo!==void 0&&Jo>=GR||Jo===void 0&&Ns>=WR)&&f.stalledBackgroundAgentTasks.set(j,`no output after ${Jo??"unknown"}s across ${Ns} poll(s)`)}else f.backgroundAgentNoOutputPollCounts.delete(j),Xe<Vm&&f.stalledBackgroundAgentTasks.delete(j)}}if(g.ok&&g.toolName==="read"){let S=ut.find(j=>j.id===g.callId);if(S){let j=zc(S.function.arguments);if(j){let Y=Te(j),le=f.fileReadCounts.get(Y)??0;f.fileReadCounts.set(Y,le+1);let Ce=Gm(j);Ce&&f.fileReadSignatures.set(Y,Ce);let Xe=typeof g.message?.content=="string"?g.message.content:"";m=k0(f,j,Xe,f.turnCount,g.details)||m}}}yield mu(r,g);for(let S of gu(r,g))yield S;for(let S of _u({turnId:r,result:g,toolCalls:ce}))yield S;let Os=ce.find(S=>S.id===g.callId),xg=typeof g.message?.content=="string"?g.message.content:"";if(Os){Cm({state:f.artifactContract,inputMessages:i,toolName:g.toolName,rawArguments:Os.function.arguments,ok:g.ok,content:xg,details:g.details}),gs()&&(yield ms());let S=FR(g.toolName,Os.function.arguments);if(S){let j=Im(g),Y=g.ok&&!Lr(g);Y&&rs.delete(S);let le=Y||j?0:(rs.get(S)??0)+1;if(le>0&&rs.set(S,le),le===Lm){let Ce=S.startsWith("exec:")?"exec":"edit";f.recoveryTrace.set(`no_progress_observed:${Ce}`,(f.recoveryTrace.get(`no_progress_observed:${Ce}`)??0)+1),tl.has(S)||(tl.add(S),b.push({role:"user",content:`You have now run ${Lm} consecutive failed or empty variations of the same action (${S}) without completing the user's request. Stop this approach: summarize what you tried and why it failed, then either take a FUNDAMENTALLY different route or report the blocker honestly. Do not run another variation of the same command family.`}),yield z("no_progress_nudge",S))}}}!Wo&&ug&&ri(g.toolName,"stt")&&g.ok&&(Wo=wR(i,g))}if(jn&&(x=gt(Ke(),Le),jn=!1),Ln&&!It){let g=I(x);x=gt(Ke(),Le),ge=!1,b.push({role:"user",content:"The grounded action allowed by the connector's interaction-step control has returned. Continue from that action result. A new observation is allowed only if the action advanced the interaction step; do not repeat the exhausted observation step."}),yield{type:"tool_selection_policy",turnId:r,policyId:"mcp_interaction_step_advanced",intent:"tool_recovery",reason:"mcp-interaction-step-action-returned",availableToolNames:I(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:I(x),suppressedToolNames:[],nextAction:"continue-from-grounded-action-result"},yield z("mcp_interaction_step_advanced",We?.reason??"mcp-interaction-step-blocked"),We=void 0,Ln=!1}else if(Fn){let g=I(x);x=nn([],E),ge=!1,b.push({role:"user",content:"The selected MCP connector's bounded cleanup tool has now returned. Do not invoke another tool in this turn. Summarize only the verified evidence already returned, report the remaining blocker clearly, and do not claim the requested action completed."}),yield{type:"tool_selection_policy",turnId:r,policyId:"mcp_turn_cleanup_completed",intent:"tool_recovery",reason:"mcp-turn-cleanup-returned",availableToolNames:I(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:I(x),suppressedToolNames:Om(g,I(x)),nextAction:"report-verified-evidence-and-blocker"},yield z("mcp_turn_cleanup_completed",We?.reason??"mcp-turn-blocked"),We=void 0,Fn=!1}else if(It){let g=It;Ln=!1;let $=I(x),R=x.filter(P=>jc(P.function.name,g));x=nn(R,E),ge=R.length>0,b.push({role:"user",content:g.scope==="interaction-step"?R.length>0?g.reason.includes("observation")?"The selected MCP connector exhausted the current interaction step's observation budget. Do not observe again. Use exactly one protocol-declared continuation: perform a grounded action from existing evidence, or release control when no safe grounded action exists. Never claim completion without verified action evidence.":"The selected MCP connector requires another bounded interaction step. Continue only through one protocol-declared tool using the structured state returned by the connector. Do not switch to an undeclared fallback or claim completion before the connector returns verified completion evidence.":"The selected MCP connector blocked the current interaction step and exposed no available continuation tool. Report the incomplete state and blocker explicitly; do not claim completion.":x.length>0?"The selected MCP connector returned a structured, turn-scoped, non-retryable block. Invoke the single remaining connector cleanup tool exactly once, then report only verified evidence and the blocker. Do not retry the blocked operation or claim completion.":"The selected MCP connector returned a structured, turn-scoped, non-retryable block and exposed no available cleanup tool. Do not invoke another tool in this turn. Report only verified evidence and the blocker; do not claim completion."}),yield{type:"tool_selection_policy",turnId:r,policyId:g.scope==="interaction-step"?"mcp_interaction_step_execution_block":"mcp_turn_execution_block",intent:"tool_recovery",reason:g.scope==="interaction-step"?"mcp-interaction-step-non-retryable":"mcp-turn-non-retryable",availableToolNames:I(a??c),enabledToolNamesBefore:$,enabledToolNamesAfter:I(x),suppressedToolNames:Om($,I(x)),nextAction:R.length>0?g.scope==="interaction-step"?"invoke-grounded-action-or-release":"invoke-bounded-connector-cleanup":"report-verified-evidence-and-blocker"},yield z(g.scope==="interaction-step"?"mcp_interaction_step_execution_block":"mcp_turn_execution_block",g.reason)}if(m){let g=b0(r,f.maintainedDocuments,f.fileReadCounts,f.turnCount);g&&(yield g);for(let P of T0(r,f.maintainedDocuments))yield P;let $=a0(f.maintainedDocuments,f.turnCount),R=x.some(P=>Uc.has(P.function.name));if($&&R){f.longHorizonStateMaintenanceRequiredFiles=new Set(rg(f.maintainedDocuments).map(Te));for(let P of x)Uc.has(P.function.name)||Le.add(P.function.name);x=gt(x,Le),ge=!0,b.push({role:"user",content:$}),yield z("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let T=u0(f.maintainedDocuments);if(T.length>0&&f.longHorizonStateIntegrityRecoveryCount<r0){let g=T.map($=>`${At($.path)}: ${$.reason}`).join("; ");f={...f,longHorizonStateIntegrityRecoveryCount:f.longHorizonStateIntegrityRecoveryCount+1,messages:[...b,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+g+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},ge=!0,yield z("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(c0(f)){yield*je("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(u){let m=u instanceof Error?u.message:String(u);yield*Je(m,"TOOL_EXECUTION_ERROR");return}if(Wo){yield*je(Wo);return}b.push(...lm({toolFailureCounts:f.toolFailureCounts,snapshot:wg})),Be=Zo(Be,{replayMessages:b,completedToolCallIds:[...Be.completedToolCallIds,...ke],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&ce.length>0&&(cs=!0);let Rg=ce.length>0&&ce.every(u=>{let m=b.find(g=>g?.role==="tool"&&g?.tool_call_id===u.id);if(!m)return!0;let T=m.content;return typeof T=="string"&&T.startsWith("Error: ")}),Ot=f.consecutiveFailedRounds,Ps=f.repeatedToolFailureRecoveryCount;if(Rg){if(Ot+=1,Ot>=eu){if(an>=3&&f.repeatedToolFailureRecoveryCount<1){let R=bc({inputMessages:i,messages:b,finalText:f.finalText,thinkingBlocks:[],stopHookActive:f.stopHookActive,totalToolCallCount:$t,distinctToolNames:Oe,log:o});if(R?.reason==="explicit_required_file_verification"||R?.reason==="explicit_extra_file_verification"){yield z("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),f={...f,messages:R.messages,stopHookActive:R.stopHookActive,transition:R.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:f.repeatedToolFailureRecoveryCount+1};continue}}if(f.repeatedToolFailureRecoveryCount<1){let R=$p(b,ct.at(-1)?.failureKind);if(R){yield z("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),f={...f,messages:[...b,R],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:f.repeatedToolFailureRecoveryCount+1};continue}}let u=`repeated tool failures (${Ot} rounds in a row)`,m=$n({inputMessages:i,messages:b,reason:`${u} before all required files were produced`}),T=f.finalText.trim()?f.finalText:lc(b,Ot),g=m?`${T}
|
|
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
68
|
|
|
69
|
-
${m}`:T
|
|
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
70
|
|
|
71
|
-
${u}`:m);return}if(
|
|
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
72
|
|
|
73
|
-
${u}`:m);return}f={messages:b,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:
|
|
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};
|