@sunerpy/kiro-provider 3.6.0 → 3.7.0
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/cli.js +2 -2
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -54,7 +54,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
54
54
|
missingProperty: ${N},
|
|
55
55
|
depsCount: ${G},
|
|
56
56
|
deps: ${C}}`};var DmI={keyword:"dependencies",type:"object",schemaType:"object",error:yp.error,code(I){let[G,C]=qmI(I);Kp(I,G),kp(I,C)}};function qmI({schema:I}){let G={},C={};for(let N in I){if(N==="__proto__")continue;let Y=Array.isArray(I[N])?G:C;Y[N]=I[N]}return[G,C]}function Kp(I,G=I.schema){let{gen:C,data:N,it:Y}=I;if(Object.keys(G).length===0)return;let Z=C.let("missing");for(let W in G){let b=G[W];if(b.length===0)continue;let l=(0,i0.propertyInData)(C,N,W,Y.opts.ownProperties);if(I.setParams({property:W,depsCount:b.length,deps:b.join(", ")}),Y.allErrors)C.if(l,()=>{for(let Q of b)(0,i0.checkReportMissingProp)(I,Q)});else C.if(BH._`${l} && (${(0,i0.checkMissingProp)(I,b,Z)})`),(0,i0.reportMissingProp)(I,Z),C.else()}}yp.validatePropertyDeps=Kp;function kp(I,G=I.schema){let{gen:C,data:N,keyword:Y,it:Z}=I,W=C.name("valid");for(let b in G){if((0,zmI.alwaysValidSchema)(Z,G[b]))continue;C.if((0,i0.propertyInData)(C,N,b,Z.opts.ownProperties),()=>{let l=I.subschema({keyword:Y,schemaProp:b},W);I.mergeValidEvaluated(l,W)},()=>C.var(W,!0)),I.ok(W)}}yp.validateSchemaDeps=kp;yp.default=DmI});var qp=z((Dp)=>{Object.defineProperty(Dp,"__esModule",{value:!0});var zp=hI(),BmI=AI(),amI={message:"property name must be valid",params:({params:I})=>zp._`{propertyName: ${I.propertyName}}`},xmI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:amI,code(I){let{gen:G,schema:C,data:N,it:Y}=I;if((0,BmI.alwaysValidSchema)(Y,C))return;let Z=G.name("valid");G.forIn("key",N,(W)=>{I.setParams({propertyName:W}),I.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},Z),G.if((0,zp.not)(Z),()=>{if(I.error(!0),!Y.allErrors)G.break()})}),I.ok(Z)}};Dp.default=xmI});var aH=z((Up)=>{Object.defineProperty(Up,"__esModule",{value:!0});var g2=nC(),hN=hI(),SmI=SC(),K2=AI(),nmI={message:"must NOT have additional properties",params:({params:I})=>hN._`{additionalProperty: ${I.additionalProperty}}`},TmI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nmI,code(I){let{gen:G,schema:C,parentSchema:N,data:Y,errsCount:Z,it:W}=I;if(!Z)throw Error("ajv implementation error");let{allErrors:b,opts:l}=W;if(W.props=!0,l.removeAdditional!=="all"&&(0,K2.alwaysValidSchema)(W,C))return;let Q=(0,g2.allSchemaProperties)(N.properties),L=(0,g2.allSchemaProperties)(N.patternProperties);m(),I.ok(hN._`${Z} === ${SmI.default.errors}`);function m(){G.forIn("key",Y,(H)=>{if(!Q.length&&!L.length)R(H);else G.if(V(H),()=>R(H))})}function V(H){let d;if(Q.length>8){let O=(0,K2.schemaRefOrVal)(W,N.properties,"properties");d=(0,g2.isOwnProperty)(G,O,H)}else if(Q.length)d=(0,hN.or)(...Q.map((O)=>hN._`${H} === ${O}`));else d=hN.nil;if(L.length)d=(0,hN.or)(d,...L.map((O)=>hN._`${(0,g2.usePattern)(I,O)}.test(${H})`));return(0,hN.not)(d)}function X(H){G.code(hN._`delete ${Y}[${H}]`)}function R(H){if(l.removeAdditional==="all"||l.removeAdditional&&C===!1){X(H);return}if(C===!1){if(I.setParams({additionalProperty:H}),I.error(),!b)G.break();return}if(typeof C=="object"&&!(0,K2.alwaysValidSchema)(W,C)){let d=G.name("valid");if(l.removeAdditional==="failing")h(H,d,!1),G.if((0,hN.not)(d),()=>{I.reset(),X(H)});else if(h(H,d),!b)G.if((0,hN.not)(d),()=>G.break())}}function h(H,d,O){let F={keyword:"additionalProperties",dataProp:H,dataPropType:K2.Type.Str};if(O===!1)Object.assign(F,{compositeRule:!0,createErrors:!1,allErrors:!1});I.subschema(F,d)}}};Up.default=TmI});var xp=z((ap)=>{Object.defineProperty(ap,"__esModule",{value:!0});var imI=eZ(),jp=nC(),xH=AI(),Bp=aH(),PmI={keyword:"properties",type:"object",schemaType:"object",code(I){let{gen:G,schema:C,parentSchema:N,data:Y,it:Z}=I;if(Z.opts.removeAdditional==="all"&&N.additionalProperties===void 0)Bp.default.code(new imI.KeywordCxt(Z,Bp.default,"additionalProperties"));let W=(0,jp.allSchemaProperties)(C);for(let m of W)Z.definedProperties.add(m);if(Z.opts.unevaluated&&W.length&&Z.props!==!0)Z.props=xH.mergeEvaluated.props(G,(0,xH.toHash)(W),Z.props);let b=W.filter((m)=>!(0,xH.alwaysValidSchema)(Z,C[m]));if(b.length===0)return;let l=G.name("valid");for(let m of b){if(Q(m))L(m);else{if(G.if((0,jp.propertyInData)(G,Y,m,Z.opts.ownProperties)),L(m),!Z.allErrors)G.else().var(l,!0);G.endIf()}I.it.definedProperties.add(m),I.ok(l)}function Q(m){return Z.opts.useDefaults&&!Z.compositeRule&&C[m].default!==void 0}function L(m){I.subschema({keyword:"properties",schemaProp:m,dataProp:m},l)}}};ap.default=PmI});var sp=z((Tp)=>{Object.defineProperty(Tp,"__esModule",{value:!0});var Mp=nC(),k2=hI(),Sp=AI(),np=AI(),$mI={keyword:"patternProperties",type:"object",schemaType:"object",code(I){let{gen:G,schema:C,data:N,parentSchema:Y,it:Z}=I,{opts:W}=Z,b=(0,Mp.allSchemaProperties)(C),l=b.filter((h)=>(0,Sp.alwaysValidSchema)(Z,C[h]));if(b.length===0||l.length===b.length&&(!Z.opts.unevaluated||Z.props===!0))return;let Q=W.strictSchema&&!W.allowMatchingProperties&&Y.properties,L=G.name("valid");if(Z.props!==!0&&!(Z.props instanceof k2.Name))Z.props=(0,np.evaluatedPropsToName)(G,Z.props);let{props:m}=Z;V();function V(){for(let h of b){if(Q)X(h);if(Z.allErrors)R(h);else G.var(L,!0),R(h),G.if(L)}}function X(h){for(let H in Q)if(new RegExp(h).test(H))(0,Sp.checkStrictMode)(Z,`property ${H} matches pattern ${h} (use allowMatchingProperties)`)}function R(h){G.forIn("key",N,(H)=>{G.if(k2._`${(0,Mp.usePattern)(I,h)}.test(${H})`,()=>{let d=l.includes(h);if(!d)I.subschema({keyword:"patternProperties",schemaProp:h,dataProp:H,dataPropType:np.Type.Str},L);if(Z.opts.unevaluated&&m!==!0)G.assign(k2._`${m}[${H}]`,!0);else if(!d&&!Z.allErrors)G.if((0,k2.not)(L),()=>G.break())})})}}};Tp.default=$mI});var Pp=z((ip)=>{Object.defineProperty(ip,"__esModule",{value:!0});var _mI=AI(),rmI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(I){let{gen:G,schema:C,it:N}=I;if((0,_mI.alwaysValidSchema)(N,C)){I.fail();return}let Y=G.name("valid");I.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Y),I.failResult(Y,()=>I.reset(),()=>I.error())},error:{message:"must NOT be valid"}};ip.default=rmI});var $p=z((fp)=>{Object.defineProperty(fp,"__esModule",{value:!0});var emI=nC(),IVI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:emI.validateUnion,error:{message:"must match a schema in anyOf"}};fp.default=IVI});var _p=z((tp)=>{Object.defineProperty(tp,"__esModule",{value:!0});var y2=hI(),CVI=AI(),NVI={message:"must match exactly one schema in oneOf",params:({params:I})=>y2._`{passingSchemas: ${I.passing}}`},YVI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:NVI,code(I){let{gen:G,schema:C,parentSchema:N,it:Y}=I;if(!Array.isArray(C))throw Error("ajv implementation error");if(Y.opts.discriminator&&N.discriminator)return;let Z=C,W=G.let("valid",!1),b=G.let("passing",null),l=G.name("_valid");I.setParams({passing:b}),G.block(Q),I.result(W,()=>I.reset(),()=>I.error(!0));function Q(){Z.forEach((L,m)=>{let V;if((0,CVI.alwaysValidSchema)(Y,L))G.var(l,!0);else V=I.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},l);if(m>0)G.if(y2._`${l} && ${W}`).assign(W,!1).assign(b,y2._`[${b}, ${m}]`).else();G.if(l,()=>{if(G.assign(W,!0),G.assign(b,m),V)I.mergeEvaluated(V,y2.Name)})})}}};tp.default=YVI});var op=z((rp)=>{Object.defineProperty(rp,"__esModule",{value:!0});var WVI=AI(),bVI={keyword:"allOf",schemaType:"array",code(I){let{gen:G,schema:C,it:N}=I;if(!Array.isArray(C))throw Error("ajv implementation error");let Y=G.name("valid");C.forEach((Z,W)=>{if((0,WVI.alwaysValidSchema)(N,Z))return;let b=I.subschema({keyword:"allOf",schemaProp:W},Y);I.ok(Y),I.mergeEvaluated(b)})}};rp.default=bVI});var CE=z((GE)=>{Object.defineProperty(GE,"__esModule",{value:!0});var p2=hI(),IE=AI(),QVI={message:({params:I})=>p2.str`must match "${I.ifClause}" schema`,params:({params:I})=>p2._`{failingKeyword: ${I.ifClause}}`},LVI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:QVI,code(I){let{gen:G,parentSchema:C,it:N}=I;if(C.then===void 0&&C.else===void 0)(0,IE.checkStrictMode)(N,'"if" without "then" and "else" is ignored');let Y=ep(N,"then"),Z=ep(N,"else");if(!Y&&!Z)return;let W=G.let("valid",!0),b=G.name("_valid");if(l(),I.reset(),Y&&Z){let L=G.let("ifClause");I.setParams({ifClause:L}),G.if(b,Q("then",L),Q("else",L))}else if(Y)G.if(b,Q("then"));else G.if((0,p2.not)(b),Q("else"));I.pass(W,()=>I.error(!0));function l(){let L=I.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},b);I.mergeEvaluated(L)}function Q(L,m){return()=>{let V=I.subschema({keyword:L},b);if(G.assign(W,b),I.mergeValidEvaluated(V,W),m)G.assign(m,p2._`${L}`);else I.setParams({ifClause:L})}}}};function ep(I,G){let C=I.schema[G];return C!==void 0&&!(0,IE.alwaysValidSchema)(I,C)}GE.default=LVI});var YE=z((NE)=>{Object.defineProperty(NE,"__esModule",{value:!0});var VVI=AI(),XVI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:I,parentSchema:G,it:C}){if(G.if===void 0)(0,VVI.checkStrictMode)(C,`"${I}" without "if" is ignored`)}};NE.default=XVI});var MH=z((ZE)=>{Object.defineProperty(ZE,"__esModule",{value:!0});var hVI=UH(),HVI=Fp(),wVI=jH(),dVI=Jp(),cVI=gp(),OVI=A2(),FVI=qp(),vVI=aH(),uVI=xp(),JVI=sp(),AVI=Pp(),gVI=$p(),KVI=_p(),kVI=op(),yVI=CE(),pVI=YE();function EVI(I=!1){let G=[AVI.default,gVI.default,KVI.default,kVI.default,yVI.default,pVI.default,FVI.default,vVI.default,OVI.default,uVI.default,JVI.default];if(I)G.push(HVI.default,dVI.default);else G.push(hVI.default,wVI.default);return G.push(cVI.default),G}ZE.default=EVI});var bE=z((WE)=>{Object.defineProperty(WE,"__esModule",{value:!0});var QG=hI(),DVI={message:({schemaCode:I})=>QG.str`must match format "${I}"`,params:({schemaCode:I})=>QG._`{format: ${I}}`},qVI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:DVI,code(I,G){let{gen:C,data:N,$data:Y,schema:Z,schemaCode:W,it:b}=I,{opts:l,errSchemaPath:Q,schemaEnv:L,self:m}=b;if(!l.validateFormats)return;if(Y)V();else X();function V(){let R=C.scopeValue("formats",{ref:m.formats,code:l.code.formats}),h=C.const("fDef",QG._`${R}[${W}]`),H=C.let("fType"),d=C.let("format");C.if(QG._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>C.assign(H,QG._`${h}.type || "string"`).assign(d,QG._`${h}.validate`),()=>C.assign(H,QG._`"string"`).assign(d,h)),I.fail$data((0,QG.or)(O(),F()));function O(){if(l.strictSchema===!1)return QG.nil;return QG._`${W} && !${d}`}function F(){let c=L.$async?QG._`(${h}.async ? await ${d}(${N}) : ${d}(${N}))`:QG._`${d}(${N})`,v=QG._`(typeof ${d} == "function" ? ${c} : ${d}.test(${N}))`;return QG._`${d} && ${d} !== true && ${H} === ${G} && !${v}`}}function X(){let R=m.formats[Z];if(!R){O();return}if(R===!0)return;let[h,H,d]=F(R);if(h===G)I.pass(c());function O(){if(l.strictSchema===!1){m.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${Z}" ignored in schema at path "${Q}"`}}function F(v){let J=v instanceof RegExp?(0,QG.regexpCode)(v):l.code.formats?QG._`${l.code.formats}${(0,QG.getProperty)(Z)}`:void 0,u=C.scopeValue("formats",{key:Z,ref:v,code:J});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,QG._`${u}.validate`];return["string",v,u]}function c(){if(typeof R=="object"&&!(R instanceof RegExp)&&R.async){if(!L.$async)throw Error("async format in sync schema");return QG._`await ${d}(${N})`}return typeof H=="function"?QG._`${d}(${N})`:QG._`${d}.test(${N})`}}}};WE.default=qVI});var SH=z((lE)=>{Object.defineProperty(lE,"__esModule",{value:!0});var jVI=bE(),BVI=[jVI.default];lE.default=BVI});var nH=z((QE)=>{Object.defineProperty(QE,"__esModule",{value:!0});QE.contentVocabulary=QE.metadataVocabulary=void 0;QE.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];QE.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var TH=z((VE)=>{Object.defineProperty(VE,"__esModule",{value:!0});var MVI=pH(),SVI=DH(),nVI=MH(),TVI=SH(),mE=nH(),sVI=[MVI.default,SVI.default,(0,nVI.default)(),TVI.default,mE.metadataVocabulary,mE.contentVocabulary];VE.default=sVI});var HE=z((RE)=>{Object.defineProperty(RE,"__esModule",{value:!0});RE.DiscrError=void 0;var XE;(function(I){I.Tag="tag",I.Mapping="mapping"})(XE||(RE.DiscrError=XE={}))});var E2=z((dE)=>{Object.defineProperty(dE,"__esModule",{value:!0});var xb=hI(),sH=HE(),wE=q0(),PVI=IW(),fVI=AI(),$VI={message:({params:{discrError:I,tagName:G}})=>I===sH.DiscrError.Tag?`tag "${G}" must be string`:`value of tag "${G}" must be in oneOf`,params:({params:{discrError:I,tag:G,tagName:C}})=>xb._`{error: ${I}, tag: ${C}, tagValue: ${G}}`},tVI={keyword:"discriminator",type:"object",schemaType:"object",error:$VI,code(I){let{gen:G,data:C,schema:N,parentSchema:Y,it:Z}=I,{oneOf:W}=Y;if(!Z.opts.discriminator)throw Error("discriminator: requires discriminator option");let b=N.propertyName;if(typeof b!="string")throw Error("discriminator: requires propertyName");if(N.mapping)throw Error("discriminator: mapping is not supported");if(!W)throw Error("discriminator: requires oneOf keyword");let l=G.let("valid",!1),Q=G.const("tag",xb._`${C}${(0,xb.getProperty)(b)}`);G.if(xb._`typeof ${Q} == "string"`,()=>L(),()=>I.error(!1,{discrError:sH.DiscrError.Tag,tag:Q,tagName:b})),I.ok(l);function L(){let X=V();G.if(!1);for(let R in X)G.elseIf(xb._`${Q} === ${R}`),G.assign(l,m(X[R]));G.else(),I.error(!1,{discrError:sH.DiscrError.Mapping,tag:Q,tagName:b}),G.endIf()}function m(X){let R=G.name("valid"),h=I.subschema({keyword:"oneOf",schemaProp:X},R);return I.mergeEvaluated(h,xb.Name),R}function V(){var X;let R={},h=d(Y),H=!0;for(let c=0;c<W.length;c++){let v=W[c];if((v===null||v===void 0?void 0:v.$ref)&&!(0,fVI.schemaHasRulesButRef)(v,Z.self.RULES)){let u=v.$ref;if(v=wE.resolveRef.call(Z.self,Z.schemaEnv.root,Z.baseId,u),v instanceof wE.SchemaEnv)v=v.schema;if(v===void 0)throw new PVI.default(Z.opts.uriResolver,Z.baseId,u)}let J=(X=v===null||v===void 0?void 0:v.properties)===null||X===void 0?void 0:X[b];if(typeof J!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${b}"`);H=H&&(h||d(v)),O(J,c)}if(!H)throw Error(`discriminator: "${b}" must be required`);return R;function d({required:c}){return Array.isArray(c)&&c.includes(b)}function O(c,v){if(c.const)F(c.const,v);else if(c.enum)for(let J of c.enum)F(J,v);else throw Error(`discriminator: "properties/${b}" must have "const" or "enum"`)}function F(c,v){if(typeof c!="string"||c in R)throw Error(`discriminator: "${b}" values must be unique strings`);R[c]=v}}}};dE.default=tVI});var cE=z((VyI,rVI)=>{rVI.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var PH=z((QC,iH)=>{Object.defineProperty(QC,"__esModule",{value:!0});QC.MissingRefError=QC.ValidationError=QC.CodeGen=QC.Name=QC.nil=QC.stringify=QC.str=QC._=QC.KeywordCxt=QC.Ajv=void 0;var oVI=H2(),eVI=TH(),IXI=E2(),OE=cE(),GXI=["/properties"],z2="http://json-schema.org/draft-07/schema";class P0 extends oVI.default{_addVocabularies(){if(super._addVocabularies(),eVI.default.forEach((I)=>this.addVocabulary(I)),this.opts.discriminator)this.addKeyword(IXI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let I=this.opts.$data?this.$dataMetaSchema(OE,GXI):OE;this.addMetaSchema(I,z2,!1),this.refs["http://json-schema.org/schema"]=z2}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(z2)?z2:void 0)}}QC.Ajv=P0;iH.exports=QC=P0;iH.exports.Ajv=P0;Object.defineProperty(QC,"__esModule",{value:!0});QC.default=P0;var CXI=eZ();Object.defineProperty(QC,"KeywordCxt",{enumerable:!0,get:function(){return CXI.KeywordCxt}});var Mb=hI();Object.defineProperty(QC,"_",{enumerable:!0,get:function(){return Mb._}});Object.defineProperty(QC,"str",{enumerable:!0,get:function(){return Mb.str}});Object.defineProperty(QC,"stringify",{enumerable:!0,get:function(){return Mb.stringify}});Object.defineProperty(QC,"nil",{enumerable:!0,get:function(){return Mb.nil}});Object.defineProperty(QC,"Name",{enumerable:!0,get:function(){return Mb.Name}});Object.defineProperty(QC,"CodeGen",{enumerable:!0,get:function(){return Mb.CodeGen}});var NXI=Ub();Object.defineProperty(QC,"ValidationError",{enumerable:!0,get:function(){return NXI.default}});var YXI=IW();Object.defineProperty(QC,"MissingRefError",{enumerable:!0,get:function(){return YXI.default}})});var $H=z((uE)=>{Object.defineProperty(uE,"__esModule",{value:!0});uE.dynamicAnchor=void 0;var fH=hI(),bXI=SC(),FE=q0(),lXI=c2(),QXI={keyword:"$dynamicAnchor",schemaType:"string",code:(I)=>vE(I,I.schema)};function vE(I,G){let{gen:C,it:N}=I;N.schemaEnv.root.dynamicAnchors[G]=!0;let Y=fH._`${bXI.default.dynamicAnchors}${(0,fH.getProperty)(G)}`,Z=N.errSchemaPath==="#"?N.validateName:LXI(I);C.if(fH._`!${Y}`,()=>C.assign(Y,Z))}uE.dynamicAnchor=vE;function LXI(I){let{schemaEnv:G,schema:C,self:N}=I.it,{root:Y,baseId:Z,localRefs:W,meta:b}=G.root,{schemaId:l}=N.opts,Q=new FE.SchemaEnv({schema:C,schemaId:l,root:Y,baseId:Z,localRefs:W,meta:b});return FE.compileSchema.call(N,Q),(0,lXI.getValidate)(I,Q)}uE.default=QXI});var tH=z((kE)=>{Object.defineProperty(kE,"__esModule",{value:!0});kE.dynamicRef=void 0;var AE=hI(),VXI=SC(),gE=c2(),XXI={keyword:"$dynamicRef",schemaType:"string",code:(I)=>KE(I,I.schema)};function KE(I,G){let{gen:C,keyword:N,it:Y}=I;if(G[0]!=="#")throw Error(`"${N}" only supports hash fragment reference`);let Z=G.slice(1);if(Y.allErrors)W();else{let l=C.let("valid",!1);W(l),I.ok(l)}function W(l){if(Y.schemaEnv.root.dynamicAnchors[Z]){let Q=C.let("_v",AE._`${VXI.default.dynamicAnchors}${(0,AE.getProperty)(Z)}`);C.if(Q,b(Q,l),b(Y.validateName,l))}else b(Y.validateName,l)()}function b(l,Q){return Q?()=>C.block(()=>{(0,gE.callRef)(I,l),C.let(Q,!0)}):()=>(0,gE.callRef)(I,l)}}kE.dynamicRef=KE;kE.default=XXI});var EE=z((pE)=>{Object.defineProperty(pE,"__esModule",{value:!0});var hXI=$H(),HXI=AI(),wXI={keyword:"$recursiveAnchor",schemaType:"boolean",code(I){if(I.schema)(0,hXI.dynamicAnchor)(I,"");else(0,HXI.checkStrictMode)(I.it,"$recursiveAnchor: false is ignored")}};pE.default=wXI});var DE=z((zE)=>{Object.defineProperty(zE,"__esModule",{value:!0});var cXI=tH(),OXI={keyword:"$recursiveRef",schemaType:"string",code:(I)=>(0,cXI.dynamicRef)(I,I.schema)};zE.default=OXI});var _H=z((qE)=>{Object.defineProperty(qE,"__esModule",{value:!0});var vXI=$H(),uXI=tH(),JXI=EE(),AXI=DE(),gXI=[vXI.default,uXI.default,JXI.default,AXI.default];qE.default=gXI});var BE=z((jE)=>{Object.defineProperty(jE,"__esModule",{value:!0});var UE=A2(),kXI={keyword:"dependentRequired",type:"object",schemaType:"object",error:UE.error,code:(I)=>(0,UE.validatePropertyDeps)(I)};jE.default=kXI});var xE=z((aE)=>{Object.defineProperty(aE,"__esModule",{value:!0});var pXI=A2(),EXI={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(I)=>(0,pXI.validateSchemaDeps)(I)};aE.default=EXI});var SE=z((ME)=>{Object.defineProperty(ME,"__esModule",{value:!0});var DXI=AI(),qXI={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:I,parentSchema:G,it:C}){if(G.contains===void 0)(0,DXI.checkStrictMode)(C,`"${I}" without "contains" is ignored`)}};ME.default=qXI});var rH=z((nE)=>{Object.defineProperty(nE,"__esModule",{value:!0});var jXI=BE(),BXI=xE(),aXI=SE(),xXI=[jXI.default,BXI.default,aXI.default];nE.default=xXI});var iE=z((sE)=>{Object.defineProperty(sE,"__esModule",{value:!0});var YZ=hI(),TE=AI(),SXI=SC(),nXI={message:"must NOT have unevaluated properties",params:({params:I})=>YZ._`{unevaluatedProperty: ${I.unevaluatedProperty}}`},TXI={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:nXI,code(I){let{gen:G,schema:C,data:N,errsCount:Y,it:Z}=I;if(!Y)throw Error("ajv implementation error");let{allErrors:W,props:b}=Z;if(b instanceof YZ.Name)G.if(YZ._`${b} !== true`,()=>G.forIn("key",N,(m)=>G.if(Q(b,m),()=>l(m))));else if(b!==!0)G.forIn("key",N,(m)=>b===void 0?l(m):G.if(L(b,m),()=>l(m)));Z.props=!0,I.ok(YZ._`${Y} === ${SXI.default.errors}`);function l(m){if(C===!1){if(I.setParams({unevaluatedProperty:m}),I.error(),!W)G.break();return}if(!(0,TE.alwaysValidSchema)(Z,C)){let V=G.name("valid");if(I.subschema({keyword:"unevaluatedProperties",dataProp:m,dataPropType:TE.Type.Str},V),!W)G.if((0,YZ.not)(V),()=>G.break())}}function Q(m,V){return YZ._`!${m} || !${m}[${V}]`}function L(m,V){let X=[];for(let R in m)if(m[R]===!0)X.push(YZ._`${V} !== ${R}`);return(0,YZ.and)(...X)}}};sE.default=TXI});var $E=z((fE)=>{Object.defineProperty(fE,"__esModule",{value:!0});var WW=hI(),PE=AI(),iXI={message:({params:{len:I}})=>WW.str`must NOT have more than ${I} items`,params:({params:{len:I}})=>WW._`{limit: ${I}}`},PXI={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:iXI,code(I){let{gen:G,schema:C,data:N,it:Y}=I,Z=Y.items||0;if(Z===!0)return;let W=G.const("len",WW._`${N}.length`);if(C===!1)I.setParams({len:Z}),I.fail(WW._`${W} > ${Z}`);else if(typeof C=="object"&&!(0,PE.alwaysValidSchema)(Y,C)){let l=G.var("valid",WW._`${W} <= ${Z}`);G.if((0,WW.not)(l),()=>b(l,Z)),I.ok(l)}Y.items=!0;function b(l,Q){G.forRange("i",Q,W,(L)=>{if(I.subschema({keyword:"unevaluatedItems",dataProp:L,dataPropType:PE.Type.Num},l),!Y.allErrors)G.if((0,WW.not)(l),()=>G.break())})}}};fE.default=PXI});var oH=z((tE)=>{Object.defineProperty(tE,"__esModule",{value:!0});var $XI=iE(),tXI=$E(),_XI=[$XI.default,tXI.default];tE.default=_XI});var _E=z((DyI,oXI)=>{oXI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}});var rE=z((qyI,eXI)=>{eXI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}});var oE=z((UyI,IRI)=>{IRI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}});var eE=z((jyI,GRI)=>{GRI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}});var I9=z((ByI,CRI)=>{CRI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}});var G9=z((ayI,NRI)=>{NRI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,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 C9=z((xyI,YRI)=>{YRI.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{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"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$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 Y9=z((N9)=>{Object.defineProperty(N9,"__esModule",{value:!0});var ZRI=_E(),WRI=rE(),bRI=oE(),lRI=eE(),QRI=I9(),LRI=G9(),mRI=C9(),VRI=["/properties"];function XRI(I){return[ZRI,WRI,bRI,lRI,G(this,QRI),LRI,G(this,mRI)].forEach((C)=>this.addMetaSchema(C,void 0,!1)),this;function G(C,N){return I?C.$dataMetaSchema(N,VRI):N}}N9.default=XRI});var Z9=z((LC,Iw)=>{Object.defineProperty(LC,"__esModule",{value:!0});LC.MissingRefError=LC.ValidationError=LC.CodeGen=LC.Name=LC.nil=LC.stringify=LC.str=LC._=LC.KeywordCxt=LC.Ajv2019=void 0;var hRI=H2(),HRI=TH(),wRI=_H(),dRI=rH(),cRI=oH(),ORI=E2(),FRI=Y9(),eH="https://json-schema.org/draft/2019-09/schema";class f0 extends hRI.default{constructor(I={}){super({...I,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),this.addVocabulary(wRI.default),HRI.default.forEach((I)=>this.addVocabulary(I)),this.addVocabulary(dRI.default),this.addVocabulary(cRI.default),this.opts.discriminator)this.addKeyword(ORI.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:I,meta:G}=this.opts;if(!G)return;FRI.default.call(this,I),this.refs["http://json-schema.org/schema"]=eH}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(eH)?eH:void 0)}}LC.Ajv2019=f0;Iw.exports=LC=f0;Iw.exports.Ajv2019=f0;Object.defineProperty(LC,"__esModule",{value:!0});LC.default=f0;var vRI=eZ();Object.defineProperty(LC,"KeywordCxt",{enumerable:!0,get:function(){return vRI.KeywordCxt}});var Sb=hI();Object.defineProperty(LC,"_",{enumerable:!0,get:function(){return Sb._}});Object.defineProperty(LC,"str",{enumerable:!0,get:function(){return Sb.str}});Object.defineProperty(LC,"stringify",{enumerable:!0,get:function(){return Sb.stringify}});Object.defineProperty(LC,"nil",{enumerable:!0,get:function(){return Sb.nil}});Object.defineProperty(LC,"Name",{enumerable:!0,get:function(){return Sb.Name}});Object.defineProperty(LC,"CodeGen",{enumerable:!0,get:function(){return Sb.CodeGen}});var uRI=Ub();Object.defineProperty(LC,"ValidationError",{enumerable:!0,get:function(){return uRI.default}});var JRI=IW();Object.defineProperty(LC,"MissingRefError",{enumerable:!0,get:function(){return JRI.default}})});var l9=z((b9)=>{Object.defineProperty(b9,"__esModule",{value:!0});var KRI=pH(),kRI=DH(),yRI=MH(),pRI=_H(),ERI=rH(),zRI=oH(),DRI=SH(),W9=nH(),qRI=[pRI.default,KRI.default,kRI.default,(0,yRI.default)(!0),DRI.default,W9.metadataVocabulary,W9.contentVocabulary,ERI.default,zRI.default];b9.default=qRI});var Q9=z((_yI,jRI)=>{jRI.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 L9=z((ryI,BRI)=>{BRI.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 m9=z((oyI,aRI)=>{aRI.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 V9=z((eyI,xRI)=>{xRI.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 X9=z((IpI,MRI)=>{MRI.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 R9=z((GpI,SRI)=>{SRI.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 h9=z((CpI,nRI)=>{nRI.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 H9=z((NpI,TRI)=>{TRI.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 d9=z((w9)=>{Object.defineProperty(w9,"__esModule",{value:!0});var sRI=Q9(),iRI=L9(),PRI=m9(),fRI=V9(),$RI=X9(),tRI=R9(),_RI=h9(),rRI=H9(),oRI=["/properties"];function eRI(I){return[sRI,iRI,PRI,fRI,$RI,G(this,tRI),_RI,G(this,rRI)].forEach((C)=>this.addMetaSchema(C,void 0,!1)),this;function G(C,N){return I?C.$dataMetaSchema(N,oRI):N}}w9.default=eRI});var c9=z((mC,Cw)=>{Object.defineProperty(mC,"__esModule",{value:!0});mC.MissingRefError=mC.ValidationError=mC.CodeGen=mC.Name=mC.nil=mC.stringify=mC.str=mC._=mC.KeywordCxt=mC.Ajv2020=void 0;var GhI=H2(),ChI=l9(),NhI=E2(),YhI=d9(),Gw="https://json-schema.org/draft/2020-12/schema";class $0 extends GhI.default{constructor(I={}){super({...I,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),ChI.default.forEach((I)=>this.addVocabulary(I)),this.opts.discriminator)this.addKeyword(NhI.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:I,meta:G}=this.opts;if(!G)return;YhI.default.call(this,I),this.refs["http://json-schema.org/schema"]=Gw}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Gw)?Gw:void 0)}}mC.Ajv2020=$0;Cw.exports=mC=$0;Cw.exports.Ajv2020=$0;Object.defineProperty(mC,"__esModule",{value:!0});mC.default=$0;var ZhI=eZ();Object.defineProperty(mC,"KeywordCxt",{enumerable:!0,get:function(){return ZhI.KeywordCxt}});var nb=hI();Object.defineProperty(mC,"_",{enumerable:!0,get:function(){return nb._}});Object.defineProperty(mC,"str",{enumerable:!0,get:function(){return nb.str}});Object.defineProperty(mC,"stringify",{enumerable:!0,get:function(){return nb.stringify}});Object.defineProperty(mC,"nil",{enumerable:!0,get:function(){return nb.nil}});Object.defineProperty(mC,"Name",{enumerable:!0,get:function(){return nb.Name}});Object.defineProperty(mC,"CodeGen",{enumerable:!0,get:function(){return nb.CodeGen}});var WhI=Ub();Object.defineProperty(mC,"ValidationError",{enumerable:!0,get:function(){return WhI.default}});var bhI=IW();Object.defineProperty(mC,"MissingRefError",{enumerable:!0,get:function(){return bhI.default}})});var Rz=z((zzI,Xz)=>{var lZ=jI("constants"),QdI=process.cwd,mm=null,LdI=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!mm)mm=QdI.call(process);return mm};try{process.cwd()}catch(I){}if(typeof process.chdir==="function"){if(Vm=process.chdir,process.chdir=function(I){mm=null,Vm.call(process,I)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,Vm)}var Vm;Xz.exports=mdI;function mdI(I){if(lZ.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))G(I);if(!I.lutimes)C(I);if(I.chown=Z(I.chown),I.fchown=Z(I.fchown),I.lchown=Z(I.lchown),I.chmod=N(I.chmod),I.fchmod=N(I.fchmod),I.lchmod=N(I.lchmod),I.chownSync=W(I.chownSync),I.fchownSync=W(I.fchownSync),I.lchownSync=W(I.lchownSync),I.chmodSync=Y(I.chmodSync),I.fchmodSync=Y(I.fchmodSync),I.lchmodSync=Y(I.lchmodSync),I.stat=b(I.stat),I.fstat=b(I.fstat),I.lstat=b(I.lstat),I.statSync=l(I.statSync),I.fstatSync=l(I.fstatSync),I.lstatSync=l(I.lstatSync),I.chmod&&!I.lchmod)I.lchmod=function(L,m,V){if(V)process.nextTick(V)},I.lchmodSync=function(){};if(I.chown&&!I.lchown)I.lchown=function(L,m,V,X){if(X)process.nextTick(X)},I.lchownSync=function(){};if(LdI==="win32")I.rename=typeof I.rename!=="function"?I.rename:function(L){function m(V,X,R){var h=Date.now(),H=0;L(V,X,function d(O){if(O&&(O.code==="EACCES"||O.code==="EPERM"||O.code==="EBUSY")&&Date.now()-h<60000){if(setTimeout(function(){I.stat(X,function(F,c){if(F&&F.code==="ENOENT")L(V,X,d);else R(O)})},H),H<100)H+=10;return}if(R)R(O)})}if(Object.setPrototypeOf)Object.setPrototypeOf(m,L);return m}(I.rename);I.read=typeof I.read!=="function"?I.read:function(L){function m(V,X,R,h,H,d){var O;if(d&&typeof d==="function"){var F=0;O=function(c,v,J){if(c&&c.code==="EAGAIN"&&F<10)return F++,L.call(I,V,X,R,h,H,O);d.apply(this,arguments)}}return L.call(I,V,X,R,h,H,O)}if(Object.setPrototypeOf)Object.setPrototypeOf(m,L);return m}(I.read),I.readSync=typeof I.readSync!=="function"?I.readSync:function(L){return function(m,V,X,R,h){var H=0;while(!0)try{return L.call(I,m,V,X,R,h)}catch(d){if(d.code==="EAGAIN"&&H<10){H++;continue}throw d}}}(I.readSync);function G(L){L.lchmod=function(m,V,X){L.open(m,lZ.O_WRONLY|lZ.O_SYMLINK,V,function(R,h){if(R){if(X)X(R);return}L.fchmod(h,V,function(H){L.close(h,function(d){if(X)X(H||d)})})})},L.lchmodSync=function(m,V){var X=L.openSync(m,lZ.O_WRONLY|lZ.O_SYMLINK,V),R=!0,h;try{h=L.fchmodSync(X,V),R=!1}finally{if(R)try{L.closeSync(X)}catch(H){}else L.closeSync(X)}return h}}function C(L){if(lZ.hasOwnProperty("O_SYMLINK")&&L.futimes)L.lutimes=function(m,V,X,R){L.open(m,lZ.O_SYMLINK,function(h,H){if(h){if(R)R(h);return}L.futimes(H,V,X,function(d){L.close(H,function(O){if(R)R(d||O)})})})},L.lutimesSync=function(m,V,X){var R=L.openSync(m,lZ.O_SYMLINK),h,H=!0;try{h=L.futimesSync(R,V,X),H=!1}finally{if(H)try{L.closeSync(R)}catch(d){}else L.closeSync(R)}return h};else if(L.futimes)L.lutimes=function(m,V,X,R){if(R)process.nextTick(R)},L.lutimesSync=function(){}}function N(L){if(!L)return L;return function(m,V,X){return L.call(I,m,V,function(R){if(Q(R))R=null;if(X)X.apply(this,arguments)})}}function Y(L){if(!L)return L;return function(m,V){try{return L.call(I,m,V)}catch(X){if(!Q(X))throw X}}}function Z(L){if(!L)return L;return function(m,V,X,R){return L.call(I,m,V,X,function(h){if(Q(h))h=null;if(R)R.apply(this,arguments)})}}function W(L){if(!L)return L;return function(m,V,X){try{return L.call(I,m,V,X)}catch(R){if(!Q(R))throw R}}}function b(L){if(!L)return L;return function(m,V,X){if(typeof V==="function")X=V,V=null;function R(h,H){if(H){if(H.uid<0)H.uid+=4294967296;if(H.gid<0)H.gid+=4294967296}if(X)X.apply(this,arguments)}return V?L.call(I,m,V,R):L.call(I,m,R)}}function l(L){if(!L)return L;return function(m,V){var X=V?L.call(I,m,V):L.call(I,m);if(X){if(X.uid<0)X.uid+=4294967296;if(X.gid<0)X.gid+=4294967296}return X}}function Q(L){if(!L)return!0;if(L.code==="ENOSYS")return!0;var m=!process.getuid||process.getuid()!==0;if(m){if(L.code==="EINVAL"||L.code==="EPERM")return!0}return!1}}});var wz=z((DzI,Hz)=>{var hz=jI("stream").Stream;Hz.exports=VdI;function VdI(I){return{ReadStream:G,WriteStream:C};function G(N,Y){if(!(this instanceof G))return new G(N,Y);hz.call(this);var Z=this;this.path=N,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,Y=Y||{};var W=Object.keys(Y);for(var b=0,l=W.length;b<l;b++){var Q=W[b];this[Q]=Y[Q]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){Z._read()});return}I.open(this.path,this.flags,this.mode,function(L,m){if(L){Z.emit("error",L),Z.readable=!1;return}Z.fd=m,Z.emit("open",m),Z._read()})}function C(N,Y){if(!(this instanceof C))return new C(N,Y);hz.call(this),this.path=N,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,Y=Y||{};var Z=Object.keys(Y);for(var W=0,b=Z.length;W<b;W++){var l=Z[W];this[l]=Y[l]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=I.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var cz=z((qzI,dz)=>{dz.exports=RdI;var XdI=Object.getPrototypeOf||function(I){return I.__proto__};function RdI(I){if(I===null||typeof I!=="object")return I;if(I instanceof Object)var G={__proto__:XdI(I)};else var G=Object.create(null);return Object.getOwnPropertyNames(I).forEach(function(C){Object.defineProperty(G,C,Object.getOwnPropertyDescriptor(I,C))}),G}});var Pw=z((UzI,iw)=>{var NG=jI("fs"),hdI=Rz(),HdI=wz(),wdI=cz(),Xm=jI("util"),gG,hm;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gG=Symbol.for("graceful-fs.queue"),hm=Symbol.for("graceful-fs.previous");else gG="___graceful-fs.queue",hm="___graceful-fs.previous";function ddI(){}function Fz(I,G){Object.defineProperty(I,gG,{get:function(){return G}})}var XW=ddI;if(Xm.debuglog)XW=Xm.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))XW=function(){var I=Xm.format.apply(Xm,arguments);I="GFS4: "+I.split(/\n/).join(`
|
|
57
|
-
GFS4: `),console.error(I)};if(!NG[gG]){if(nw=global[gG]||[],Fz(NG,nw),NG.close=function(I){function G(C,N){return I.call(NG,C,function(Y){if(!Y)Oz();if(typeof N==="function")N.apply(this,arguments)})}return Object.defineProperty(G,hm,{value:I}),G}(NG.close),NG.closeSync=function(I){function G(C){I.apply(NG,arguments),Oz()}return Object.defineProperty(G,hm,{value:I}),G}(NG.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){XW(NG[gG]),jI("assert").equal(NG[gG].length,0)})}var nw;if(!global[gG])Fz(global,NG[gG]);iw.exports=Tw(wdI(NG));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!NG.__patched)iw.exports=Tw(NG),NG.__patched=!0;function Tw(I){hdI(I),I.gracefulify=Tw,I.createReadStream=v,I.createWriteStream=J;var G=I.readFile;I.readFile=C;function C(A,p,D){if(typeof p==="function")D=p,p=null;return q(A,p,D);function q(k,K,B,M){return G(k,K,function(j){if(j&&(j.code==="EMFILE"||j.code==="ENFILE"))Il([q,[k,K,B],j,M||Date.now(),Date.now()]);else if(typeof B==="function")B.apply(this,arguments)})}}var N=I.writeFile;I.writeFile=Y;function Y(A,p,D,q){if(typeof D==="function")q=D,D=null;return k(A,p,D,q);function k(K,B,M,j,WI){return N(K,B,M,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}var Z=I.appendFile;if(Z)I.appendFile=W;function W(A,p,D,q){if(typeof D==="function")q=D,D=null;return k(A,p,D,q);function k(K,B,M,j,WI){return Z(K,B,M,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}var b=I.copyFile;if(b)I.copyFile=l;function l(A,p,D,q){if(typeof D==="function")q=D,D=0;return k(A,p,D,q);function k(K,B,M,j,WI){return b(K,B,M,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}var Q=I.readdir;I.readdir=m;var L=/^v[0-5]\./;function m(A,p,D){if(typeof p==="function")D=p,p=null;var q=L.test(process.version)?function(B,M,j,WI){return Q(B,k(B,M,j,WI))}:function(B,M,j,WI){return Q(B,M,k(B,M,j,WI))};return q(A,p,D);function k(K,B,M,j){return function(WI,r){if(WI&&(WI.code==="EMFILE"||WI.code==="ENFILE"))Il([q,[K,B,M],WI,j||Date.now(),Date.now()]);else{if(r&&r.sort)r.sort();if(typeof M==="function")M.call(this,WI,r)}}}}if(process.version.substr(0,4)==="v0.8"){var V=HdI(I);d=V.ReadStream,F=V.WriteStream}var X=I.ReadStream;if(X)d.prototype=Object.create(X.prototype),d.prototype.open=O;var R=I.WriteStream;if(R)F.prototype=Object.create(R.prototype),F.prototype.open=c;Object.defineProperty(I,"ReadStream",{get:function(){return d},set:function(A){d=A},enumerable:!0,configurable:!0}),Object.defineProperty(I,"WriteStream",{get:function(){return F},set:function(A){F=A},enumerable:!0,configurable:!0});var h=d;Object.defineProperty(I,"FileReadStream",{get:function(){return h},set:function(A){h=A},enumerable:!0,configurable:!0});var H=F;Object.defineProperty(I,"FileWriteStream",{get:function(){return H},set:function(A){H=A},enumerable:!0,configurable:!0});function d(A,p){if(this instanceof d)return X.apply(this,arguments),this;else return d.apply(Object.create(d.prototype),arguments)}function O(){var A=this;g(A.path,A.flags,A.mode,function(p,D){if(p){if(A.autoClose)A.destroy();A.emit("error",p)}else A.fd=D,A.emit("open",D),A.read()})}function F(A,p){if(this instanceof F)return R.apply(this,arguments),this;else return F.apply(Object.create(F.prototype),arguments)}function c(){var A=this;g(A.path,A.flags,A.mode,function(p,D){if(p)A.destroy(),A.emit("error",p);else A.fd=D,A.emit("open",D)})}function v(A,p){return new I.ReadStream(A,p)}function J(A,p){return new I.WriteStream(A,p)}var u=I.open;I.open=g;function g(A,p,D,q){if(typeof D==="function")q=D,D=null;return k(A,p,D,q);function k(K,B,M,j,WI){return u(K,B,M,function(r,GI){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}return I}function Il(I){XW("ENQUEUE",I[0].name,I[1]),NG[gG].push(I),sw()}var Rm;function Oz(){var I=Date.now();for(var G=0;G<NG[gG].length;++G)if(NG[gG][G].length>2)NG[gG][G][3]=I,NG[gG][G][4]=I;sw()}function sw(){if(clearTimeout(Rm),Rm=void 0,NG[gG].length===0)return;var I=NG[gG].shift(),G=I[0],C=I[1],N=I[2],Y=I[3],Z=I[4];if(Y===void 0)XW("RETRY",G.name,C),G.apply(null,C);else if(Date.now()-Y>=60000){XW("TIMEOUT",G.name,C);var W=C.pop();if(typeof W==="function")W.call(null,N)}else{var b=Date.now()-Z,l=Math.max(Z-Y,1),Q=Math.min(l*1.2,100);if(b>=Q)XW("RETRY",G.name,C),G.apply(null,C.concat([Y]));else NG[gG].push(I)}if(Rm===void 0)Rm=setTimeout(sw,0)}});var uz=z((jzI,vz)=>{function PC(I,G){if(typeof G==="boolean")G={forever:G};if(this._originalTimeouts=JSON.parse(JSON.stringify(I)),this._timeouts=I,this._options=G||{},this._maxRetryTime=G&&G.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}vz.exports=PC;PC.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};PC.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};PC.prototype.retry=function(I){if(this._timeout)clearTimeout(this._timeout);if(!I)return!1;var G=new Date().getTime();if(I&&G-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(I);var C=this._timeouts.shift();if(C===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),C=this._timeouts.shift();else return!1;var N=this,Y=setTimeout(function(){if(N._attempts++,N._operationTimeoutCb){if(N._timeout=setTimeout(function(){N._operationTimeoutCb(N._attempts)},N._operationTimeout),N._options.unref)N._timeout.unref()}N._fn(N._attempts)},C);if(this._options.unref)Y.unref();return!0};PC.prototype.attempt=function(I,G){if(this._fn=I,G){if(G.timeout)this._operationTimeout=G.timeout;if(G.cb)this._operationTimeoutCb=G.cb}var C=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){C._operationTimeoutCb()},C._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};PC.prototype.try=function(I){console.log("Using RetryOperation.try() is deprecated"),this.attempt(I)};PC.prototype.start=function(I){console.log("Using RetryOperation.start() is deprecated"),this.attempt(I)};PC.prototype.start=PC.prototype.try;PC.prototype.errors=function(){return this._errors};PC.prototype.attempts=function(){return this._attempts};PC.prototype.mainError=function(){if(this._errors.length===0)return null;var I={},G=null,C=0;for(var N=0;N<this._errors.length;N++){var Y=this._errors[N],Z=Y.message,W=(I[Z]||0)+1;if(I[Z]=W,W>=C)G=Y,C=W}return G}});var Az=z((OdI)=>{var cdI=uz();OdI.operation=function(I){var G=OdI.timeouts(I);return new cdI(G,{forever:I&&I.forever,unref:I&&I.unref,maxRetryTime:I&&I.maxRetryTime})};OdI.timeouts=function(I){if(I instanceof Array)return[].concat(I);var G={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var C in I)G[C]=I[C];if(G.minTimeout>G.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var N=[];for(var Y=0;Y<G.retries;Y++)N.push(this.createTimeout(Y,G));if(I&&I.forever&&!N.length)N.push(this.createTimeout(Y,G));return N.sort(function(Z,W){return Z-W}),N};OdI.createTimeout=function(I,G){var C=G.randomize?Math.random()+1:1,N=Math.round(C*G.minTimeout*Math.pow(G.factor,I));return N=Math.min(N,G.maxTimeout),N};OdI.wrap=function(I,G,C){if(G instanceof Array)C=G,G=null;if(!C){C=[];for(var N in I)if(typeof I[N]==="function")C.push(N)}for(var Y=0;Y<C.length;Y++){var Z=C[Y],W=I[Z];I[Z]=function(l){var Q=OdI.operation(G),L=Array.prototype.slice.call(arguments,1),m=L.pop();L.push(function(V){if(Q.retry(V))return;if(V)arguments[0]=Q.mainError();m.apply(this,arguments)}),Q.attempt(function(){l.apply(I,L)})}.bind(I,W),I[Z].options=G}}});var gz=z((azI,Hm)=>{Hm.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")Hm.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Hm.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var Kz=z((xzI,Cl)=>{var oI=global.process,RW=function(I){return I&&typeof I==="object"&&typeof I.removeListener==="function"&&typeof I.emit==="function"&&typeof I.reallyExit==="function"&&typeof I.listeners==="function"&&typeof I.kill==="function"&&typeof I.pid==="number"&&typeof I.on==="function"};if(!RW(oI))Cl.exports=function(){return function(){}};else{if(fw=jI("assert"),hW=gz(),$w=/^win/i.test(oI.platform),Gl=jI("events"),typeof Gl!=="function")Gl=Gl.EventEmitter;if(oI.__signal_exit_emitter__)dG=oI.__signal_exit_emitter__;else dG=oI.__signal_exit_emitter__=new Gl,dG.count=0,dG.emitted={};if(!dG.infinite)dG.setMaxListeners(1/0),dG.infinite=!0;Cl.exports=function(I,G){if(!RW(global.process))return function(){};if(fw.equal(typeof I,"function","a callback must be provided for exit handler"),HW===!1)wm();var C="exit";if(G&&G.alwaysLast)C="afterexit";var N=function(){if(dG.removeListener(C,I),dG.listeners("exit").length===0&&dG.listeners("afterexit").length===0)W4()};return dG.on(C,I),N},W4=function(){if(!HW||!RW(global.process))return;HW=!1,hW.forEach(function(G){try{oI.removeListener(G,b4[G])}catch(C){}}),oI.emit=l4,oI.reallyExit=dm,dG.count-=1},Cl.exports.unload=W4,QZ=function(G,C,N){if(dG.emitted[G])return;dG.emitted[G]=!0,dG.emit(G,C,N)},b4={},hW.forEach(function(I){b4[I]=function(){if(!RW(global.process))return;var C=oI.listeners(I);if(C.length===dG.count){if(W4(),QZ("exit",null,I),QZ("afterexit",null,I),$w&&I==="SIGHUP")I="SIGINT";oI.kill(oI.pid,I)}}}),Cl.exports.signals=function(){return hW},HW=!1,wm=function(){if(HW||!RW(global.process))return;HW=!0,dG.count+=1,hW=hW.filter(function(G){try{return oI.on(G,b4[G]),!0}catch(C){return!1}}),oI.emit=_w,oI.reallyExit=tw},Cl.exports.load=wm,dm=oI.reallyExit,tw=function(G){if(!RW(global.process))return;oI.exitCode=G||0,QZ("exit",oI.exitCode,null),QZ("afterexit",oI.exitCode,null),dm.call(oI,oI.exitCode)},l4=oI.emit,_w=function(G,C){if(G==="exit"&&RW(global.process)){if(C!==void 0)oI.exitCode=C;var N=l4.apply(this,arguments);return QZ("exit",oI.exitCode,null),QZ("afterexit",oI.exitCode,null),N}else return l4.apply(this,arguments)}}var fw,hW,$w,Gl,dG,W4,QZ,b4,HW,wm,dm,tw,l4,_w});var yz=z((gdI,rw)=>{var kz=Symbol();function JdI(I,G,C){let N=G[kz];if(N)return G.stat(I,(Z,W)=>{if(Z)return C(Z);C(null,W.mtime,N)});let Y=new Date(Math.ceil(Date.now()/1000)*1000+5);G.utimes(I,Y,Y,(Z)=>{if(Z)return C(Z);G.stat(I,(W,b)=>{if(W)return C(W);let l=b.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(G,kz,{value:l}),C(null,b.mtime,l)})})}function AdI(I){let G=Date.now();if(I==="s")G=Math.ceil(G/1000)*1000;return new Date(G)}gdI.probe=JdI;gdI.getMtime=AdI});var qz=z((UdI,L4)=>{var ydI=jI("path"),Id=Pw(),pdI=Az(),EdI=Kz(),pz=yz(),OY={};function Q4(I,G){return G.lockfilePath||`${I}.lock`}function Gd(I,G,C){if(!G.realpath)return C(null,ydI.resolve(I));G.fs.realpath(I,C)}function ew(I,G,C){let N=Q4(I,G);G.fs.mkdir(N,(Y)=>{if(!Y)return pz.probe(N,G.fs,(Z,W,b)=>{if(Z)return G.fs.rmdir(N,()=>{}),C(Z);C(null,W,b)});if(Y.code!=="EEXIST")return C(Y);if(G.stale<=0)return C(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:I}));G.fs.stat(N,(Z,W)=>{if(Z){if(Z.code==="ENOENT")return ew(I,{...G,stale:0},C);return C(Z)}if(!Ez(W,G))return C(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:I}));zz(I,G,(b)=>{if(b)return C(b);ew(I,{...G,stale:0},C)})})})}function Ez(I,G){return I.mtime.getTime()<Date.now()-G.stale}function zz(I,G,C){G.fs.rmdir(Q4(I,G),(N)=>{if(N&&N.code!=="ENOENT")return C(N);C()})}function cm(I,G){let C=OY[I];if(C.updateTimeout)return;if(C.updateDelay=C.updateDelay||G.update,C.updateTimeout=setTimeout(()=>{C.updateTimeout=null,G.fs.stat(C.lockfilePath,(N,Y)=>{let Z=C.lastUpdate+G.stale<Date.now();if(N){if(N.code==="ENOENT"||Z)return ow(I,C,Object.assign(N,{code:"ECOMPROMISED"}));return C.updateDelay=1000,cm(I,G)}if(C.mtime.getTime()!==Y.mtime.getTime())return ow(I,C,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let b=pz.getMtime(C.mtimePrecision);G.fs.utimes(C.lockfilePath,b,b,(l)=>{let Q=C.lastUpdate+G.stale<Date.now();if(C.released)return;if(l){if(l.code==="ENOENT"||Q)return ow(I,C,Object.assign(l,{code:"ECOMPROMISED"}));return C.updateDelay=1000,cm(I,G)}C.mtime=b,C.lastUpdate=Date.now(),C.updateDelay=null,cm(I,G)})})},C.updateDelay),C.updateTimeout.unref)C.updateTimeout.unref()}function ow(I,G,C){if(G.released=!0,G.updateTimeout)clearTimeout(G.updateTimeout);if(OY[I]===G)delete OY[I];G.options.onCompromised(C)}function zdI(I,G,C){G={stale:1e4,update:null,realpath:!0,retries:0,fs:Id,onCompromised:(N)=>{throw N},...G},G.retries=G.retries||0,G.retries=typeof G.retries==="number"?{retries:G.retries}:G.retries,G.stale=Math.max(G.stale||0,2000),G.update=G.update==null?G.stale/2:G.update||0,G.update=Math.max(Math.min(G.update,G.stale/2),1000),Gd(I,G,(N,Y)=>{if(N)return C(N);let Z=pdI.operation(G.retries);Z.attempt(()=>{ew(Y,G,(W,b,l)=>{if(Z.retry(W))return;if(W)return C(Z.mainError());let Q=OY[Y]={lockfilePath:Q4(Y,G),mtime:b,mtimePrecision:l,options:G,lastUpdate:Date.now()};cm(Y,G),C(null,(L)=>{if(Q.released)return L&&L(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));Dz(Y,{...G,realpath:!1},L)})})})})}function Dz(I,G,C){G={fs:Id,realpath:!0,...G},Gd(I,G,(N,Y)=>{if(N)return C(N);let Z=OY[Y];if(!Z)return C(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));Z.updateTimeout&&clearTimeout(Z.updateTimeout),Z.released=!0,delete OY[Y],zz(Y,G,C)})}function DdI(I,G,C){G={stale:1e4,realpath:!0,fs:Id,...G},G.stale=Math.max(G.stale||0,2000),Gd(I,G,(N,Y)=>{if(N)return C(N);G.fs.stat(Q4(Y,G),(Z,W)=>{if(Z)return Z.code==="ENOENT"?C(null,!1):C(Z);return C(null,!Ez(W,G))})})}function qdI(){return OY}EdI(()=>{for(let I in OY){let G=OY[I].options;try{G.fs.rmdirSync(Q4(I,G))}catch(C){}}});UdI.lock=zdI;UdI.unlock=Dz;UdI.check=DdI;UdI.getLocks=qdI});var jz=z((MzI,Uz)=>{var MdI=Pw();function SdI(I){let G=["mkdir","realpath","stat","rmdir","utimes"],C={...I};return G.forEach((N)=>{C[N]=(...Y)=>{let Z=Y.pop(),W;try{W=I[`${N}Sync`](...Y)}catch(b){return Z(b)}Z(null,W)}}),C}function ndI(I){return(...G)=>new Promise((C,N)=>{G.push((Y,Z)=>{if(Y)N(Y);else C(Z)}),I(...G)})}function TdI(I){return(...G)=>{let C,N;if(G.push((Y,Z)=>{C=Y,N=Z}),I(...G),C)throw C;return N}}function sdI(I){if(I={...I},I.fs=SdI(I.fs||MdI),typeof I.retries==="number"&&I.retries>0||I.retries&&typeof I.retries.retries==="number"&&I.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return I}Uz.exports={toPromise:ndI,toSync:TdI,toSyncOptions:sdI}});var az=z((SzI,LZ)=>{var Nl=qz(),{toPromise:Om,toSync:Fm,toSyncOptions:Cd}=jz();async function Bz(I,G){let C=await Om(Nl.lock)(I,G);return Om(C)}function idI(I,G){let C=Fm(Nl.lock)(I,Cd(G));return Fm(C)}function PdI(I,G){return Om(Nl.unlock)(I,G)}function fdI(I,G){return Fm(Nl.unlock)(I,Cd(G))}function $dI(I,G){return Om(Nl.check)(I,G)}function tdI(I,G){return Fm(Nl.check)(I,Cd(G))}LZ.exports=Bz;LZ.exports.lock=Bz;LZ.exports.unlock=PdI;LZ.exports.lockSync=idI;LZ.exports.unlockSync=fdI;LZ.exports.check=$dI;LZ.exports.checkSync=tdI});import{createInterface as pOI}from"readline/promises";var Fd={name:"@sunerpy/kiro-provider",version:"3.6.0",description:"OpenAI Responses-compatible AWS KiroRuntime provider with native and stateless fallback transports",homepage:"https://github.com/sunerpy/kiro-provider#readme",bugs:"https://github.com/sunerpy/kiro-provider/issues",license:"MIT",repository:{type:"git",url:"git+https://github.com/sunerpy/kiro-provider.git"},bin:{"kiro-provider":"dist/cli.js"},files:["dist/cli.js","README.md","LICENSE"],type:"module",publishConfig:{access:"public"},scripts:{fmt:"oxfmt --ignore-path .oxfmtignore --write '**/*.{yml,yaml,json,md}' && biome check --write ./src ./scripts ./__tests__",lint:"biome check ./src ./scripts ./__tests__",typecheck:"tsc --noEmit",test:"bun test",build:"bun run build:npm","build:binary":"bun build --compile --minify src/cli/bin.ts --outfile dist/kiro-provider","build:npm":"bun build src/cli/bin.ts --outfile dist/cli.js --target=bun --minify && chmod +x dist/cli.js","probe:projection-fidelity":"bun run scripts/probe-projection-fidelity.ts","probe:v3-fields":"bun run scripts/probe-v3-request-fields.ts","probe:v3-create-response":"bun run scripts/probe-v3-create-response.ts","study:effort":"bun run scripts/effort-study.ts","study:effort:run":"bun run scripts/run-effort-study.ts","study:effort:responses":"bun run scripts/responses-effort-study.ts","e2e:responses":"bun run scripts/responses-live-e2e.ts","diff:kiro-cli-wire":"bun run scripts/kiro-cli-wire-diff.ts",prepublishOnly:"bun run build:npm","docs:links":"bun run scripts/check-markdown-links.ts","fmt:check":"oxfmt --ignore-path .oxfmtignore --check '**/*.{yml,yaml,json,md}' && biome check ./src ./scripts ./__tests__",check:"bun run fmt:check && bun run typecheck && bun run lint && bun run docs:links && bun run test && bun run build"},dependencies:{"@aws-sdk/core":"3.975.3","@aws/codewhisperer-streaming-client":"^1.0.34","@smithy/node-http-handler":"4.9.7",ajv:"8.20.0","https-proxy-agent":"^9.1.0","js-tiktoken":"1.0.21","proper-lockfile":"^4.1.2",zod:"^3.24.0"},devDependencies:{"@ai-sdk/openai":"4.0.66","@biomejs/biome":"2.2.4","@types/bun":"^1.3.6","@types/node":"^20.0.0","@types/proper-lockfile":"^4.1.4",ai:"7.0.99",openai:"7.13.0",oxfmt:"0.64.0",typescript:"^5.7.3"},engines:{bun:">=1.3.14"},packageManager:"bun@1.3.14"};import{existsSync as VU,readFileSync as XU,statSync as RU}from"fs";var w={};PD(w,{void:()=>Eq,util:()=>gI,unknown:()=>yq,union:()=>Uq,undefined:()=>gq,tuple:()=>aq,transformer:()=>$q,symbol:()=>Aq,string:()=>pd,strictObject:()=>qq,setErrorMap:()=>_D,set:()=>Sq,record:()=>xq,quotelessJson:()=>$D,promise:()=>fq,preprocess:()=>rq,pipeline:()=>oq,ostring:()=>eq,optional:()=>tq,onumber:()=>IU,oboolean:()=>GU,objectUtil:()=>Dm,object:()=>Dq,number:()=>Ed,nullable:()=>_q,null:()=>Kq,never:()=>pq,nativeEnum:()=>Pq,nan:()=>vq,map:()=>Mq,makeIssue:()=>Wl,literal:()=>sq,lazy:()=>Tq,late:()=>Oq,isValid:()=>uY,isDirty:()=>w4,isAsync:()=>cW,isAborted:()=>H4,intersection:()=>Bq,instanceof:()=>Fq,getParsedType:()=>FN,getErrorMap:()=>dW,function:()=>nq,enum:()=>iq,effect:()=>$q,discriminatedUnion:()=>jq,defaultErrorMap:()=>_N,datetimeRegex:()=>Kd,date:()=>Jq,custom:()=>yd,coerce:()=>CU,boolean:()=>zd,bigint:()=>uq,array:()=>zq,any:()=>kq,addIssueToContext:()=>P,ZodVoid:()=>ll,ZodUnknown:()=>JY,ZodUnion:()=>AW,ZodUndefined:()=>uW,ZodType:()=>vI,ZodTuple:()=>uN,ZodTransformer:()=>IN,ZodSymbol:()=>bl,ZodString:()=>_C,ZodSet:()=>RZ,ZodSchema:()=>vI,ZodRecord:()=>Ql,ZodReadonly:()=>zW,ZodPromise:()=>hZ,ZodPipeline:()=>Vl,ZodParsedType:()=>T,ZodOptional:()=>oC,ZodObject:()=>GG,ZodNumber:()=>AY,ZodNullable:()=>oN,ZodNull:()=>JW,ZodNever:()=>vN,ZodNativeEnum:()=>yW,ZodNaN:()=>ml,ZodMap:()=>Ll,ZodLiteral:()=>kW,ZodLazy:()=>KW,ZodIssueCode:()=>x,ZodIntersection:()=>gW,ZodFunction:()=>FW,ZodFirstPartyTypeKind:()=>QI,ZodError:()=>PG,ZodEnum:()=>KY,ZodEffects:()=>IN,ZodDiscriminatedUnion:()=>d4,ZodDefault:()=>pW,ZodDate:()=>VZ,ZodCatch:()=>EW,ZodBranded:()=>c4,ZodBoolean:()=>vW,ZodBigInt:()=>gY,ZodArray:()=>rC,ZodAny:()=>XZ,Schema:()=>vI,ParseStatus:()=>FG,OK:()=>EG,NEVER:()=>NU,INVALID:()=>bI,EMPTY_PATH:()=>rD,DIRTY:()=>mZ,BRAND:()=>cq});var gI;(function(I){I.assertEqual=(Y)=>{};function G(Y){}I.assertIs=G;function C(Y){throw Error()}I.assertNever=C,I.arrayToEnum=(Y)=>{let Z={};for(let W of Y)Z[W]=W;return Z},I.getValidEnumValues=(Y)=>{let Z=I.objectKeys(Y).filter((b)=>typeof Y[Y[b]]!=="number"),W={};for(let b of Z)W[b]=Y[b];return I.objectValues(W)},I.objectValues=(Y)=>{return I.objectKeys(Y).map(function(Z){return Y[Z]})},I.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let Z=[];for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))Z.push(W);return Z},I.find=(Y,Z)=>{for(let W of Y)if(Z(W))return W;return},I.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function N(Y,Z=" | "){return Y.map((W)=>typeof W==="string"?`'${W}'`:W).join(Z)}I.joinValues=N,I.jsonStringifyReplacer=(Y,Z)=>{if(typeof Z==="bigint")return Z.toString();return Z}})(gI||(gI={}));var Dm;(function(I){I.mergeShapes=(G,C)=>{return{...G,...C}}})(Dm||(Dm={}));var T=gI.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),FN=(I)=>{switch(typeof I){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(I)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":if(Array.isArray(I))return T.array;if(I===null)return T.null;if(I.then&&typeof I.then==="function"&&I.catch&&typeof I.catch==="function")return T.promise;if(typeof Map<"u"&&I instanceof Map)return T.map;if(typeof Set<"u"&&I instanceof Set)return T.set;if(typeof Date<"u"&&I instanceof Date)return T.date;return T.object;default:return T.unknown}};var x=gI.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$D=(I)=>{return JSON.stringify(I,null,2).replace(/"([^"]+)":/g,"$1:")};class PG extends Error{get errors(){return this.issues}constructor(I){super();this.issues=[],this.addIssue=(C)=>{this.issues=[...this.issues,C]},this.addIssues=(C=[])=>{this.issues=[...this.issues,...C]};let G=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,G);else this.__proto__=G;this.name="ZodError",this.issues=I}format(I){let G=I||function(Y){return Y.message},C={_errors:[]},N=(Y)=>{for(let Z of Y.issues)if(Z.code==="invalid_union")Z.unionErrors.map(N);else if(Z.code==="invalid_return_type")N(Z.returnTypeError);else if(Z.code==="invalid_arguments")N(Z.argumentsError);else if(Z.path.length===0)C._errors.push(G(Z));else{let W=C,b=0;while(b<Z.path.length){let l=Z.path[b];if(b!==Z.path.length-1)W[l]=W[l]||{_errors:[]};else W[l]=W[l]||{_errors:[]},W[l]._errors.push(G(Z));W=W[l],b++}}};return N(this),C}static assert(I){if(!(I instanceof PG))throw Error(`Not a ZodError: ${I}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,gI.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(I=(G)=>G.message){let G={},C=[];for(let N of this.issues)if(N.path.length>0){let Y=N.path[0];G[Y]=G[Y]||[],G[Y].push(I(N))}else C.push(I(N));return{formErrors:C,fieldErrors:G}}get formErrors(){return this.flatten()}}PG.create=(I)=>{return new PG(I)};var tD=(I,G)=>{let C;switch(I.code){case x.invalid_type:if(I.received===T.undefined)C="Required";else C=`Expected ${I.expected}, received ${I.received}`;break;case x.invalid_literal:C=`Invalid literal value, expected ${JSON.stringify(I.expected,gI.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:C=`Unrecognized key(s) in object: ${gI.joinValues(I.keys,", ")}`;break;case x.invalid_union:C="Invalid input";break;case x.invalid_union_discriminator:C=`Invalid discriminator value. Expected ${gI.joinValues(I.options)}`;break;case x.invalid_enum_value:C=`Invalid enum value. Expected ${gI.joinValues(I.options)}, received '${I.received}'`;break;case x.invalid_arguments:C="Invalid function arguments";break;case x.invalid_return_type:C="Invalid function return type";break;case x.invalid_date:C="Invalid date";break;case x.invalid_string:if(typeof I.validation==="object")if("includes"in I.validation){if(C=`Invalid input: must include "${I.validation.includes}"`,typeof I.validation.position==="number")C=`${C} at one or more positions greater than or equal to ${I.validation.position}`}else if("startsWith"in I.validation)C=`Invalid input: must start with "${I.validation.startsWith}"`;else if("endsWith"in I.validation)C=`Invalid input: must end with "${I.validation.endsWith}"`;else gI.assertNever(I.validation);else if(I.validation!=="regex")C=`Invalid ${I.validation}`;else C="Invalid";break;case x.too_small:if(I.type==="array")C=`Array must contain ${I.exact?"exactly":I.inclusive?"at least":"more than"} ${I.minimum} element(s)`;else if(I.type==="string")C=`String must contain ${I.exact?"exactly":I.inclusive?"at least":"over"} ${I.minimum} character(s)`;else if(I.type==="number")C=`Number must be ${I.exact?"exactly equal to ":I.inclusive?"greater than or equal to ":"greater than "}${I.minimum}`;else if(I.type==="bigint")C=`Number must be ${I.exact?"exactly equal to ":I.inclusive?"greater than or equal to ":"greater than "}${I.minimum}`;else if(I.type==="date")C=`Date must be ${I.exact?"exactly equal to ":I.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(I.minimum))}`;else C="Invalid input";break;case x.too_big:if(I.type==="array")C=`Array must contain ${I.exact?"exactly":I.inclusive?"at most":"less than"} ${I.maximum} element(s)`;else if(I.type==="string")C=`String must contain ${I.exact?"exactly":I.inclusive?"at most":"under"} ${I.maximum} character(s)`;else if(I.type==="number")C=`Number must be ${I.exact?"exactly":I.inclusive?"less than or equal to":"less than"} ${I.maximum}`;else if(I.type==="bigint")C=`BigInt must be ${I.exact?"exactly":I.inclusive?"less than or equal to":"less than"} ${I.maximum}`;else if(I.type==="date")C=`Date must be ${I.exact?"exactly":I.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(I.maximum))}`;else C="Invalid input";break;case x.custom:C="Invalid input";break;case x.invalid_intersection_types:C="Intersection results could not be merged";break;case x.not_multiple_of:C=`Number must be a multiple of ${I.multipleOf}`;break;case x.not_finite:C="Number must be finite";break;default:C=G.defaultError,gI.assertNever(I)}return{message:C}},_N=tD;var vd=_N;function _D(I){vd=I}function dW(){return vd}var Wl=(I)=>{let{data:G,path:C,errorMaps:N,issueData:Y}=I,Z=[...C,...Y.path||[]],W={...Y,path:Z};if(Y.message!==void 0)return{...Y,path:Z,message:Y.message};let b="",l=N.filter((Q)=>!!Q).slice().reverse();for(let Q of l)b=Q(W,{data:G,defaultError:b}).message;return{...Y,path:Z,message:b}},rD=[];function P(I,G){let C=dW(),N=Wl({issueData:G,data:I.data,path:I.path,errorMaps:[I.common.contextualErrorMap,I.schemaErrorMap,C,C===_N?void 0:_N].filter((Y)=>!!Y)});I.common.issues.push(N)}class FG{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(I,G){let C=[];for(let N of G){if(N.status==="aborted")return bI;if(N.status==="dirty")I.dirty();C.push(N.value)}return{status:I.value,value:C}}static async mergeObjectAsync(I,G){let C=[];for(let N of G){let Y=await N.key,Z=await N.value;C.push({key:Y,value:Z})}return FG.mergeObjectSync(I,C)}static mergeObjectSync(I,G){let C={};for(let N of G){let{key:Y,value:Z}=N;if(Y.status==="aborted")return bI;if(Z.status==="aborted")return bI;if(Y.status==="dirty")I.dirty();if(Z.status==="dirty")I.dirty();if(Y.value!=="__proto__"&&(typeof Z.value<"u"||N.alwaysSet))C[Y.value]=Z.value}return{status:I.value,value:C}}}var bI=Object.freeze({status:"aborted"}),mZ=(I)=>({status:"dirty",value:I}),EG=(I)=>({status:"valid",value:I}),H4=(I)=>I.status==="aborted",w4=(I)=>I.status==="dirty",uY=(I)=>I.status==="valid",cW=(I)=>typeof Promise<"u"&&I instanceof Promise;var e;(function(I){I.errToObj=(G)=>typeof G==="string"?{message:G}:G||{},I.toString=(G)=>typeof G==="string"?G:G?.message})(e||(e={}));class eC{constructor(I,G,C,N){this._cachedPath=[],this.parent=I,this.data=G,this._path=C,this._key=N}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var ud=(I,G)=>{if(uY(G))return{success:!0,data:G.value};else{if(!I.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let C=new PG(I.common.issues);return this._error=C,this._error}}}};function HI(I){if(!I)return{};let{errorMap:G,invalid_type_error:C,required_error:N,description:Y}=I;if(G&&(C||N))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(G)return{errorMap:G,description:Y};return{errorMap:(W,b)=>{let{message:l}=I;if(W.code==="invalid_enum_value")return{message:l??b.defaultError};if(typeof b.data>"u")return{message:l??N??b.defaultError};if(W.code!=="invalid_type")return{message:b.defaultError};return{message:l??C??b.defaultError}},description:Y}}class vI{get description(){return this._def.description}_getType(I){return FN(I.data)}_getOrReturnCtx(I,G){return G||{common:I.parent.common,data:I.data,parsedType:FN(I.data),schemaErrorMap:this._def.errorMap,path:I.path,parent:I.parent}}_processInputParams(I){return{status:new FG,ctx:{common:I.parent.common,data:I.data,parsedType:FN(I.data),schemaErrorMap:this._def.errorMap,path:I.path,parent:I.parent}}}_parseSync(I){let G=this._parse(I);if(cW(G))throw Error("Synchronous parse encountered promise.");return G}_parseAsync(I){let G=this._parse(I);return Promise.resolve(G)}parse(I,G){let C=this.safeParse(I,G);if(C.success)return C.data;throw C.error}safeParse(I,G){let C={common:{issues:[],async:G?.async??!1,contextualErrorMap:G?.errorMap},path:G?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:FN(I)},N=this._parseSync({data:I,path:C.path,parent:C});return ud(C,N)}"~validate"(I){let G={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:FN(I)};if(!this["~standard"].async)try{let C=this._parseSync({data:I,path:[],parent:G});return uY(C)?{value:C.value}:{issues:G.common.issues}}catch(C){if(C?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;G.common={issues:[],async:!0}}return this._parseAsync({data:I,path:[],parent:G}).then((C)=>uY(C)?{value:C.value}:{issues:G.common.issues})}async parseAsync(I,G){let C=await this.safeParseAsync(I,G);if(C.success)return C.data;throw C.error}async safeParseAsync(I,G){let C={common:{issues:[],contextualErrorMap:G?.errorMap,async:!0},path:G?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:FN(I)},N=this._parse({data:I,path:C.path,parent:C}),Y=await(cW(N)?N:Promise.resolve(N));return ud(C,Y)}refine(I,G){let C=(N)=>{if(typeof G==="string"||typeof G>"u")return{message:G};else if(typeof G==="function")return G(N);else return G};return this._refinement((N,Y)=>{let Z=I(N),W=()=>Y.addIssue({code:x.custom,...C(N)});if(typeof Promise<"u"&&Z instanceof Promise)return Z.then((b)=>{if(!b)return W(),!1;else return!0});if(!Z)return W(),!1;else return!0})}refinement(I,G){return this._refinement((C,N)=>{if(!I(C))return N.addIssue(typeof G==="function"?G(C,N):G),!1;else return!0})}_refinement(I){return new IN({schema:this,typeName:QI.ZodEffects,effect:{type:"refinement",refinement:I}})}superRefine(I){return this._refinement(I)}constructor(I){this.spa=this.safeParseAsync,this._def=I,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(G)=>this["~validate"](G)}}optional(){return oC.create(this,this._def)}nullable(){return oN.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rC.create(this)}promise(){return hZ.create(this,this._def)}or(I){return AW.create([this,I],this._def)}and(I){return gW.create(this,I,this._def)}transform(I){return new IN({...HI(this._def),schema:this,typeName:QI.ZodEffects,effect:{type:"transform",transform:I}})}default(I){let G=typeof I==="function"?I:()=>I;return new pW({...HI(this._def),innerType:this,defaultValue:G,typeName:QI.ZodDefault})}brand(){return new c4({typeName:QI.ZodBranded,type:this,...HI(this._def)})}catch(I){let G=typeof I==="function"?I:()=>I;return new EW({...HI(this._def),innerType:this,catchValue:G,typeName:QI.ZodCatch})}describe(I){return new this.constructor({...this._def,description:I})}pipe(I){return Vl.create(this,I)}readonly(){return zW.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var oD=/^c[^\s-]{8,}$/i,eD=/^[0-9a-z]+$/,Iq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Gq=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Cq=/^[a-z0-9_-]{21}$/i,Nq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yq=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Zq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qm,bq=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lq=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qq=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Lq=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,mq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ad="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Xq=new RegExp(`^${Ad}$`);function gd(I){let G="[0-5]\\d";if(I.precision)G=`${G}\\.\\d{${I.precision}}`;else if(I.precision==null)G=`${G}(\\.\\d+)?`;let C=I.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${G})${C}`}function Rq(I){return new RegExp(`^${gd(I)}$`)}function Kd(I){let G=`${Ad}T${gd(I)}`,C=[];if(C.push(I.local?"Z?":"Z"),I.offset)C.push("([+-]\\d{2}:?\\d{2})");return G=`${G}(${C.join("|")})`,new RegExp(`^${G}$`)}function hq(I,G){if((G==="v4"||!G)&&bq.test(I))return!0;if((G==="v6"||!G)&&Qq.test(I))return!0;return!1}function Hq(I,G){if(!Nq.test(I))return!1;try{let[C]=I.split(".");if(!C)return!1;let N=C.replace(/-/g,"+").replace(/_/g,"/").padEnd(C.length+(4-C.length%4)%4,"="),Y=JSON.parse(atob(N));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(G&&Y.alg!==G)return!1;return!0}catch{return!1}}function wq(I,G){if((G==="v4"||!G)&&lq.test(I))return!0;if((G==="v6"||!G)&&Lq.test(I))return!0;return!1}class _C extends vI{_parse(I){if(this._def.coerce)I.data=String(I.data);if(this._getType(I)!==T.string){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_type,expected:T.string,received:Y.parsedType}),bI}let C=new FG,N=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(I.data.length<Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),C.dirty()}else if(Y.kind==="max"){if(I.data.length>Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),C.dirty()}else if(Y.kind==="length"){let Z=I.data.length>Y.value,W=I.data.length<Y.value;if(Z||W){if(N=this._getOrReturnCtx(I,N),Z)P(N,{code:x.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(W)P(N,{code:x.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});C.dirty()}}else if(Y.kind==="email"){if(!Zq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"email",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="emoji"){if(!qm)qm=new RegExp(Wq,"u");if(!qm.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"emoji",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="uuid"){if(!Gq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"uuid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="nanoid"){if(!Cq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"nanoid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="cuid"){if(!oD.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"cuid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="cuid2"){if(!eD.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"cuid2",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="ulid"){if(!Iq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"ulid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="url")try{new URL(I.data)}catch{N=this._getOrReturnCtx(I,N),P(N,{validation:"url",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"regex",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="trim")I.data=I.data.trim();else if(Y.kind==="includes"){if(!I.data.includes(Y.value,Y.position))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),C.dirty()}else if(Y.kind==="toLowerCase")I.data=I.data.toLowerCase();else if(Y.kind==="toUpperCase")I.data=I.data.toUpperCase();else if(Y.kind==="startsWith"){if(!I.data.startsWith(Y.value))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:{startsWith:Y.value},message:Y.message}),C.dirty()}else if(Y.kind==="endsWith"){if(!I.data.endsWith(Y.value))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:{endsWith:Y.value},message:Y.message}),C.dirty()}else if(Y.kind==="datetime"){if(!Kd(Y).test(I.data))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:"datetime",message:Y.message}),C.dirty()}else if(Y.kind==="date"){if(!Xq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:"date",message:Y.message}),C.dirty()}else if(Y.kind==="time"){if(!Rq(Y).test(I.data))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:"time",message:Y.message}),C.dirty()}else if(Y.kind==="duration"){if(!Yq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"duration",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="ip"){if(!hq(I.data,Y.version))N=this._getOrReturnCtx(I,N),P(N,{validation:"ip",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="jwt"){if(!Hq(I.data,Y.alg))N=this._getOrReturnCtx(I,N),P(N,{validation:"jwt",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="cidr"){if(!wq(I.data,Y.version))N=this._getOrReturnCtx(I,N),P(N,{validation:"cidr",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="base64"){if(!mq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"base64",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="base64url"){if(!Vq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"base64url",code:x.invalid_string,message:Y.message}),C.dirty()}else gI.assertNever(Y);return{status:C.value,value:I.data}}_regex(I,G,C){return this.refinement((N)=>I.test(N),{validation:G,code:x.invalid_string,...e.errToObj(C)})}_addCheck(I){return new _C({...this._def,checks:[...this._def.checks,I]})}email(I){return this._addCheck({kind:"email",...e.errToObj(I)})}url(I){return this._addCheck({kind:"url",...e.errToObj(I)})}emoji(I){return this._addCheck({kind:"emoji",...e.errToObj(I)})}uuid(I){return this._addCheck({kind:"uuid",...e.errToObj(I)})}nanoid(I){return this._addCheck({kind:"nanoid",...e.errToObj(I)})}cuid(I){return this._addCheck({kind:"cuid",...e.errToObj(I)})}cuid2(I){return this._addCheck({kind:"cuid2",...e.errToObj(I)})}ulid(I){return this._addCheck({kind:"ulid",...e.errToObj(I)})}base64(I){return this._addCheck({kind:"base64",...e.errToObj(I)})}base64url(I){return this._addCheck({kind:"base64url",...e.errToObj(I)})}jwt(I){return this._addCheck({kind:"jwt",...e.errToObj(I)})}ip(I){return this._addCheck({kind:"ip",...e.errToObj(I)})}cidr(I){return this._addCheck({kind:"cidr",...e.errToObj(I)})}datetime(I){if(typeof I==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:I});return this._addCheck({kind:"datetime",precision:typeof I?.precision>"u"?null:I?.precision,offset:I?.offset??!1,local:I?.local??!1,...e.errToObj(I?.message)})}date(I){return this._addCheck({kind:"date",message:I})}time(I){if(typeof I==="string")return this._addCheck({kind:"time",precision:null,message:I});return this._addCheck({kind:"time",precision:typeof I?.precision>"u"?null:I?.precision,...e.errToObj(I?.message)})}duration(I){return this._addCheck({kind:"duration",...e.errToObj(I)})}regex(I,G){return this._addCheck({kind:"regex",regex:I,...e.errToObj(G)})}includes(I,G){return this._addCheck({kind:"includes",value:I,position:G?.position,...e.errToObj(G?.message)})}startsWith(I,G){return this._addCheck({kind:"startsWith",value:I,...e.errToObj(G)})}endsWith(I,G){return this._addCheck({kind:"endsWith",value:I,...e.errToObj(G)})}min(I,G){return this._addCheck({kind:"min",value:I,...e.errToObj(G)})}max(I,G){return this._addCheck({kind:"max",value:I,...e.errToObj(G)})}length(I,G){return this._addCheck({kind:"length",value:I,...e.errToObj(G)})}nonempty(I){return this.min(1,e.errToObj(I))}trim(){return new _C({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _C({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _C({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((I)=>I.kind==="datetime")}get isDate(){return!!this._def.checks.find((I)=>I.kind==="date")}get isTime(){return!!this._def.checks.find((I)=>I.kind==="time")}get isDuration(){return!!this._def.checks.find((I)=>I.kind==="duration")}get isEmail(){return!!this._def.checks.find((I)=>I.kind==="email")}get isURL(){return!!this._def.checks.find((I)=>I.kind==="url")}get isEmoji(){return!!this._def.checks.find((I)=>I.kind==="emoji")}get isUUID(){return!!this._def.checks.find((I)=>I.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((I)=>I.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((I)=>I.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((I)=>I.kind==="cuid2")}get isULID(){return!!this._def.checks.find((I)=>I.kind==="ulid")}get isIP(){return!!this._def.checks.find((I)=>I.kind==="ip")}get isCIDR(){return!!this._def.checks.find((I)=>I.kind==="cidr")}get isBase64(){return!!this._def.checks.find((I)=>I.kind==="base64")}get isBase64url(){return!!this._def.checks.find((I)=>I.kind==="base64url")}get minLength(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I}get maxLength(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I}}_C.create=(I)=>{return new _C({checks:[],typeName:QI.ZodString,coerce:I?.coerce??!1,...HI(I)})};function dq(I,G){let C=(I.toString().split(".")[1]||"").length,N=(G.toString().split(".")[1]||"").length,Y=C>N?C:N,Z=Number.parseInt(I.toFixed(Y).replace(".","")),W=Number.parseInt(G.toFixed(Y).replace(".",""));return Z%W/10**Y}class AY extends vI{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(I){if(this._def.coerce)I.data=Number(I.data);if(this._getType(I)!==T.number){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_type,expected:T.number,received:Y.parsedType}),bI}let C=void 0,N=new FG;for(let Y of this._def.checks)if(Y.kind==="int"){if(!gI.isInteger(I.data))C=this._getOrReturnCtx(I,C),P(C,{code:x.invalid_type,expected:"integer",received:"float",message:Y.message}),N.dirty()}else if(Y.kind==="min"){if(Y.inclusive?I.data<Y.value:I.data<=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),N.dirty()}else if(Y.kind==="max"){if(Y.inclusive?I.data>Y.value:I.data>=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),N.dirty()}else if(Y.kind==="multipleOf"){if(dq(I.data,Y.value)!==0)C=this._getOrReturnCtx(I,C),P(C,{code:x.not_multiple_of,multipleOf:Y.value,message:Y.message}),N.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(I.data))C=this._getOrReturnCtx(I,C),P(C,{code:x.not_finite,message:Y.message}),N.dirty()}else gI.assertNever(Y);return{status:N.value,value:I.data}}gte(I,G){return this.setLimit("min",I,!0,e.toString(G))}gt(I,G){return this.setLimit("min",I,!1,e.toString(G))}lte(I,G){return this.setLimit("max",I,!0,e.toString(G))}lt(I,G){return this.setLimit("max",I,!1,e.toString(G))}setLimit(I,G,C,N){return new AY({...this._def,checks:[...this._def.checks,{kind:I,value:G,inclusive:C,message:e.toString(N)}]})}_addCheck(I){return new AY({...this._def,checks:[...this._def.checks,I]})}int(I){return this._addCheck({kind:"int",message:e.toString(I)})}positive(I){return this._addCheck({kind:"min",value:0,inclusive:!1,message:e.toString(I)})}negative(I){return this._addCheck({kind:"max",value:0,inclusive:!1,message:e.toString(I)})}nonpositive(I){return this._addCheck({kind:"max",value:0,inclusive:!0,message:e.toString(I)})}nonnegative(I){return this._addCheck({kind:"min",value:0,inclusive:!0,message:e.toString(I)})}multipleOf(I,G){return this._addCheck({kind:"multipleOf",value:I,message:e.toString(G)})}finite(I){return this._addCheck({kind:"finite",message:e.toString(I)})}safe(I){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:e.toString(I)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:e.toString(I)})}get minValue(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I}get maxValue(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I}get isInt(){return!!this._def.checks.find((I)=>I.kind==="int"||I.kind==="multipleOf"&&gI.isInteger(I.value))}get isFinite(){let I=null,G=null;for(let C of this._def.checks)if(C.kind==="finite"||C.kind==="int"||C.kind==="multipleOf")return!0;else if(C.kind==="min"){if(G===null||C.value>G)G=C.value}else if(C.kind==="max"){if(I===null||C.value<I)I=C.value}return Number.isFinite(G)&&Number.isFinite(I)}}AY.create=(I)=>{return new AY({checks:[],typeName:QI.ZodNumber,coerce:I?.coerce||!1,...HI(I)})};class gY extends vI{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(I){if(this._def.coerce)try{I.data=BigInt(I.data)}catch{return this._getInvalidInput(I)}if(this._getType(I)!==T.bigint)return this._getInvalidInput(I);let C=void 0,N=new FG;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?I.data<Y.value:I.data<=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),N.dirty()}else if(Y.kind==="max"){if(Y.inclusive?I.data>Y.value:I.data>=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),N.dirty()}else if(Y.kind==="multipleOf"){if(I.data%Y.value!==BigInt(0))C=this._getOrReturnCtx(I,C),P(C,{code:x.not_multiple_of,multipleOf:Y.value,message:Y.message}),N.dirty()}else gI.assertNever(Y);return{status:N.value,value:I.data}}_getInvalidInput(I){let G=this._getOrReturnCtx(I);return P(G,{code:x.invalid_type,expected:T.bigint,received:G.parsedType}),bI}gte(I,G){return this.setLimit("min",I,!0,e.toString(G))}gt(I,G){return this.setLimit("min",I,!1,e.toString(G))}lte(I,G){return this.setLimit("max",I,!0,e.toString(G))}lt(I,G){return this.setLimit("max",I,!1,e.toString(G))}setLimit(I,G,C,N){return new gY({...this._def,checks:[...this._def.checks,{kind:I,value:G,inclusive:C,message:e.toString(N)}]})}_addCheck(I){return new gY({...this._def,checks:[...this._def.checks,I]})}positive(I){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:e.toString(I)})}negative(I){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:e.toString(I)})}nonpositive(I){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:e.toString(I)})}nonnegative(I){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:e.toString(I)})}multipleOf(I,G){return this._addCheck({kind:"multipleOf",value:I,message:e.toString(G)})}get minValue(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I}get maxValue(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I}}gY.create=(I)=>{return new gY({checks:[],typeName:QI.ZodBigInt,coerce:I?.coerce??!1,...HI(I)})};class vW extends vI{_parse(I){if(this._def.coerce)I.data=Boolean(I.data);if(this._getType(I)!==T.boolean){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.boolean,received:C.parsedType}),bI}return EG(I.data)}}vW.create=(I)=>{return new vW({typeName:QI.ZodBoolean,coerce:I?.coerce||!1,...HI(I)})};class VZ extends vI{_parse(I){if(this._def.coerce)I.data=new Date(I.data);if(this._getType(I)!==T.date){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_type,expected:T.date,received:Y.parsedType}),bI}if(Number.isNaN(I.data.getTime())){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_date}),bI}let C=new FG,N=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(I.data.getTime()<Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),C.dirty()}else if(Y.kind==="max"){if(I.data.getTime()>Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),C.dirty()}else gI.assertNever(Y);return{status:C.value,value:new Date(I.data.getTime())}}_addCheck(I){return new VZ({...this._def,checks:[...this._def.checks,I]})}min(I,G){return this._addCheck({kind:"min",value:I.getTime(),message:e.toString(G)})}max(I,G){return this._addCheck({kind:"max",value:I.getTime(),message:e.toString(G)})}get minDate(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I!=null?new Date(I):null}get maxDate(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I!=null?new Date(I):null}}VZ.create=(I)=>{return new VZ({checks:[],coerce:I?.coerce||!1,typeName:QI.ZodDate,...HI(I)})};class bl extends vI{_parse(I){if(this._getType(I)!==T.symbol){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.symbol,received:C.parsedType}),bI}return EG(I.data)}}bl.create=(I)=>{return new bl({typeName:QI.ZodSymbol,...HI(I)})};class uW extends vI{_parse(I){if(this._getType(I)!==T.undefined){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.undefined,received:C.parsedType}),bI}return EG(I.data)}}uW.create=(I)=>{return new uW({typeName:QI.ZodUndefined,...HI(I)})};class JW extends vI{_parse(I){if(this._getType(I)!==T.null){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.null,received:C.parsedType}),bI}return EG(I.data)}}JW.create=(I)=>{return new JW({typeName:QI.ZodNull,...HI(I)})};class XZ extends vI{constructor(){super(...arguments);this._any=!0}_parse(I){return EG(I.data)}}XZ.create=(I)=>{return new XZ({typeName:QI.ZodAny,...HI(I)})};class JY extends vI{constructor(){super(...arguments);this._unknown=!0}_parse(I){return EG(I.data)}}JY.create=(I)=>{return new JY({typeName:QI.ZodUnknown,...HI(I)})};class vN extends vI{_parse(I){let G=this._getOrReturnCtx(I);return P(G,{code:x.invalid_type,expected:T.never,received:G.parsedType}),bI}}vN.create=(I)=>{return new vN({typeName:QI.ZodNever,...HI(I)})};class ll extends vI{_parse(I){if(this._getType(I)!==T.undefined){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.void,received:C.parsedType}),bI}return EG(I.data)}}ll.create=(I)=>{return new ll({typeName:QI.ZodVoid,...HI(I)})};class rC extends vI{_parse(I){let{ctx:G,status:C}=this._processInputParams(I),N=this._def;if(G.parsedType!==T.array)return P(G,{code:x.invalid_type,expected:T.array,received:G.parsedType}),bI;if(N.exactLength!==null){let Z=G.data.length>N.exactLength.value,W=G.data.length<N.exactLength.value;if(Z||W)P(G,{code:Z?x.too_big:x.too_small,minimum:W?N.exactLength.value:void 0,maximum:Z?N.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:N.exactLength.message}),C.dirty()}if(N.minLength!==null){if(G.data.length<N.minLength.value)P(G,{code:x.too_small,minimum:N.minLength.value,type:"array",inclusive:!0,exact:!1,message:N.minLength.message}),C.dirty()}if(N.maxLength!==null){if(G.data.length>N.maxLength.value)P(G,{code:x.too_big,maximum:N.maxLength.value,type:"array",inclusive:!0,exact:!1,message:N.maxLength.message}),C.dirty()}if(G.common.async)return Promise.all([...G.data].map((Z,W)=>{return N.type._parseAsync(new eC(G,Z,G.path,W))})).then((Z)=>{return FG.mergeArray(C,Z)});let Y=[...G.data].map((Z,W)=>{return N.type._parseSync(new eC(G,Z,G.path,W))});return FG.mergeArray(C,Y)}get element(){return this._def.type}min(I,G){return new rC({...this._def,minLength:{value:I,message:e.toString(G)}})}max(I,G){return new rC({...this._def,maxLength:{value:I,message:e.toString(G)}})}length(I,G){return new rC({...this._def,exactLength:{value:I,message:e.toString(G)}})}nonempty(I){return this.min(1,I)}}rC.create=(I,G)=>{return new rC({type:I,minLength:null,maxLength:null,exactLength:null,typeName:QI.ZodArray,...HI(G)})};function OW(I){if(I instanceof GG){let G={};for(let C in I.shape){let N=I.shape[C];G[C]=oC.create(OW(N))}return new GG({...I._def,shape:()=>G})}else if(I instanceof rC)return new rC({...I._def,type:OW(I.element)});else if(I instanceof oC)return oC.create(OW(I.unwrap()));else if(I instanceof oN)return oN.create(OW(I.unwrap()));else if(I instanceof uN)return uN.create(I.items.map((G)=>OW(G)));else return I}class GG extends vI{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let I=this._def.shape(),G=gI.objectKeys(I);return this._cached={shape:I,keys:G},this._cached}_parse(I){if(this._getType(I)!==T.object){let l=this._getOrReturnCtx(I);return P(l,{code:x.invalid_type,expected:T.object,received:l.parsedType}),bI}let{status:C,ctx:N}=this._processInputParams(I),{shape:Y,keys:Z}=this._getCached(),W=[];if(!(this._def.catchall instanceof vN&&this._def.unknownKeys==="strip")){for(let l in N.data)if(!Z.includes(l))W.push(l)}let b=[];for(let l of Z){let Q=Y[l],L=N.data[l];b.push({key:{status:"valid",value:l},value:Q._parse(new eC(N,L,N.path,l)),alwaysSet:l in N.data})}if(this._def.catchall instanceof vN){let l=this._def.unknownKeys;if(l==="passthrough")for(let Q of W)b.push({key:{status:"valid",value:Q},value:{status:"valid",value:N.data[Q]}});else if(l==="strict"){if(W.length>0)P(N,{code:x.unrecognized_keys,keys:W}),C.dirty()}else if(l==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let Q of W){let L=N.data[Q];b.push({key:{status:"valid",value:Q},value:l._parse(new eC(N,L,N.path,Q)),alwaysSet:Q in N.data})}}if(N.common.async)return Promise.resolve().then(async()=>{let l=[];for(let Q of b){let L=await Q.key,m=await Q.value;l.push({key:L,value:m,alwaysSet:Q.alwaysSet})}return l}).then((l)=>{return FG.mergeObjectSync(C,l)});else return FG.mergeObjectSync(C,b)}get shape(){return this._def.shape()}strict(I){return e.errToObj,new GG({...this._def,unknownKeys:"strict",...I!==void 0?{errorMap:(G,C)=>{let N=this._def.errorMap?.(G,C).message??C.defaultError;if(G.code==="unrecognized_keys")return{message:e.errToObj(I).message??N};return{message:N}}}:{}})}strip(){return new GG({...this._def,unknownKeys:"strip"})}passthrough(){return new GG({...this._def,unknownKeys:"passthrough"})}extend(I){return new GG({...this._def,shape:()=>({...this._def.shape(),...I})})}merge(I){return new GG({unknownKeys:I._def.unknownKeys,catchall:I._def.catchall,shape:()=>({...this._def.shape(),...I._def.shape()}),typeName:QI.ZodObject})}setKey(I,G){return this.augment({[I]:G})}catchall(I){return new GG({...this._def,catchall:I})}pick(I){let G={};for(let C of gI.objectKeys(I))if(I[C]&&this.shape[C])G[C]=this.shape[C];return new GG({...this._def,shape:()=>G})}omit(I){let G={};for(let C of gI.objectKeys(this.shape))if(!I[C])G[C]=this.shape[C];return new GG({...this._def,shape:()=>G})}deepPartial(){return OW(this)}partial(I){let G={};for(let C of gI.objectKeys(this.shape)){let N=this.shape[C];if(I&&!I[C])G[C]=N;else G[C]=N.optional()}return new GG({...this._def,shape:()=>G})}required(I){let G={};for(let C of gI.objectKeys(this.shape))if(I&&!I[C])G[C]=this.shape[C];else{let Y=this.shape[C];while(Y instanceof oC)Y=Y._def.innerType;G[C]=Y}return new GG({...this._def,shape:()=>G})}keyof(){return kd(gI.objectKeys(this.shape))}}GG.create=(I,G)=>{return new GG({shape:()=>I,unknownKeys:"strip",catchall:vN.create(),typeName:QI.ZodObject,...HI(G)})};GG.strictCreate=(I,G)=>{return new GG({shape:()=>I,unknownKeys:"strict",catchall:vN.create(),typeName:QI.ZodObject,...HI(G)})};GG.lazycreate=(I,G)=>{return new GG({shape:I,unknownKeys:"strip",catchall:vN.create(),typeName:QI.ZodObject,...HI(G)})};class AW extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C=this._def.options;function N(Y){for(let W of Y)if(W.result.status==="valid")return W.result;for(let W of Y)if(W.result.status==="dirty")return G.common.issues.push(...W.ctx.common.issues),W.result;let Z=Y.map((W)=>new PG(W.ctx.common.issues));return P(G,{code:x.invalid_union,unionErrors:Z}),bI}if(G.common.async)return Promise.all(C.map(async(Y)=>{let Z={...G,common:{...G.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:G.data,path:G.path,parent:Z}),ctx:Z}})).then(N);else{let Y=void 0,Z=[];for(let b of C){let l={...G,common:{...G.common,issues:[]},parent:null},Q=b._parseSync({data:G.data,path:G.path,parent:l});if(Q.status==="valid")return Q;else if(Q.status==="dirty"&&!Y)Y={result:Q,ctx:l};if(l.common.issues.length)Z.push(l.common.issues)}if(Y)return G.common.issues.push(...Y.ctx.common.issues),Y.result;let W=Z.map((b)=>new PG(b));return P(G,{code:x.invalid_union,unionErrors:W}),bI}}get options(){return this._def.options}}AW.create=(I,G)=>{return new AW({options:I,typeName:QI.ZodUnion,...HI(G)})};var rN=(I)=>{if(I instanceof KW)return rN(I.schema);else if(I instanceof IN)return rN(I.innerType());else if(I instanceof kW)return[I.value];else if(I instanceof KY)return I.options;else if(I instanceof yW)return gI.objectValues(I.enum);else if(I instanceof pW)return rN(I._def.innerType);else if(I instanceof uW)return[void 0];else if(I instanceof JW)return[null];else if(I instanceof oC)return[void 0,...rN(I.unwrap())];else if(I instanceof oN)return[null,...rN(I.unwrap())];else if(I instanceof c4)return rN(I.unwrap());else if(I instanceof zW)return rN(I.unwrap());else if(I instanceof EW)return rN(I._def.innerType);else return[]};class d4 extends vI{_parse(I){let{ctx:G}=this._processInputParams(I);if(G.parsedType!==T.object)return P(G,{code:x.invalid_type,expected:T.object,received:G.parsedType}),bI;let C=this.discriminator,N=G.data[C],Y=this.optionsMap.get(N);if(!Y)return P(G,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[C]}),bI;if(G.common.async)return Y._parseAsync({data:G.data,path:G.path,parent:G});else return Y._parseSync({data:G.data,path:G.path,parent:G})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(I,G,C){let N=new Map;for(let Y of G){let Z=rN(Y.shape[I]);if(!Z.length)throw Error(`A discriminator value for key \`${I}\` could not be extracted from all schema options`);for(let W of Z){if(N.has(W))throw Error(`Discriminator property ${String(I)} has duplicate value ${String(W)}`);N.set(W,Y)}}return new d4({typeName:QI.ZodDiscriminatedUnion,discriminator:I,options:G,optionsMap:N,...HI(C)})}}function Um(I,G){let C=FN(I),N=FN(G);if(I===G)return{valid:!0,data:I};else if(C===T.object&&N===T.object){let Y=gI.objectKeys(G),Z=gI.objectKeys(I).filter((b)=>Y.indexOf(b)!==-1),W={...I,...G};for(let b of Z){let l=Um(I[b],G[b]);if(!l.valid)return{valid:!1};W[b]=l.data}return{valid:!0,data:W}}else if(C===T.array&&N===T.array){if(I.length!==G.length)return{valid:!1};let Y=[];for(let Z=0;Z<I.length;Z++){let W=I[Z],b=G[Z],l=Um(W,b);if(!l.valid)return{valid:!1};Y.push(l.data)}return{valid:!0,data:Y}}else if(C===T.date&&N===T.date&&+I===+G)return{valid:!0,data:I};else return{valid:!1}}class gW extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I),N=(Y,Z)=>{if(H4(Y)||H4(Z))return bI;let W=Um(Y.value,Z.value);if(!W.valid)return P(C,{code:x.invalid_intersection_types}),bI;if(w4(Y)||w4(Z))G.dirty();return{status:G.value,value:W.data}};if(C.common.async)return Promise.all([this._def.left._parseAsync({data:C.data,path:C.path,parent:C}),this._def.right._parseAsync({data:C.data,path:C.path,parent:C})]).then(([Y,Z])=>N(Y,Z));else return N(this._def.left._parseSync({data:C.data,path:C.path,parent:C}),this._def.right._parseSync({data:C.data,path:C.path,parent:C}))}}gW.create=(I,G,C)=>{return new gW({left:I,right:G,typeName:QI.ZodIntersection,...HI(C)})};class uN extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.array)return P(C,{code:x.invalid_type,expected:T.array,received:C.parsedType}),bI;if(C.data.length<this._def.items.length)return P(C,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bI;if(!this._def.rest&&C.data.length>this._def.items.length)P(C,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G.dirty();let Y=[...C.data].map((Z,W)=>{let b=this._def.items[W]||this._def.rest;if(!b)return null;return b._parse(new eC(C,Z,C.path,W))}).filter((Z)=>!!Z);if(C.common.async)return Promise.all(Y).then((Z)=>{return FG.mergeArray(G,Z)});else return FG.mergeArray(G,Y)}get items(){return this._def.items}rest(I){return new uN({...this._def,rest:I})}}uN.create=(I,G)=>{if(!Array.isArray(I))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new uN({items:I,typeName:QI.ZodTuple,rest:null,...HI(G)})};class Ql extends vI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.object)return P(C,{code:x.invalid_type,expected:T.object,received:C.parsedType}),bI;let N=[],Y=this._def.keyType,Z=this._def.valueType;for(let W in C.data)N.push({key:Y._parse(new eC(C,W,C.path,W)),value:Z._parse(new eC(C,C.data[W],C.path,W)),alwaysSet:W in C.data});if(C.common.async)return FG.mergeObjectAsync(G,N);else return FG.mergeObjectSync(G,N)}get element(){return this._def.valueType}static create(I,G,C){if(G instanceof vI)return new Ql({keyType:I,valueType:G,typeName:QI.ZodRecord,...HI(C)});return new Ql({keyType:_C.create(),valueType:I,typeName:QI.ZodRecord,...HI(G)})}}class Ll extends vI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.map)return P(C,{code:x.invalid_type,expected:T.map,received:C.parsedType}),bI;let N=this._def.keyType,Y=this._def.valueType,Z=[...C.data.entries()].map(([W,b],l)=>{return{key:N._parse(new eC(C,W,C.path,[l,"key"])),value:Y._parse(new eC(C,b,C.path,[l,"value"]))}});if(C.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let b of Z){let l=await b.key,Q=await b.value;if(l.status==="aborted"||Q.status==="aborted")return bI;if(l.status==="dirty"||Q.status==="dirty")G.dirty();W.set(l.value,Q.value)}return{status:G.value,value:W}})}else{let W=new Map;for(let b of Z){let{key:l,value:Q}=b;if(l.status==="aborted"||Q.status==="aborted")return bI;if(l.status==="dirty"||Q.status==="dirty")G.dirty();W.set(l.value,Q.value)}return{status:G.value,value:W}}}}Ll.create=(I,G,C)=>{return new Ll({valueType:G,keyType:I,typeName:QI.ZodMap,...HI(C)})};class RZ extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.set)return P(C,{code:x.invalid_type,expected:T.set,received:C.parsedType}),bI;let N=this._def;if(N.minSize!==null){if(C.data.size<N.minSize.value)P(C,{code:x.too_small,minimum:N.minSize.value,type:"set",inclusive:!0,exact:!1,message:N.minSize.message}),G.dirty()}if(N.maxSize!==null){if(C.data.size>N.maxSize.value)P(C,{code:x.too_big,maximum:N.maxSize.value,type:"set",inclusive:!0,exact:!1,message:N.maxSize.message}),G.dirty()}let Y=this._def.valueType;function Z(b){let l=new Set;for(let Q of b){if(Q.status==="aborted")return bI;if(Q.status==="dirty")G.dirty();l.add(Q.value)}return{status:G.value,value:l}}let W=[...C.data.values()].map((b,l)=>Y._parse(new eC(C,b,C.path,l)));if(C.common.async)return Promise.all(W).then((b)=>Z(b));else return Z(W)}min(I,G){return new RZ({...this._def,minSize:{value:I,message:e.toString(G)}})}max(I,G){return new RZ({...this._def,maxSize:{value:I,message:e.toString(G)}})}size(I,G){return this.min(I,G).max(I,G)}nonempty(I){return this.min(1,I)}}RZ.create=(I,G)=>{return new RZ({valueType:I,minSize:null,maxSize:null,typeName:QI.ZodSet,...HI(G)})};class FW extends vI{constructor(){super(...arguments);this.validate=this.implement}_parse(I){let{ctx:G}=this._processInputParams(I);if(G.parsedType!==T.function)return P(G,{code:x.invalid_type,expected:T.function,received:G.parsedType}),bI;function C(W,b){return Wl({data:W,path:G.path,errorMaps:[G.common.contextualErrorMap,G.schemaErrorMap,dW(),_N].filter((l)=>!!l),issueData:{code:x.invalid_arguments,argumentsError:b}})}function N(W,b){return Wl({data:W,path:G.path,errorMaps:[G.common.contextualErrorMap,G.schemaErrorMap,dW(),_N].filter((l)=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:b}})}let Y={errorMap:G.common.contextualErrorMap},Z=G.data;if(this._def.returns instanceof hZ){let W=this;return EG(async function(...b){let l=new PG([]),Q=await W._def.args.parseAsync(b,Y).catch((V)=>{throw l.addIssue(C(b,V)),l}),L=await Reflect.apply(Z,this,Q);return await W._def.returns._def.type.parseAsync(L,Y).catch((V)=>{throw l.addIssue(N(L,V)),l})})}else{let W=this;return EG(function(...b){let l=W._def.args.safeParse(b,Y);if(!l.success)throw new PG([C(b,l.error)]);let Q=Reflect.apply(Z,this,l.data),L=W._def.returns.safeParse(Q,Y);if(!L.success)throw new PG([N(Q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...I){return new FW({...this._def,args:uN.create(I).rest(JY.create())})}returns(I){return new FW({...this._def,returns:I})}implement(I){return this.parse(I)}strictImplement(I){return this.parse(I)}static create(I,G,C){return new FW({args:I?I:uN.create([]).rest(JY.create()),returns:G||JY.create(),typeName:QI.ZodFunction,...HI(C)})}}class KW extends vI{get schema(){return this._def.getter()}_parse(I){let{ctx:G}=this._processInputParams(I);return this._def.getter()._parse({data:G.data,path:G.path,parent:G})}}KW.create=(I,G)=>{return new KW({getter:I,typeName:QI.ZodLazy,...HI(G)})};class kW extends vI{_parse(I){if(I.data!==this._def.value){let G=this._getOrReturnCtx(I);return P(G,{received:G.data,code:x.invalid_literal,expected:this._def.value}),bI}return{status:"valid",value:I.data}}get value(){return this._def.value}}kW.create=(I,G)=>{return new kW({value:I,typeName:QI.ZodLiteral,...HI(G)})};function kd(I,G){return new KY({values:I,typeName:QI.ZodEnum,...HI(G)})}class KY extends vI{_parse(I){if(typeof I.data!=="string"){let G=this._getOrReturnCtx(I),C=this._def.values;return P(G,{expected:gI.joinValues(C),received:G.parsedType,code:x.invalid_type}),bI}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(I.data)){let G=this._getOrReturnCtx(I),C=this._def.values;return P(G,{received:G.data,code:x.invalid_enum_value,options:C}),bI}return EG(I.data)}get options(){return this._def.values}get enum(){let I={};for(let G of this._def.values)I[G]=G;return I}get Values(){let I={};for(let G of this._def.values)I[G]=G;return I}get Enum(){let I={};for(let G of this._def.values)I[G]=G;return I}extract(I,G=this._def){return KY.create(I,{...this._def,...G})}exclude(I,G=this._def){return KY.create(this.options.filter((C)=>!I.includes(C)),{...this._def,...G})}}KY.create=kd;class yW extends vI{_parse(I){let G=gI.getValidEnumValues(this._def.values),C=this._getOrReturnCtx(I);if(C.parsedType!==T.string&&C.parsedType!==T.number){let N=gI.objectValues(G);return P(C,{expected:gI.joinValues(N),received:C.parsedType,code:x.invalid_type}),bI}if(!this._cache)this._cache=new Set(gI.getValidEnumValues(this._def.values));if(!this._cache.has(I.data)){let N=gI.objectValues(G);return P(C,{received:C.data,code:x.invalid_enum_value,options:N}),bI}return EG(I.data)}get enum(){return this._def.values}}yW.create=(I,G)=>{return new yW({values:I,typeName:QI.ZodNativeEnum,...HI(G)})};class hZ extends vI{unwrap(){return this._def.type}_parse(I){let{ctx:G}=this._processInputParams(I);if(G.parsedType!==T.promise&&G.common.async===!1)return P(G,{code:x.invalid_type,expected:T.promise,received:G.parsedType}),bI;let C=G.parsedType===T.promise?G.data:Promise.resolve(G.data);return EG(C.then((N)=>{return this._def.type.parseAsync(N,{path:G.path,errorMap:G.common.contextualErrorMap})}))}}hZ.create=(I,G)=>{return new hZ({type:I,typeName:QI.ZodPromise,...HI(G)})};class IN extends vI{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===QI.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(I){let{status:G,ctx:C}=this._processInputParams(I),N=this._def.effect||null,Y={addIssue:(Z)=>{if(P(C,Z),Z.fatal)G.abort();else G.dirty()},get path(){return C.path}};if(Y.addIssue=Y.addIssue.bind(Y),N.type==="preprocess"){let Z=N.transform(C.data,Y);if(C.common.async)return Promise.resolve(Z).then(async(W)=>{if(G.value==="aborted")return bI;let b=await this._def.schema._parseAsync({data:W,path:C.path,parent:C});if(b.status==="aborted")return bI;if(b.status==="dirty")return mZ(b.value);if(G.value==="dirty")return mZ(b.value);return b});else{if(G.value==="aborted")return bI;let W=this._def.schema._parseSync({data:Z,path:C.path,parent:C});if(W.status==="aborted")return bI;if(W.status==="dirty")return mZ(W.value);if(G.value==="dirty")return mZ(W.value);return W}}if(N.type==="refinement"){let Z=(W)=>{let b=N.refinement(W,Y);if(C.common.async)return Promise.resolve(b);if(b instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if(C.common.async===!1){let W=this._def.schema._parseSync({data:C.data,path:C.path,parent:C});if(W.status==="aborted")return bI;if(W.status==="dirty")G.dirty();return Z(W.value),{status:G.value,value:W.value}}else return this._def.schema._parseAsync({data:C.data,path:C.path,parent:C}).then((W)=>{if(W.status==="aborted")return bI;if(W.status==="dirty")G.dirty();return Z(W.value).then(()=>{return{status:G.value,value:W.value}})})}if(N.type==="transform")if(C.common.async===!1){let Z=this._def.schema._parseSync({data:C.data,path:C.path,parent:C});if(!uY(Z))return bI;let W=N.transform(Z.value,Y);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:G.value,value:W}}else return this._def.schema._parseAsync({data:C.data,path:C.path,parent:C}).then((Z)=>{if(!uY(Z))return bI;return Promise.resolve(N.transform(Z.value,Y)).then((W)=>({status:G.value,value:W}))});gI.assertNever(N)}}IN.create=(I,G,C)=>{return new IN({schema:I,typeName:QI.ZodEffects,effect:G,...HI(C)})};IN.createWithPreprocess=(I,G,C)=>{return new IN({schema:G,effect:{type:"preprocess",transform:I},typeName:QI.ZodEffects,...HI(C)})};class oC extends vI{_parse(I){if(this._getType(I)===T.undefined)return EG(void 0);return this._def.innerType._parse(I)}unwrap(){return this._def.innerType}}oC.create=(I,G)=>{return new oC({innerType:I,typeName:QI.ZodOptional,...HI(G)})};class oN extends vI{_parse(I){if(this._getType(I)===T.null)return EG(null);return this._def.innerType._parse(I)}unwrap(){return this._def.innerType}}oN.create=(I,G)=>{return new oN({innerType:I,typeName:QI.ZodNullable,...HI(G)})};class pW extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C=G.data;if(G.parsedType===T.undefined)C=this._def.defaultValue();return this._def.innerType._parse({data:C,path:G.path,parent:G})}removeDefault(){return this._def.innerType}}pW.create=(I,G)=>{return new pW({innerType:I,typeName:QI.ZodDefault,defaultValue:typeof G.default==="function"?G.default:()=>G.default,...HI(G)})};class EW extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C={...G,common:{...G.common,issues:[]}},N=this._def.innerType._parse({data:C.data,path:C.path,parent:{...C}});if(cW(N))return N.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new PG(C.common.issues)},input:C.data})}});else return{status:"valid",value:N.status==="valid"?N.value:this._def.catchValue({get error(){return new PG(C.common.issues)},input:C.data})}}removeCatch(){return this._def.innerType}}EW.create=(I,G)=>{return new EW({innerType:I,typeName:QI.ZodCatch,catchValue:typeof G.catch==="function"?G.catch:()=>G.catch,...HI(G)})};class ml extends vI{_parse(I){if(this._getType(I)!==T.nan){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.nan,received:C.parsedType}),bI}return{status:"valid",value:I.data}}}ml.create=(I)=>{return new ml({typeName:QI.ZodNaN,...HI(I)})};var cq=Symbol("zod_brand");class c4 extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C=G.data;return this._def.type._parse({data:C,path:G.path,parent:G})}unwrap(){return this._def.type}}class Vl extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:C.data,path:C.path,parent:C});if(Y.status==="aborted")return bI;if(Y.status==="dirty")return G.dirty(),mZ(Y.value);else return this._def.out._parseAsync({data:Y.value,path:C.path,parent:C})})();else{let N=this._def.in._parseSync({data:C.data,path:C.path,parent:C});if(N.status==="aborted")return bI;if(N.status==="dirty")return G.dirty(),{status:"dirty",value:N.value};else return this._def.out._parseSync({data:N.value,path:C.path,parent:C})}}static create(I,G){return new Vl({in:I,out:G,typeName:QI.ZodPipeline})}}class zW extends vI{_parse(I){let G=this._def.innerType._parse(I),C=(N)=>{if(uY(N))N.value=Object.freeze(N.value);return N};return cW(G)?G.then((N)=>C(N)):C(G)}unwrap(){return this._def.innerType}}zW.create=(I,G)=>{return new zW({innerType:I,typeName:QI.ZodReadonly,...HI(G)})};function Jd(I,G){let C=typeof I==="function"?I(G):typeof I==="string"?{message:I}:I;return typeof C==="string"?{message:C}:C}function yd(I,G={},C){if(I)return XZ.create().superRefine((N,Y)=>{let Z=I(N);if(Z instanceof Promise)return Z.then((W)=>{if(!W){let b=Jd(G,N),l=b.fatal??C??!0;Y.addIssue({code:"custom",...b,fatal:l})}});if(!Z){let W=Jd(G,N),b=W.fatal??C??!0;Y.addIssue({code:"custom",...W,fatal:b})}return});return XZ.create()}var Oq={object:GG.lazycreate},QI;(function(I){I.ZodString="ZodString",I.ZodNumber="ZodNumber",I.ZodNaN="ZodNaN",I.ZodBigInt="ZodBigInt",I.ZodBoolean="ZodBoolean",I.ZodDate="ZodDate",I.ZodSymbol="ZodSymbol",I.ZodUndefined="ZodUndefined",I.ZodNull="ZodNull",I.ZodAny="ZodAny",I.ZodUnknown="ZodUnknown",I.ZodNever="ZodNever",I.ZodVoid="ZodVoid",I.ZodArray="ZodArray",I.ZodObject="ZodObject",I.ZodUnion="ZodUnion",I.ZodDiscriminatedUnion="ZodDiscriminatedUnion",I.ZodIntersection="ZodIntersection",I.ZodTuple="ZodTuple",I.ZodRecord="ZodRecord",I.ZodMap="ZodMap",I.ZodSet="ZodSet",I.ZodFunction="ZodFunction",I.ZodLazy="ZodLazy",I.ZodLiteral="ZodLiteral",I.ZodEnum="ZodEnum",I.ZodEffects="ZodEffects",I.ZodNativeEnum="ZodNativeEnum",I.ZodOptional="ZodOptional",I.ZodNullable="ZodNullable",I.ZodDefault="ZodDefault",I.ZodCatch="ZodCatch",I.ZodPromise="ZodPromise",I.ZodBranded="ZodBranded",I.ZodPipeline="ZodPipeline",I.ZodReadonly="ZodReadonly"})(QI||(QI={}));var Fq=(I,G={message:`Input not instance of ${I.name}`})=>yd((C)=>C instanceof I,G),pd=_C.create,Ed=AY.create,vq=ml.create,uq=gY.create,zd=vW.create,Jq=VZ.create,Aq=bl.create,gq=uW.create,Kq=JW.create,kq=XZ.create,yq=JY.create,pq=vN.create,Eq=ll.create,zq=rC.create,Dq=GG.create,qq=GG.strictCreate,Uq=AW.create,jq=d4.create,Bq=gW.create,aq=uN.create,xq=Ql.create,Mq=Ll.create,Sq=RZ.create,nq=FW.create,Tq=KW.create,sq=kW.create,iq=KY.create,Pq=yW.create,fq=hZ.create,$q=IN.create,tq=oC.create,_q=oN.create,rq=IN.createWithPreprocess,oq=Vl.create,eq=()=>pd().optional(),IU=()=>Ed().optional(),GU=()=>zd().optional(),CU={string:(I)=>_C.create({...I,coerce:!0}),number:(I)=>AY.create({...I,coerce:!0}),boolean:(I)=>vW.create({...I,coerce:!0}),bigint:(I)=>gY.create({...I,coerce:!0}),date:(I)=>VZ.create({...I,coerce:!0})};var NU=bI;import{createHash as YU}from"crypto";var Dd={debug:0,info:1,warn:2,error:3},ZU="info",jm=ZU;function Xl(I){jm=I}function qd(){return jm}function a(I){return YU("sha256").update("kiro-provider-audit-v1\x00").update(I).digest("hex").slice(0,16)}function y(I,G,C={}){if(Dd[I]<Dd[jm])return;let N=Object.fromEntries(Object.entries(C).filter((Y)=>Y[1]!==void 0));console.error(JSON.stringify({timestamp:new Date().toISOString(),level:I,event:G,...N}))}import{existsSync as WU}from"fs";import{homedir as Ud}from"os";import{posix as bU,win32 as lU}from"path";function Bm(I){return I===void 0||I.trim().length===0?void 0:I}function eN(I,...G){return I==="win32"?lU.join(...G):bU.join(...G)}function IY(I={}){let G=I.env??process.env,C=I.platform??process.platform,N=I.homeDirectory??Ud();return C==="win32"?Bm(G.APPDATA)??eN(C,N,"AppData","Roaming"):Bm(G.XDG_CONFIG_HOME)??eN(C,N,".config")}function QU(I={}){let G=I.env??process.env,C=I.platform??process.platform,N=I.homeDirectory??Ud();return Bm(G.XDG_CONFIG_HOME)??eN(C,N,".config")}function jd(I={}){let G=I.exists??WU,C=I.platform??process.platform,N=eN(C,IY(I),"kiro-provider","config.json");if(C!=="win32")return N;let Y=eN(C,QU(I),"kiro-provider","config.json");if(Y!==N&&!G(N)&&G(Y))return Y;return N}var O4=w.enum(["low","medium","high","xhigh","max"]),kC=w.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var LU=w.array(w.string()).transform((I)=>I.map((G)=>G.trim()).filter((G)=>G.length>0)).refine((I)=>I.length>0,{message:"api_keys must contain at least one non-empty key"}),mU=w.preprocess((I)=>typeof I==="string"&&I.trim().length===0?null:I,w.string().trim().refine((I)=>URL.canParse(I),{message:"proxy_url must be a valid URL"}).refine((I)=>{if(!URL.canParse(I))return!1;let G=new URL(I).protocol;return G==="http:"||G==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),am=w.preprocess((I)=>typeof I==="string"&&I.trim().length===0?null:I,w.string().trim().min(1).nullable()).default(null),F4=w.object({host:w.string().trim().min(1).default("127.0.0.1"),port:w.number().int().min(0).max(65535).default(8787),api_keys:LU,enable_legacy_chat_completions:w.boolean().default(!1),protocol_projection_mode:w.enum(["v3-auto","safe","native-context-safe","legacy-user-prefix"]).default("v3-auto"),responses_fidelity_mode:w.enum(["compatible","strict"]).default("compatible"),responses_instruction_lift:w.enum(["auto","off","experimental"]).default("auto"),responses_native_tool_bridge:w.enum(["auto","off","experimental"]).default("auto"),session_affinity_mode:w.enum(["explicit-only","legacy-initial-input"]).default("explicit-only"),kiro_prompt_cache_mode:w.enum(["server-auto","explicit-checkpoints","off"]).default("server-auto"),proxy_url:mU,sdk_http_keep_alive:w.boolean().default(!1),enforce_single_instance:w.boolean().default(!0),instance_lock_path:am,runtime_endpoint_mode:w.enum(["legacy-q","kiro-runtime"]).default("kiro-runtime"),dynamic_model_catalog:w.boolean().default(!0),model_catalog_ttl_ms:w.number().int().min(1).max(2147483647).default(900000),model_catalog_stale_ttl_ms:w.number().int().min(1).max(2147483647).default(86400000),model_catalog_request_timeout_ms:w.number().int().min(1).max(2147483647).default(1e4),auth_source:w.enum(["local","opencode-shared"]).default("local"),opencode_auth_db_path:am,default_region:kC.default("us-east-1"),account_selection_strategy:w.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),account_inference_concurrency:w.number().int().min(1).max(10).default(10),rate_limit_max_retries:w.number().int().min(0).max(100).default(3),rate_limit_retry_delay_ms:w.number().int().min(1).max(2147483647).default(5000),quota_recheck_interval_ms:w.number().int().min(1).max(2147483647).default(900000),stop_on_overage:w.boolean().default(!0),overage_threshold:w.number().int().min(0).max(1e6).default(0),quota_recheck_timeout_ms:w.number().int().min(1).max(2147483647).default(1e4),quota_recheck_concurrency:w.number().int().min(1).max(32).default(4),account_maintenance_enabled:w.boolean().default(!0),account_maintenance_interval_ms:w.number().int().min(1000).max(2147483647).default(60000),account_maintenance_timeout_ms:w.number().int().min(1000).max(2147483647).default(120000),account_maintenance_concurrency:w.number().int().min(1).max(32).default(4),usage_refresh_interval_ms:w.number().int().min(1000).max(2147483647).default(900000),max_request_iterations:w.number().int().min(1).max(1000).default(20),request_timeout_ms:w.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:w.number().int().min(1).max(2147483647).default(60000),stream_max_attempts:w.number().int().min(1).max(10).default(3),retry_empty_completion:w.boolean().default(!0),max_request_body_bytes:w.number().int().min(1).max(2147483647).default(33554432),max_inflight_requests:w.number().int().min(1).max(1e4).default(16),max_inflight_request_body_bytes:w.number().int().min(1).max(2147483647).default(134217728),token_expiry_buffer_ms:w.number().int().min(1).max(2147483647).default(300000),session_affinity_ttl_ms:w.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:w.number().int().min(1).max(1e6).default(1e4),session_affinity_stall_failover_threshold:w.number().int().min(0).max(100).default(2),session_affinity_stall_window_ms:w.number().int().min(1).max(2147483647).default(600000),reasoning_replay_key_path:am,reasoning_replay_keys:w.array(w.string().trim().min(1)).default([]),reasoning_replay_token_format:w.enum(["portable-v2","database-v1"]).default("portable-v2"),reasoning_replay_account_failover:w.enum(["verified","strict"]).default("verified"),reasoning_replay_legacy_account_failover:w.enum(["strict","verified-current-cell"]).default("strict"),reasoning_replay_ttl_ms:w.number().int().min(1).max(2147483647).default(86400000),reasoning_replay_max_entries:w.number().int().min(1).max(1e6).default(1e4),effort:O4.nullable().default(null),auto_effort_mapping:w.boolean().default(!0),log_level:w.enum(["debug","info","warn","error"]).default("info"),test_upstream_endpoint:w.string().url().optional()});var xm='auth_source "opencode-shared" was removed in kiro-provider 0.7.0. Copy the OpenCode accounts once with "kiro-provider accounts import [--from <path>]", then set auth_source to "local" or delete the key; the provider-owned store (~/.config/kiro-provider/accounts.db) is the only authentication authority.';function hU(I){if(I.auth_source==="opencode-shared")throw new GY(xm);if(I.opencode_auth_db_path!==null)y("warn","config_opencode_auth_db_path_deprecated",{hint:"opencode_auth_db_path is ignored since 0.7.0 and will be removed; pass --from to kiro-provider accounts import instead"});return I}class GY extends Error{constructor(I,G){super(I,G);this.name="ConfigLoadError"}}var HU=F4.partial().strict(),wU=Object.keys(F4.shape),dU=[{env:"KIRO_PROVIDER_HOST",field:"host",kind:"string"},{env:"KIRO_PROVIDER_PORT",field:"port",kind:"integer"},{env:"KIRO_PROVIDER_API_KEYS",field:"api_keys",kind:"list"},{env:"KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS",field:"enable_legacy_chat_completions",kind:"boolean"},{env:"KIRO_PROVIDER_PROTOCOL_PROJECTION_MODE",field:"protocol_projection_mode",kind:"string"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_MODE",field:"session_affinity_mode",kind:"string"},{env:"KIRO_PROVIDER_PROMPT_CACHE_MODE",field:"kiro_prompt_cache_mode",kind:"string"},{env:"KIRO_PROVIDER_RESPONSES_FIDELITY_MODE",field:"responses_fidelity_mode",kind:"string"},{env:"KIRO_PROVIDER_RESPONSES_INSTRUCTION_LIFT",field:"responses_instruction_lift",kind:"string"},{env:"KIRO_PROVIDER_RESPONSES_NATIVE_TOOL_BRIDGE",field:"responses_native_tool_bridge",kind:"string"},{env:"KIRO_PROVIDER_PROXY_URL",field:"proxy_url",kind:"string"},{env:"KIRO_PROVIDER_SDK_HTTP_KEEP_ALIVE",field:"sdk_http_keep_alive",kind:"boolean"},{env:"KIRO_PROVIDER_ENFORCE_SINGLE_INSTANCE",field:"enforce_single_instance",kind:"boolean"},{env:"KIRO_PROVIDER_INSTANCE_LOCK_PATH",field:"instance_lock_path",kind:"string"},{env:"KIRO_PROVIDER_RUNTIME_ENDPOINT_MODE",field:"runtime_endpoint_mode",kind:"string"},{env:"KIRO_PROVIDER_DYNAMIC_MODEL_CATALOG",field:"dynamic_model_catalog",kind:"boolean"},{env:"KIRO_PROVIDER_MODEL_CATALOG_TTL_MS",field:"model_catalog_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_MODEL_CATALOG_STALE_TTL_MS",field:"model_catalog_stale_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_MODEL_CATALOG_REQUEST_TIMEOUT_MS",field:"model_catalog_request_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_AUTH_SOURCE",field:"auth_source",kind:"string"},{env:"KIRO_PROVIDER_OPENCODE_AUTH_DB_PATH",field:"opencode_auth_db_path",kind:"string"},{env:"KIRO_PROVIDER_DEFAULT_REGION",field:"default_region",kind:"string"},{env:"KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY",field:"account_selection_strategy",kind:"string"},{env:"KIRO_PROVIDER_ACCOUNT_INFERENCE_CONCURRENCY",field:"account_inference_concurrency",kind:"integer"},{env:"KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES",field:"rate_limit_max_retries",kind:"integer"},{env:"KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS",field:"rate_limit_retry_delay_ms",kind:"integer"},{env:"KIRO_PROVIDER_QUOTA_RECHECK_INTERVAL_MS",field:"quota_recheck_interval_ms",kind:"integer"},{env:"KIRO_PROVIDER_STOP_ON_OVERAGE",field:"stop_on_overage",kind:"boolean"},{env:"KIRO_PROVIDER_OVERAGE_THRESHOLD",field:"overage_threshold",kind:"integer"},{env:"KIRO_PROVIDER_QUOTA_RECHECK_TIMEOUT_MS",field:"quota_recheck_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_QUOTA_RECHECK_CONCURRENCY",field:"quota_recheck_concurrency",kind:"integer"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_ENABLED",field:"account_maintenance_enabled",kind:"boolean"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_INTERVAL_MS",field:"account_maintenance_interval_ms",kind:"integer"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_TIMEOUT_MS",field:"account_maintenance_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_CONCURRENCY",field:"account_maintenance_concurrency",kind:"integer"},{env:"KIRO_PROVIDER_USAGE_REFRESH_INTERVAL_MS",field:"usage_refresh_interval_ms",kind:"integer"},{env:"KIRO_PROVIDER_MAX_REQUEST_ITERATIONS",field:"max_request_iterations",kind:"integer"},{env:"KIRO_PROVIDER_REQUEST_TIMEOUT_MS",field:"request_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS",field:"stream_idle_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_STREAM_MAX_ATTEMPTS",field:"stream_max_attempts",kind:"integer"},{env:"KIRO_PROVIDER_RETRY_EMPTY_COMPLETION",field:"retry_empty_completion",kind:"boolean"},{env:"KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES",field:"max_request_body_bytes",kind:"integer"},{env:"KIRO_PROVIDER_MAX_INFLIGHT_REQUESTS",field:"max_inflight_requests",kind:"integer"},{env:"KIRO_PROVIDER_MAX_INFLIGHT_REQUEST_BODY_BYTES",field:"max_inflight_request_body_bytes",kind:"integer"},{env:"KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS",field:"token_expiry_buffer_ms",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_TTL_MS",field:"session_affinity_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_MAX_ENTRIES",field:"session_affinity_max_entries",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_STALL_FAILOVER_THRESHOLD",field:"session_affinity_stall_failover_threshold",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_STALL_WINDOW_MS",field:"session_affinity_stall_window_ms",kind:"integer"},{env:"KIRO_PROVIDER_REASONING_REPLAY_KEY_PATH",field:"reasoning_replay_key_path",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_KEYS",field:"reasoning_replay_keys",kind:"list"},{env:"KIRO_PROVIDER_REASONING_REPLAY_TOKEN_FORMAT",field:"reasoning_replay_token_format",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_ACCOUNT_FAILOVER",field:"reasoning_replay_account_failover",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_LEGACY_ACCOUNT_FAILOVER",field:"reasoning_replay_legacy_account_failover",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_TTL_MS",field:"reasoning_replay_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_REASONING_REPLAY_MAX_ENTRIES",field:"reasoning_replay_max_entries",kind:"integer"},{env:"KIRO_PROVIDER_EFFORT",field:"effort",kind:"string"},{env:"KIRO_PROVIDER_AUTO_EFFORT_MAPPING",field:"auto_effort_mapping",kind:"boolean"},{env:"KIRO_PROVIDER_LOG_LEVEL",field:"log_level",kind:"string"},{env:"KIRO_PROVIDER_TEST_UPSTREAM",field:"test_upstream_endpoint",kind:"string"}];function cU(I){return I===void 0||I.trim().length===0?void 0:I}var OU=/^[+-]?\d+$/;function FU(I,G){let C=G.trim();if(!OU.test(C))throw new GY(`Invalid environment variable ${I}: expected a decimal integer, got "${G}"`);let N=Number(C);if(!Number.isSafeInteger(N))throw new GY(`Invalid environment variable ${I}: integer out of range, got "${G}"`);return N}function vU(I){let G=I.trim().toLowerCase();if(G==="true"||G==="1")return!0;if(G==="false"||G==="0")return!1;return I}function uU(I){return I.split(",").map((G)=>G.trim()).filter((G)=>G.length>0)}function JU(I){let G={},C=new Map;for(let{env:N,field:Y,kind:Z}of dU){let W=cU(I[N]);if(W===void 0)continue;switch(Z){case"integer":G[Y]=FU(N,W);break;case"boolean":G[Y]=vU(W);break;case"list":G[Y]=uU(W);break;case"string":G[Y]=W.trim();break}C.set(Y,N)}return{values:G,sources:C}}function AU(I,G){let C=Array.from({length:G.length+1},(N,Y)=>Y);for(let N=1;N<=I.length;N+=1){let Y=C[0];C[0]=N;for(let Z=1;Z<=G.length;Z+=1){let W=C[Z],b=C[Z-1],l=I[N-1]===G[Z-1]?0:1;C[Z]=Math.min(W+1,b+1,Y+l),Y=W}}return C[G.length]}function gU(I){let G=I.toLowerCase(),C;for(let Y of wU){let Z=AU(G,Y);if(C===void 0||Z<C.distance)C={field:Y,distance:Z}}if(!C)return;let N=C.field.startsWith(G)||G.startsWith(C.field);return C.distance<=3||N?C.field:void 0}function KU(I){let G=I.map((C)=>{let N=gU(C);return N?`"${C}" (did you mean "${N}"?)`:`"${C}"`});return`unknown key${I.length===1?"":"s"} ${G.join(", ")}`}function kU(I,G){if(I.code===w.ZodIssueCode.unrecognized_keys)return KU(I.keys);let C=I.path.length>0?I.path.join("."):"config",N=G?.get(String(I.path[0]));return`${C}: ${I.message}${N?` (from ${N})`:""}`}function Bd(I,G){return I.issues.map((C)=>kU(C,G)).join(", ")}function yU(I,G){if(G==="win32")return;let C;try{C=RU(I).mode&511}catch{return}if((C&63)===0)return;y("warn","config_file_permissions_loose",{path:I,mode:`0${C.toString(8)}`,recommended_mode:"0600",hint:"the file may contain api_keys; run chmod 600 on it"})}function pU(I,G){if(!VU(I))return{};yU(I,G);try{let C=JSON.parse(XU(I,"utf8"));return HU.parse(C)}catch(C){if(C instanceof w.ZodError)throw new GY(`Invalid configuration file ${I}: ${Bd(C)}`,{cause:C});if(C instanceof Error)throw new GY(`Unable to read configuration file ${I}: ${C.message}`,{cause:C});throw C}}function ad(I={}){let G=I.env??process.env,C=I.platform??process.platform,N=I.configPath??jd({env:G,platform:C}),Y;try{let Z=pU(N,C),W=JU(G);Y=new Map([...W.sources].filter(([l])=>!(l in(I.overrides??{}))));let b=F4.parse({...Z,...W.values,...I.overrides});if(b.max_inflight_request_body_bytes<b.max_request_body_bytes)throw new GY("max_inflight_request_body_bytes must be at least max_request_body_bytes");return hU(b)}catch(Z){if(Z instanceof GY)throw Z;if(Z instanceof w.ZodError)throw new GY(`Invalid configuration: ${Bd(Z,Y)}`,{cause:Z});throw Z}}var EU=["invalid_grant","invalid_client","unauthorized_client","InvalidGrantException","InvalidClientException","UnauthorizedClientException","ExpiredTokenException","InvalidTokenException","ExpiredClientException","Invalid refresh token","Invalid grant provided","Client is expired"],zU=["MISSING_CREDENTIALS","INVALID_RESPONSE"];function DU(I){return zU.some((G)=>I===G||I.startsWith(`${G}:`)||I.includes(` ${G}:`))}function GN(I){if(!I)return!1;if(DU(I))return!0;return EU.some((G)=>I.includes(G))}function JN(I){if(!I)return!1;let G=I.toLowerCase();return G.includes("bearer token included in the request is invalid")||G.includes("access token has expired")||G.includes("access_token expired")||G.includes("the access token expired")}var mG={stopOnOverage:!0,overageThreshold:0};function DW(I){return{stopOnOverage:I.stop_on_overage,overageThreshold:I.overage_threshold}}function Rl(I){let G=I.usedCount??0,C=I.limitCount??0;return Number.isFinite(G)&&Number.isFinite(C)&&C>0&&G>=C}function qU(I){return typeof I==="object"&&I!==null&&typeof I.stopOnOverage==="boolean"&&typeof I.overageThreshold==="number"?I:mG}function hl(I,G){let C=qU(G);if(!C.stopOnOverage)return!1;let N=I.overageCount??0;return Number.isFinite(N)&&N>C.overageThreshold}function nI(I,G){return hl(I,G)||Rl(I)}function xG(I){return GN(I)}function AN(I){let G=I&&I.length>0?I:"Account needs re-authentication";return GN(G)?G:`InvalidTokenException: ${G}`}class VG extends Error{code;originalError;constructor(I,G,C){super(I);this.name="KiroTokenRefreshError",this.code=G,this.originalError=C}}function v4(I){let G=I.split("|"),C=G[0]??"";if(G.length<2)return{refreshToken:C,authMethod:"desktop"};if(G.at(-1)==="idc")return{refreshToken:C,clientId:G[1],clientSecret:G[2],authMethod:"idc"};return{refreshToken:C,authMethod:"desktop"}}function Hl(I,G=120000){if(!I.access||!I.expires)return!0;return Date.now()>=I.expires-G}function qW(I){if(I.authMethod==="idc"){if(!I.clientId||!I.clientSecret)throw new VG("Missing credentials","MISSING_CREDENTIALS");return`${I.refreshToken}|${I.clientId}|${I.clientSecret}|idc`}return`${I.refreshToken}|desktop`}function xd(I){return typeof I==="object"&&I!==null&&"code"in I&&typeof I.code==="string"?I.code:void 0}function UW(I){let G=xd(I),C=I instanceof Error?I.message:String(I);return G?`${G}: ${C}`:C}function wl(I){return{error_name:I instanceof Error?I.name:"UnknownError",error_code:xd(I)}}function Md(I){if(typeof I==="object"&&I!==null&&"unref"in I&&typeof I.unref==="function")I.unref()}class Mm{options;initialTimer;intervalTimer;lifecycleController=new AbortController;inFlight;constructor(I){this.options=I}start(){if(!this.options.enabled||this.initialTimer!==void 0||this.intervalTimer!==void 0)return;this.lifecycleController=new AbortController;let I=()=>{this.runOnce(this.lifecycleController.signal).catch((G)=>{if(this.lifecycleController.signal.aborted)return;y("warn","account_maintenance_pass_failed",{...wl(G)})})};this.initialTimer=setTimeout(()=>{this.initialTimer=void 0,I()},this.options.initialDelayMs??5000),this.intervalTimer=setInterval(I,this.options.intervalMs),Md(this.initialTimer),Md(this.intervalTimer),y("info","account_maintenance_started",{interval_ms:this.options.intervalMs,timeout_ms:this.options.timeoutMs,concurrency:this.options.concurrency})}stop(){if(this.initialTimer!==void 0)clearTimeout(this.initialTimer),this.initialTimer=void 0;if(this.intervalTimer!==void 0)clearInterval(this.intervalTimer),this.intervalTimer=void 0;if(!this.lifecycleController.signal.aborted)this.lifecycleController.abort(new DOMException("Account maintenance stopped","AbortError"));y("info","account_maintenance_stopped",{})}runOnce(I){if(!this.options.enabled)return Promise.resolve();if(this.inFlight)return this.inFlight;let G=this.runPass(I).finally(()=>{if(this.inFlight===G)this.inFlight=void 0});return this.inFlight=G,G}async runPass(I){let G=Date.now(),C=AbortSignal.timeout(this.options.timeoutMs),N=I?AbortSignal.any([I,C]):C,Y=this.options.accountManager.reconcileFromDb(),Z=this.overagePolicy(),W=0,b=0,l=[];for(let X of Y){if(xG(X.unhealthyReason)||nI(X,Z))continue;let R=this.authDetails(X);if(R===void 0){b+=1;continue}if(Hl(R,this.options.tokenExpiryBufferMs))l.push({account:X,auth:R})}let Q=0,L=async()=>{for(;;){if(N.aborted)throw N.reason;let X=l[Q];if(Q+=1,!X)return;try{await this.options.tokenRefresher.refreshIfNeeded(X.account,X.auth,N),W+=1}catch(R){b+=1,this.recordTokenFailure(X.account,R)}}};await Promise.all(Array.from({length:Math.min(this.options.concurrency,l.length)},L));let m=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.recheckDueAccounts(m,N);let V=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.syncDueAccounts(V,N),y("info","account_maintenance_pass_completed",{account_count:V.length,token_due_count:l.length,token_refreshed_count:W,token_failed_count:b,duration_ms:Date.now()-G})}overagePolicy(){return this.options.overagePolicy??this.options.accountManager.getOveragePolicy?.()??mG}authDetails(I){try{return this.options.accountManager.toAuthDetails(I)}catch(G){this.recordTokenFailure(I,G);return}}recordTokenFailure(I,G){let C=UW(G);if(GN(C))try{this.options.accountManager.markUnhealthy(I,AN(C))}catch{}y("warn","account_maintenance_token_refresh_failed",{account_hash:a(I.id),...wl(G)})}}function Sd(I,G){if(!G)return I;G.start();let C=I.stop.bind(I),N=(Y)=>{try{G.stop()}finally{C(Y)}};try{Object.defineProperty(I,"stop",{configurable:!0,value:N})}catch(Y){try{G.stop()}finally{C(!0)}throw Y}return I}function UU(I){throw TypeError(`Unsupported account selection strategy: ${String(I)}`)}function HC(I,G,C=mG){if(xG(I.unhealthyReason))return!1;if(nI(I,C))return!1;if(I.rateLimitResetTime>G)return!1;return nd(I,G)}function nd(I,G){if(I.isHealthy||JN(I.unhealthyReason))return!0;return I.recoveryTime!==void 0&&I.recoveryTime<=G}function Td(I,G,C=mG){if(!hl(I,C))return!1;if(xG(I.unhealthyReason))return!1;if(Rl(I))return!1;return nd(I,G)}function sd(I,G,C,N=mG){return I.filter((Y)=>HC(Y,G,N)).filter((Y)=>C?.has(Y.id)??!0).sort((Y,Z)=>Y.id.localeCompare(Z.id))}function id(I,G,C,N=mG){return I.filter((Y)=>HC(Y,G,N)&&(C?.has(Y.id)??!0)).length}class Sm{strategy;stickyId;roundRobinCursor=0;constructor(I){this.strategy=I}pick(I,G){return I.find(({id:C})=>C===G)??this.pickByStrategy(I)}retainSticky(I){if(this.stickyId&&!I.some(({id:G})=>G===this.stickyId))this.stickyId=void 0}forget(I){if(this.stickyId===I)this.stickyId=void 0}pickByStrategy(I){switch(this.strategy){case"sticky":{let C=I.find(({id:N})=>N===this.stickyId)??I[0];if(!C)throw RangeError("Candidate list cannot be empty");return this.stickyId=C.id,C}case"round-robin":{let G=I[this.roundRobinCursor%I.length];if(!G)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,G}case"lowest-usage":{let G=[...I].sort((C,N)=>(C.usedCount??0)-(N.usedCount??0)||(C.lastUsed??0)-(N.lastUsed??0)||C.id.localeCompare(N.id))[0];if(!G)throw RangeError("Candidate list cannot be empty");return G}default:return UU(this.strategy)}}}import{createHash as JJ}from"crypto";import{Agent as eCI}from"http";import{Agent as INI}from"https";var jY=NI(NN(),1);var Tl=NI(NN(),1);var sl=NI(NN(),1);var QY=NI(NN(),1);var wC=NI(NN(),1);var xI=NI($G(),1);var bb=NI(UY(),1),WJ=NI(kY(),1);var cX=NI(e4(),1);var il=NI(_G(),1);var yC=NI(cZ(),1);var fI=NI(Sl(),1);var uI=NI(YY(),1);var _W=NI(UY(),1);var tW=NI(YY(),1);var e5=async(I,G,C)=>{return{operation:tW.getSmithyContext(G).operation}};function Hf(I){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:G,filepath:C,configFilepath:N,ignoreCache:Y},Z)=>({identityProperties:{profile:G,filepath:C,configFilepath:N,ignoreCache:Y}})}}var I1=(I)=>{let G=[];switch(I.operation){default:G.push(Hf(I))}return G},G1=(I)=>{let G=_W.memoizeIdentityProvider(I.token,_W.isIdentityExpired,_W.doesIdentityRequireRefresh);return Object.assign(I,{authSchemePreference:tW.normalizeProvider(I.authSchemePreference??[]),token:G})};var C1=(I)=>{return Object.assign(I,{useDualstackEndpoint:I.useDualstackEndpoint??!1,useFipsEndpoint:I.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},N1={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var Y1={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var eu=NI(NN(),1),IJ=NI(zX(),1);var Yb=NI($G(),1);var oG=NI($G(),1);var T1=300000,oW="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var du=async(I,G={},C)=>{let{SSOOIDCClient:N}=await Promise.resolve().then(() => NI(hR(),1)),Y=(W)=>G.clientConfig?.[W]??G.parentClientConfig?.[W]??C?.[W];return new N(Object.assign({},G.clientConfig??{},{region:I??G.clientConfig?.region,logger:Y("logger"),userAgentAppId:Y("userAgentAppId")}))};var cu=async(I,G,C={},N)=>{let{CreateTokenCommand:Y}=await Promise.resolve().then(() => NI(hR(),1));return(await du(G,C,N)).send(new Y({clientId:I.clientId,clientSecret:I.clientSecret,refreshToken:I.refreshToken,grantType:"refresh_token"}))};var Ou=NI($G(),1);var HR=(I)=>{if(I.expiration&&I.expiration.getTime()<Date.now())throw new Ou.TokenProviderError(`Token is expired. ${oW}`,!1)};var Fu=NI($G(),1);var xY=(I,G,C=!1)=>{if(typeof G>"u")throw new Fu.TokenProviderError(`Value not present for '${I}' in SSO Token${C?". Cannot refresh":""}. ${oW}`,!1)};var vu=NI($G(),1);import{promises as Te}from"fs";var{writeFile:se}=Te,uu=(I,G)=>{let C=vu.getSSOTokenFilepath(I),N=JSON.stringify(G,null,2);return se(C,N)};var Ju=new Date(0),Au=(I={})=>async({callerClientConfig:G}={})=>{I.logger?.debug("@aws-sdk/token-providers - fromSso");let C=await oG.parseKnownFiles(I),N=oG.getProfileName({profile:I.profile??G?.profile}),Y=C[N];if(!Y)throw new oG.TokenProviderError(`Profile '${N}' could not be found in shared credentials file.`,!1);else if(!Y.sso_session)throw new oG.TokenProviderError(`Profile '${N}' is missing required property 'sso_session'.`);let Z=Y.sso_session,b=(await oG.loadSsoSessionData(I))[Z];if(!b)throw new oG.TokenProviderError(`Sso session '${Z}' could not be found in shared credentials file.`,!1);for(let R of["sso_start_url","sso_region"])if(!b[R])throw new oG.TokenProviderError(`Sso session '${Z}' is missing required property '${R}'.`,!1);let{sso_start_url:l,sso_region:Q}=b,L;try{L=await oG.getSSOTokenFromFile(Z)}catch(R){throw new oG.TokenProviderError(`The SSO session token associated with profile=${N} was not found or is invalid. ${oW}`,!1)}xY("accessToken",L.accessToken),xY("expiresAt",L.expiresAt);let{accessToken:m,expiresAt:V}=L,X={token:m,expiration:new Date(V)};if(X.expiration.getTime()-Date.now()>T1)return X;if(Date.now()-Ju.getTime()<30000)return HR(X),X;xY("clientId",L.clientId,!0),xY("clientSecret",L.clientSecret,!0),xY("refreshToken",L.refreshToken,!0);try{Ju.setTime(Date.now());let R=await cu(L,Q,I,G);xY("accessToken",R.accessToken),xY("expiresIn",R.expiresIn);let h=new Date(Date.now()+R.expiresIn*1000);try{await uu(Z,{...L,accessToken:R.accessToken,expiresAt:h.toISOString(),refreshToken:R.refreshToken})}catch(H){}return{token:R.accessToken,expiration:h}}catch(R){return HR(X),X}};var wR=(I={})=>Yb.memoize(Yb.chain(Au(I),async()=>{throw new Yb.TokenProviderError("Could not load token from any providers",!1)}),(G)=>G.expiration!==void 0&&G.expiration.getTime()-Date.now()<300000,(G)=>G.expiration!==void 0);var UN=NI(NN(),1);var GJ=NI(UY(),1);var iQ=NI(e4(),1);var dR=NI(tG(),1);var LY=NI($G(),1);var YL=NI(vQ(),1);var cR=NI(tG(),1);var OR=NI($G(),1);var HG=NI(Sl(),1);var _u=NI(EQ(),1),ru=NI(UY(),1);var FR=NI(_G(),1);var Zb=NI(tG(),1);var kZ=NI(tG(),1);var DG=NI(cZ(),1);var G0="ref",yZ=-1,PQ=!0,gu="isSet",pu="PartitionResult",fQ="booleanEquals",vR="getAttr",Ku={[G0]:"Endpoint"},uR={[G0]:pu},Wb={},ku=[{[G0]:"Region"}],yu={conditions:[[gu,[Ku]],[gu,ku],["aws.partition",ku,pu],[fQ,[{[G0]:"UseFIPS"},PQ]],[fQ,[{[G0]:"UseDualStack"},PQ]],[fQ,[{fn:vR,argv:[uR,"supportsDualStack"]},PQ]],[fQ,[{fn:vR,argv:[uR,"supportsFIPS"]},PQ]],["stringEquals",[{fn:vR,argv:[uR,"name"]},"aws-us-gov"]]],results:[[yZ],[yZ,"Invalid Configuration: FIPS and custom endpoint are not supported"],[yZ,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[Ku,Wb],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Wb],[yZ,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",Wb],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",Wb],[yZ,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",Wb],[yZ,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",Wb],[yZ,"Invalid Configuration: Missing Region"]]},ie=2,eG=1e8,Pe=new Int32Array([-1,1,-1,0,13,3,1,4,eG+12,2,5,eG+12,3,8,6,4,7,eG+11,5,eG+9,eG+10,4,11,9,6,10,eG+8,7,eG+6,eG+7,5,12,eG+5,6,eG+4,eG+5,3,eG+1,14,4,eG+2,eG+3]),Eu=DG.BinaryDecisionDiagram.from(Pe,ie,yu.conditions,yu.results);var fe=new DG.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),zu=(I,G={})=>{return fe.get(I,()=>DG.decideEndpoint(Eu,{endpointParams:I,logger:G.logger}))};DG.customEndpointFunctions.aws=wC.awsEndpointFunctions;var gR=NI(kY(),1);class IC extends uI.ServiceException{constructor(I){super(I);Object.setPrototypeOf(this,IC.prototype)}}class $Q extends IC{name="AccessDeniedException";$fault="client";reason;constructor(I){super({name:"AccessDeniedException",$fault:"client",...I});Object.setPrototypeOf(this,$Q.prototype),this.reason=I.reason}}class tQ extends IC{name="ConflictException";$fault="client";reason;constructor(I){super({name:"ConflictException",$fault:"client",...I});Object.setPrototypeOf(this,tQ.prototype),this.reason=I.reason}}class _Q extends IC{name="InternalServerException";$fault="server";$retryable={};reason;constructor(I){super({name:"InternalServerException",$fault:"server",...I});Object.setPrototypeOf(this,_Q.prototype),this.reason=I.reason}}class rQ extends IC{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(I){super({name:"ThrottlingException",$fault:"client",...I});Object.setPrototypeOf(this,rQ.prototype),this.reason=I.reason}}class oQ extends IC{name="ValidationException";$fault="client";reason;constructor(I){super({name:"ValidationException",$fault:"client",...I});Object.setPrototypeOf(this,oQ.prototype),this.reason=I.reason}}class eQ extends IC{name="ResourceNotFoundException";$fault="client";constructor(I){super({name:"ResourceNotFoundException",$fault:"client",...I});Object.setPrototypeOf(this,eQ.prototype)}}class IL extends IC{name="ServiceUnavailableException";$fault="server";constructor(I){super({name:"ServiceUnavailableException",$fault:"server",...I});Object.setPrototypeOf(this,IL.prototype)}}class GL extends IC{name="ServiceQuotaExceededException";$fault="client";reason;constructor(I){super({name:"ServiceQuotaExceededException",$fault:"client",...I});Object.setPrototypeOf(this,GL.prototype),this.reason=I.reason}}class CL extends IC{name="DryRunOperationException";$fault="client";responseCode;constructor(I){super({name:"DryRunOperationException",$fault:"client",...I});Object.setPrototypeOf(this,CL.prototype),this.responseCode=I.responseCode}}var Du=gR.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),$e=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];Du.registerError($e,IC);var jN=gR.TypeRegistry.for("com.amazon.aws.codewhisperer"),te=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];jN.registerError(te,$Q);var _e=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];jN.registerError(_e,tQ);var re=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];jN.registerError(re,CL);var qu=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];jN.registerError(qu,_Q);var oe=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];jN.registerError(oe,eQ);var ee=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];jN.registerError(ee,GL);var III=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];jN.registerError(III,IL);var GII=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];jN.registerError(GII,rQ);var CII=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];jN.registerError(CII,oQ);var Uu=[Du,jN];var KR=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],CI=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],NII=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],NL=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],aI=[0,"com.amazon.aws.q","SensitiveString",8,0],YII=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>CI,0],[()=>CI,0],[()=>CI,0]],2],ZII=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>CI,0],[()=>CI,0],[()=>CI,0],[()=>CI,0]],3],WII=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>CI,0],0],1],bII=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>CI,0],0,[()=>fu,0],()=>Pu,[()=>ju,0],[()=>MGI,0],()=>kR,[()=>LCI,0]],1];var kR=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],lII=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>NCI,[()=>CI,0],[()=>CI,0]],2],QII=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],LII=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>CI,0]],1],mII=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>CI,0]],1],VII=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>Pu]],XII=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>CI,0],0,0,0,[()=>CI,0],[()=>CI,0]]],RII=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],hII=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>$u,0],0,0,0,[()=>yGI,0],0,0,0],2],HII=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>CI,0],()=>yR],2],wII=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>HII,0],[()=>CI,0]],2],dII=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>bCI,0]],3],cII=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>CI,0],[()=>CI,0],[()=>WCI,0],[()=>zGI,0]]],OII=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],FII=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>CI,0]]],JR=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],vII=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>CI,0],[()=>CI,0]]],uII=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],JII=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],AII=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>xu,0],()=>YCI,[()=>UGI,0],2,[()=>SGI,0]]],gII=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>CI,0],[()=>CI,0]]],KII=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>CI,0],[()=>DGI,0],1]],ju=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>CI,0],0],1],kII=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>ju,0]]],yII=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>CI,0]]],pII=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>lCI,0]],2],EII=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>ICI,0]]],zII=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],DII=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],qII=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>IGI]],UII=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],AR=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],Bu=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],yR=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>AR,()=>AR],2],jII=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>CI,0],21,[()=>CI,0]]],BII=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>CI,0],[()=>CI,0]],1],aII=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>au]],xII=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>CI,0],()=>Bu,[()=>CI,0],()=>iu,0],1],MII=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>CI,0],0,[()=>CI,0]],3],SII=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>CI,0],[()=>CI,0],1,[()=>CI,0],[()=>CI,0]],1],nII=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>jGI,0]],1],au=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],TII=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>CI,0],[()=>CI,0],[()=>CI,0]],2],sII=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>fu,0]]],xu=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>CI,0],()=>Bu,[()=>CI,0],()=>iu],1],iII=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>xu,0],()=>yR,[()=>CI,0],0,[()=>CI,0],[()=>CI,0],[()=>LII,0],64,[()=>pGI,0],[()=>CI,0]],5],PII=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>KR,0]]],Mu=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>BGI,0],0,[()=>NL,0]],2],fII=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>Mu,0]]],$II=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>PII,0],[()=>NL,0],[()=>NII,0]],2],tII=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>NL,0],[()=>KR,0]],3],_II=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>NL,0],[()=>CI,0],2],2];var rII=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>CI,0],[()=>oII,0],0,0,[()=>qGI,0],[()=>EGI,0],0,()=>kR,()=>QII],1],oII=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>AII,0],[()=>nII,0],[()=>yII,0],[()=>KII,0],[()=>ZII,0],[()=>ZCI,0],[()=>XII,0],()=>eII,[()=>kGI,0],[()=>aGI,0],[()=>xGI,0]]],eII=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var IGI=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var GGI=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>hII,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],CGI=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>CCI,16]],2];var NGI=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>iGI,0]],1],pR=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>KGI,0],[()=>XGI,0]]],ER=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>nGI,0]],2],YGI=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>C0,0]]],ZGI=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>sGI,0],2],1],WGI=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>aI,0],[()=>aI,0]],2],bGI=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>aI,0],[()=>TGI,0],2,2],2],lGI=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>aI,0],[()=>aI,0],[()=>aI,0]],2],Su=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>QGI,0]]],QGI=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>aI,0],[()=>aI,0]],2],LGI=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0]],4],mGI=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>C0,0],[()=>ER,0],[()=>Su,0],[()=>nu,0],[()=>su,0],[()=>JGI,0],()=>gGI,[()=>cGI,0],[()=>hGI,0],[()=>zR,0],[()=>Tu,0],[()=>pR,0],[()=>ZGI,0],[()=>LGI,0]]],VGI=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>mGI,0],0],1],XGI=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>lGI,0]]],nu=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>PGI,0]],1],RGI=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>su,0]]],zR=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0]],6],Tu=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>fGI,0],[()=>pR,0]],1],hGI=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>aI,0],[()=>$GI,0],[()=>pR,0]],2],HGI=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>C0,0],[()=>ER,0],[()=>zR,0],[()=>Tu,0]]],su=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>aI,0],[()=>tGI,0]],3],wGI=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>C0,0]]],dGI=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>aI,0]],1],cGI=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>_GI,0]],1],OGI=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>aI,0],[()=>GCI,0],[()=>vGI,0],2,2,[()=>FGI,0]],2],FGI=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>aI,0]]],vGI=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>aI,0],0],1],uGI=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>C0,0],[()=>Su,0],[()=>ER,0],[()=>nu,0]]],JGI=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>AGI,0],[()=>oGI,0],[()=>rGI,0]],2],AGI=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>aI,0],[()=>aI,0]],2],gGI=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],C0=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>aI,0]],1],KGI=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>aI,0],[()=>aI,0]],2];var kGI=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>YII,0]],yGI=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>$u,0]],pGI=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>wII,0]];var EGI=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>dII,0]],zGI=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>FII,0]],iu=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>uII],DGI=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>gII,0]],qGI=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>pII,0]],Pu=[1,"com.amazon.aws.codewhisperer","References",0,()=>aII],UGI=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>xII,0]],jGI=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>SII,0]],fu=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>TII,0]],BGI=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>VCI,0]],aGI=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>Mu,0]],xGI=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>mCI,0]],MGI=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>tII,0]],SGI=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>CI,0]],nGI=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>YGI,0]],TGI=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>WGI,0]],sGI=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>bGI,0]],iGI=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>VGI,0]],PGI=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>RGI,0]],fGI=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>zR,0]],$GI=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>HGI,0]],tGI=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>wGI,0]],_GI=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>dGI,0]],rGI=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>OGI,0]],oGI=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>uGI,0]],eGI=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>QCI],ICI=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>eGI,0]],GCI=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>aI,0]],$u=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>rII,0],[()=>bII,0]]],CCI=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>DII,[()=>WII,0],[()=>jII,0],()=>JII,()=>VII,[()=>sII,0],[()=>kII,0],[()=>mII,0],[()=>EII,0],[()=>NGI,0],[()=>_II,0],[()=>fII,0],()=>qII,()=>UII,()=>RII,[()=>lII,0],[()=>cII,0],()=>zII,[()=>qu,0]]],NCI=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>au]],YCI=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>AR,()=>yR]],ZCI=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>iII,0],[()=>MII,0]]],WCI=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>JR,()=>JR,()=>JR,()=>OII,[()=>vII,0]]],bCI=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var lCI=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],QCI=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],LCI=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>BII,0],21]];var mCI=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>$II,0],()=>kR]],VCI=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>CI,0],[()=>KR,0]]];var tu=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>GGI,()=>CGI];var ou=(I)=>{return{apiVersion:"2023-11-27",base64Decoder:I?.base64Decoder??Zb.fromBase64,base64Encoder:I?.base64Encoder??Zb.toBase64,disableHostPrefix:I?.disableHostPrefix??!1,endpointProvider:I?.endpointProvider??zu,extensions:I?.extensions??[],httpAuthSchemeProvider:I?.httpAuthSchemeProvider??I1,httpAuthSchemes:I?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(G)=>G.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new ru.HttpBearerAuthSigner}],logger:I?.logger??new uI.NoOpLogger,protocol:I?.protocol??_u.AwsRestJsonProtocol,protocolSettings:I?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:Uu,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:I?.serviceId??"CodeWhispererStreaming",urlParser:I?.urlParser??FR.parseUrl,utf8Decoder:I?.utf8Decoder??kZ.fromUtf8,utf8Encoder:I?.utf8Encoder??kZ.toUtf8}};var CJ=(I)=>{uI.emitWarningIfUnsupportedVersion(process.version);let G=OR.resolveDefaultsModeConfig(I),C=()=>G().then(uI.loadConfigsForDefaultMode),N=ou(I);eu.emitWarningIfUnsupportedVersion(process.version);let Y={profile:I?.profile,logger:N.logger};return{...N,...I,runtime:"node",defaultsMode:G,authSchemePreference:I?.authSchemePreference??LY.loadConfig(IJ.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,Y),bodyLengthChecker:I?.bodyLengthChecker??cR.calculateBodyLength,defaultUserAgentProvider:I?.defaultUserAgentProvider??UN.createDefaultUserAgentProvider({serviceId:N.serviceId,clientVersion:Y1.version}),eventStreamSerdeProvider:I?.eventStreamSerdeProvider??iQ.eventStreamSerdeProvider,httpAuthSchemes:I?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(Z)=>Z.getIdentityProvider("smithy.api#httpBearerAuth")||(async(W)=>{return await wR(W)(W)}),signer:new GJ.HttpBearerAuthSigner}],maxAttempts:I?.maxAttempts??LY.loadConfig(fI.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,I),region:I?.region??LY.loadConfig(xI.NODE_REGION_CONFIG_OPTIONS,{...xI.NODE_REGION_CONFIG_FILE_OPTIONS,...Y}),requestHandler:YL.NodeHttpHandler.create(I?.requestHandler??C),retryMode:I?.retryMode??LY.loadConfig({...fI.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await C()).retryMode||HG.DEFAULT_RETRY_MODE},I),sha256:I?.sha256??dR.Hash.bind(null,"sha256"),streamCollector:I?.streamCollector??YL.streamCollector,useDualstackEndpoint:I?.useDualstackEndpoint??LY.loadConfig(xI.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,Y),useFipsEndpoint:I?.useFipsEndpoint??LY.loadConfig(xI.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,Y),userAgentAppId:I?.userAgentAppId??LY.loadConfig(UN.NODE_APP_ID_CONFIG_OPTIONS,Y)}};var dC=NI(NN(),1);var GC=NI(_G(),1);var NJ=(I)=>{let{httpAuthSchemes:G,httpAuthSchemeProvider:C,token:N}=I;return{setHttpAuthScheme(Y){let Z=G.findIndex((W)=>W.schemeId===Y.schemeId);if(Z===-1)G.push(Y);else G.splice(Z,1,Y)},httpAuthSchemes(){return G},setHttpAuthSchemeProvider(Y){C=Y},httpAuthSchemeProvider(){return C},setToken(Y){N=Y},token(){return N}}},YJ=(I)=>{return{httpAuthSchemes:I.httpAuthSchemes(),httpAuthSchemeProvider:I.httpAuthSchemeProvider(),token:I.token()}};var ZJ=(I,G)=>{let C=Object.assign(dC.getAwsRegionExtensionConfiguration(I),uI.getDefaultExtensionConfiguration(I),GC.getHttpHandlerExtensionConfiguration(I),NJ(I));return G.forEach((N)=>N.configure(C)),Object.assign(I,dC.resolveAwsRegionExtensionConfiguration(C),uI.resolveDefaultRuntimeConfig(C),GC.resolveHttpHandlerRuntimeConfig(C),YJ(C))};class DR extends uI.Client{config;constructor(...[I]){let G=CJ(I||{});super(G);this.initConfig=G;let C=C1(G),N=QY.resolveUserAgentConfig(C),Y=fI.resolveRetryConfig(N),Z=xI.resolveRegionConfig(Y),W=jY.resolveHostHeaderConfig(Z),b=yC.resolveEndpointConfig(W),l=wC.resolveDefaultAwsRegionalEndpointsConfig(b),Q=cX.resolveEventStreamSerdeConfig(l),L=G1(Q),m=ZJ(L,I?.extensions||[]);this.config=m,this.middlewareStack.use(WJ.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(QY.getUserAgentPlugin(this.config)),this.middlewareStack.use(fI.getRetryPlugin(this.config)),this.middlewareStack.use(il.getContentLengthPlugin(this.config)),this.middlewareStack.use(jY.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Tl.getLoggerPlugin(this.config)),this.middlewareStack.use(sl.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(bb.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:e5,identityProviderConfigProvider:async(V)=>new bb.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":V.token})})),this.middlewareStack.use(bb.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class qR extends uI.Command.classBuilder().ep(N1).m(function(I,G,C,N){return[yC.getEndpointPlugin(C,I.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(tu).build(){}var DC={CONTENT_LENGTH_EXCEEDS_THRESHOLD:"CONTENT_LENGTH_EXCEEDS_THRESHOLD",DOCUMENT_COUNT_EXCEEDED:"DOCUMENT_COUNT_EXCEEDED",DOCUMENT_DUPLICATE_NAME:"DOCUMENT_DUPLICATE_NAME",DOCUMENT_MAXIMUM_PAGES_EXCEEDED:"DOCUMENT_MAXIMUM_PAGES_EXCEEDED",DOCUMENT_MODEL_NOT_SUPPORTED:"DOCUMENT_MODEL_NOT_SUPPORTED",DOCUMENT_PASSWORD_PROTECTED:"DOCUMENT_PASSWORD_PROTECTED",DOCUMENT_SIZE_EXCEEDED:"DOCUMENT_SIZE_EXCEEDED",IMAGE_COUNT_EXCEEDED:"IMAGE_COUNT_EXCEEDED",IMAGE_DIMENSION_EXCEEDED:"IMAGE_DIMENSION_EXCEEDED",IMAGE_FORMAT_UNSUPPORTED:"IMAGE_FORMAT_UNSUPPORTED",IMAGE_MIME_MISMATCH:"IMAGE_MIME_MISMATCH",IMAGE_SIZE_EXCEEDED:"IMAGE_SIZE_EXCEEDED",INVALID_CONVERSATION_ID:"INVALID_CONVERSATION_ID",INVALID_KMS_GRANT:"INVALID_KMS_GRANT",INVALID_MODEL_ID:"INVALID_MODEL_ID",PROMPT_TOO_LONG:"PROMPT_TOO_LONG",REQUEST_BODY_INVALID:"REQUEST_BODY_INVALID",REQUEST_BODY_INVALID_JSON:"REQUEST_BODY_INVALID_JSON",THINKING_SIGNATURE_INVALID:"THINKING_SIGNATURE_INVALID",TOOL_CONFIG_MISSING:"TOOL_CONFIG_MISSING",TOOL_DUPLICATE:"TOOL_DUPLICATE",TOOL_SCHEMA_INVALID:"TOOL_SCHEMA_INVALID",TOOL_USE_RESULT_MISMATCH:"TOOL_USE_RESULT_MISMATCH"},ZL={CONVERSATION_LIMIT_EXCEEDED:"CONVERSATION_LIMIT_EXCEEDED",MONTHLY_REQUEST_COUNT:"MONTHLY_REQUEST_COUNT",OVERAGE_REQUEST_LIMIT_EXCEEDED:"OVERAGE_REQUEST_LIMIT_EXCEEDED"};var AJ=NI(EQ(),1),gJ=NI(vQ(),1);var FJ=NI(BR(),1);import*as aN from"net";import*as Y0 from"tls";import $CI from"assert";import*as HJ from"net";import*as wJ from"http";import{Agent as fCI}from"https";var BN=Symbol("AgentBaseInternalState");class aR extends wJ.Agent{constructor(I){super(I);this[BN]={}}isSecureEndpoint(I){if(I){if(typeof I.secureEndpoint==="boolean")return I.secureEndpoint;if(typeof I.protocol==="string")return I.protocol==="https:"}let{stack:G}=Error();if(typeof G!=="string")return!1;return G.split(`
|
|
57
|
+
GFS4: `),console.error(I)};if(!NG[gG]){if(nw=global[gG]||[],Fz(NG,nw),NG.close=function(I){function G(C,N){return I.call(NG,C,function(Y){if(!Y)Oz();if(typeof N==="function")N.apply(this,arguments)})}return Object.defineProperty(G,hm,{value:I}),G}(NG.close),NG.closeSync=function(I){function G(C){I.apply(NG,arguments),Oz()}return Object.defineProperty(G,hm,{value:I}),G}(NG.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){XW(NG[gG]),jI("assert").equal(NG[gG].length,0)})}var nw;if(!global[gG])Fz(global,NG[gG]);iw.exports=Tw(wdI(NG));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!NG.__patched)iw.exports=Tw(NG),NG.__patched=!0;function Tw(I){hdI(I),I.gracefulify=Tw,I.createReadStream=v,I.createWriteStream=J;var G=I.readFile;I.readFile=C;function C(A,p,D){if(typeof p==="function")D=p,p=null;return q(A,p,D);function q(k,K,B,M){return G(k,K,function(j){if(j&&(j.code==="EMFILE"||j.code==="ENFILE"))Il([q,[k,K,B],j,M||Date.now(),Date.now()]);else if(typeof B==="function")B.apply(this,arguments)})}}var N=I.writeFile;I.writeFile=Y;function Y(A,p,D,q){if(typeof D==="function")q=D,D=null;return k(A,p,D,q);function k(K,B,M,j,WI){return N(K,B,M,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}var Z=I.appendFile;if(Z)I.appendFile=W;function W(A,p,D,q){if(typeof D==="function")q=D,D=null;return k(A,p,D,q);function k(K,B,M,j,WI){return Z(K,B,M,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}var b=I.copyFile;if(b)I.copyFile=l;function l(A,p,D,q){if(typeof D==="function")q=D,D=0;return k(A,p,D,q);function k(K,B,M,j,WI){return b(K,B,M,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}var Q=I.readdir;I.readdir=m;var L=/^v[0-5]\./;function m(A,p,D){if(typeof p==="function")D=p,p=null;var q=L.test(process.version)?function(B,M,j,WI){return Q(B,k(B,M,j,WI))}:function(B,M,j,WI){return Q(B,M,k(B,M,j,WI))};return q(A,p,D);function k(K,B,M,j){return function(WI,r){if(WI&&(WI.code==="EMFILE"||WI.code==="ENFILE"))Il([q,[K,B,M],WI,j||Date.now(),Date.now()]);else{if(r&&r.sort)r.sort();if(typeof M==="function")M.call(this,WI,r)}}}}if(process.version.substr(0,4)==="v0.8"){var V=HdI(I);d=V.ReadStream,F=V.WriteStream}var X=I.ReadStream;if(X)d.prototype=Object.create(X.prototype),d.prototype.open=O;var R=I.WriteStream;if(R)F.prototype=Object.create(R.prototype),F.prototype.open=c;Object.defineProperty(I,"ReadStream",{get:function(){return d},set:function(A){d=A},enumerable:!0,configurable:!0}),Object.defineProperty(I,"WriteStream",{get:function(){return F},set:function(A){F=A},enumerable:!0,configurable:!0});var h=d;Object.defineProperty(I,"FileReadStream",{get:function(){return h},set:function(A){h=A},enumerable:!0,configurable:!0});var H=F;Object.defineProperty(I,"FileWriteStream",{get:function(){return H},set:function(A){H=A},enumerable:!0,configurable:!0});function d(A,p){if(this instanceof d)return X.apply(this,arguments),this;else return d.apply(Object.create(d.prototype),arguments)}function O(){var A=this;g(A.path,A.flags,A.mode,function(p,D){if(p){if(A.autoClose)A.destroy();A.emit("error",p)}else A.fd=D,A.emit("open",D),A.read()})}function F(A,p){if(this instanceof F)return R.apply(this,arguments),this;else return F.apply(Object.create(F.prototype),arguments)}function c(){var A=this;g(A.path,A.flags,A.mode,function(p,D){if(p)A.destroy(),A.emit("error",p);else A.fd=D,A.emit("open",D)})}function v(A,p){return new I.ReadStream(A,p)}function J(A,p){return new I.WriteStream(A,p)}var u=I.open;I.open=g;function g(A,p,D,q){if(typeof D==="function")q=D,D=null;return k(A,p,D,q);function k(K,B,M,j,WI){return u(K,B,M,function(r,GI){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))Il([k,[K,B,M,j],r,WI||Date.now(),Date.now()]);else if(typeof j==="function")j.apply(this,arguments)})}}return I}function Il(I){XW("ENQUEUE",I[0].name,I[1]),NG[gG].push(I),sw()}var Rm;function Oz(){var I=Date.now();for(var G=0;G<NG[gG].length;++G)if(NG[gG][G].length>2)NG[gG][G][3]=I,NG[gG][G][4]=I;sw()}function sw(){if(clearTimeout(Rm),Rm=void 0,NG[gG].length===0)return;var I=NG[gG].shift(),G=I[0],C=I[1],N=I[2],Y=I[3],Z=I[4];if(Y===void 0)XW("RETRY",G.name,C),G.apply(null,C);else if(Date.now()-Y>=60000){XW("TIMEOUT",G.name,C);var W=C.pop();if(typeof W==="function")W.call(null,N)}else{var b=Date.now()-Z,l=Math.max(Z-Y,1),Q=Math.min(l*1.2,100);if(b>=Q)XW("RETRY",G.name,C),G.apply(null,C.concat([Y]));else NG[gG].push(I)}if(Rm===void 0)Rm=setTimeout(sw,0)}});var uz=z((jzI,vz)=>{function PC(I,G){if(typeof G==="boolean")G={forever:G};if(this._originalTimeouts=JSON.parse(JSON.stringify(I)),this._timeouts=I,this._options=G||{},this._maxRetryTime=G&&G.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}vz.exports=PC;PC.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};PC.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};PC.prototype.retry=function(I){if(this._timeout)clearTimeout(this._timeout);if(!I)return!1;var G=new Date().getTime();if(I&&G-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(I);var C=this._timeouts.shift();if(C===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),C=this._timeouts.shift();else return!1;var N=this,Y=setTimeout(function(){if(N._attempts++,N._operationTimeoutCb){if(N._timeout=setTimeout(function(){N._operationTimeoutCb(N._attempts)},N._operationTimeout),N._options.unref)N._timeout.unref()}N._fn(N._attempts)},C);if(this._options.unref)Y.unref();return!0};PC.prototype.attempt=function(I,G){if(this._fn=I,G){if(G.timeout)this._operationTimeout=G.timeout;if(G.cb)this._operationTimeoutCb=G.cb}var C=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){C._operationTimeoutCb()},C._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};PC.prototype.try=function(I){console.log("Using RetryOperation.try() is deprecated"),this.attempt(I)};PC.prototype.start=function(I){console.log("Using RetryOperation.start() is deprecated"),this.attempt(I)};PC.prototype.start=PC.prototype.try;PC.prototype.errors=function(){return this._errors};PC.prototype.attempts=function(){return this._attempts};PC.prototype.mainError=function(){if(this._errors.length===0)return null;var I={},G=null,C=0;for(var N=0;N<this._errors.length;N++){var Y=this._errors[N],Z=Y.message,W=(I[Z]||0)+1;if(I[Z]=W,W>=C)G=Y,C=W}return G}});var Az=z((OdI)=>{var cdI=uz();OdI.operation=function(I){var G=OdI.timeouts(I);return new cdI(G,{forever:I&&I.forever,unref:I&&I.unref,maxRetryTime:I&&I.maxRetryTime})};OdI.timeouts=function(I){if(I instanceof Array)return[].concat(I);var G={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var C in I)G[C]=I[C];if(G.minTimeout>G.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var N=[];for(var Y=0;Y<G.retries;Y++)N.push(this.createTimeout(Y,G));if(I&&I.forever&&!N.length)N.push(this.createTimeout(Y,G));return N.sort(function(Z,W){return Z-W}),N};OdI.createTimeout=function(I,G){var C=G.randomize?Math.random()+1:1,N=Math.round(C*G.minTimeout*Math.pow(G.factor,I));return N=Math.min(N,G.maxTimeout),N};OdI.wrap=function(I,G,C){if(G instanceof Array)C=G,G=null;if(!C){C=[];for(var N in I)if(typeof I[N]==="function")C.push(N)}for(var Y=0;Y<C.length;Y++){var Z=C[Y],W=I[Z];I[Z]=function(l){var Q=OdI.operation(G),L=Array.prototype.slice.call(arguments,1),m=L.pop();L.push(function(V){if(Q.retry(V))return;if(V)arguments[0]=Q.mainError();m.apply(this,arguments)}),Q.attempt(function(){l.apply(I,L)})}.bind(I,W),I[Z].options=G}}});var gz=z((azI,Hm)=>{Hm.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")Hm.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Hm.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var Kz=z((xzI,Cl)=>{var oI=global.process,RW=function(I){return I&&typeof I==="object"&&typeof I.removeListener==="function"&&typeof I.emit==="function"&&typeof I.reallyExit==="function"&&typeof I.listeners==="function"&&typeof I.kill==="function"&&typeof I.pid==="number"&&typeof I.on==="function"};if(!RW(oI))Cl.exports=function(){return function(){}};else{if(fw=jI("assert"),hW=gz(),$w=/^win/i.test(oI.platform),Gl=jI("events"),typeof Gl!=="function")Gl=Gl.EventEmitter;if(oI.__signal_exit_emitter__)dG=oI.__signal_exit_emitter__;else dG=oI.__signal_exit_emitter__=new Gl,dG.count=0,dG.emitted={};if(!dG.infinite)dG.setMaxListeners(1/0),dG.infinite=!0;Cl.exports=function(I,G){if(!RW(global.process))return function(){};if(fw.equal(typeof I,"function","a callback must be provided for exit handler"),HW===!1)wm();var C="exit";if(G&&G.alwaysLast)C="afterexit";var N=function(){if(dG.removeListener(C,I),dG.listeners("exit").length===0&&dG.listeners("afterexit").length===0)W4()};return dG.on(C,I),N},W4=function(){if(!HW||!RW(global.process))return;HW=!1,hW.forEach(function(G){try{oI.removeListener(G,b4[G])}catch(C){}}),oI.emit=l4,oI.reallyExit=dm,dG.count-=1},Cl.exports.unload=W4,QZ=function(G,C,N){if(dG.emitted[G])return;dG.emitted[G]=!0,dG.emit(G,C,N)},b4={},hW.forEach(function(I){b4[I]=function(){if(!RW(global.process))return;var C=oI.listeners(I);if(C.length===dG.count){if(W4(),QZ("exit",null,I),QZ("afterexit",null,I),$w&&I==="SIGHUP")I="SIGINT";oI.kill(oI.pid,I)}}}),Cl.exports.signals=function(){return hW},HW=!1,wm=function(){if(HW||!RW(global.process))return;HW=!0,dG.count+=1,hW=hW.filter(function(G){try{return oI.on(G,b4[G]),!0}catch(C){return!1}}),oI.emit=_w,oI.reallyExit=tw},Cl.exports.load=wm,dm=oI.reallyExit,tw=function(G){if(!RW(global.process))return;oI.exitCode=G||0,QZ("exit",oI.exitCode,null),QZ("afterexit",oI.exitCode,null),dm.call(oI,oI.exitCode)},l4=oI.emit,_w=function(G,C){if(G==="exit"&&RW(global.process)){if(C!==void 0)oI.exitCode=C;var N=l4.apply(this,arguments);return QZ("exit",oI.exitCode,null),QZ("afterexit",oI.exitCode,null),N}else return l4.apply(this,arguments)}}var fw,hW,$w,Gl,dG,W4,QZ,b4,HW,wm,dm,tw,l4,_w});var yz=z((gdI,rw)=>{var kz=Symbol();function JdI(I,G,C){let N=G[kz];if(N)return G.stat(I,(Z,W)=>{if(Z)return C(Z);C(null,W.mtime,N)});let Y=new Date(Math.ceil(Date.now()/1000)*1000+5);G.utimes(I,Y,Y,(Z)=>{if(Z)return C(Z);G.stat(I,(W,b)=>{if(W)return C(W);let l=b.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(G,kz,{value:l}),C(null,b.mtime,l)})})}function AdI(I){let G=Date.now();if(I==="s")G=Math.ceil(G/1000)*1000;return new Date(G)}gdI.probe=JdI;gdI.getMtime=AdI});var qz=z((UdI,L4)=>{var ydI=jI("path"),Id=Pw(),pdI=Az(),EdI=Kz(),pz=yz(),OY={};function Q4(I,G){return G.lockfilePath||`${I}.lock`}function Gd(I,G,C){if(!G.realpath)return C(null,ydI.resolve(I));G.fs.realpath(I,C)}function ew(I,G,C){let N=Q4(I,G);G.fs.mkdir(N,(Y)=>{if(!Y)return pz.probe(N,G.fs,(Z,W,b)=>{if(Z)return G.fs.rmdir(N,()=>{}),C(Z);C(null,W,b)});if(Y.code!=="EEXIST")return C(Y);if(G.stale<=0)return C(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:I}));G.fs.stat(N,(Z,W)=>{if(Z){if(Z.code==="ENOENT")return ew(I,{...G,stale:0},C);return C(Z)}if(!Ez(W,G))return C(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:I}));zz(I,G,(b)=>{if(b)return C(b);ew(I,{...G,stale:0},C)})})})}function Ez(I,G){return I.mtime.getTime()<Date.now()-G.stale}function zz(I,G,C){G.fs.rmdir(Q4(I,G),(N)=>{if(N&&N.code!=="ENOENT")return C(N);C()})}function cm(I,G){let C=OY[I];if(C.updateTimeout)return;if(C.updateDelay=C.updateDelay||G.update,C.updateTimeout=setTimeout(()=>{C.updateTimeout=null,G.fs.stat(C.lockfilePath,(N,Y)=>{let Z=C.lastUpdate+G.stale<Date.now();if(N){if(N.code==="ENOENT"||Z)return ow(I,C,Object.assign(N,{code:"ECOMPROMISED"}));return C.updateDelay=1000,cm(I,G)}if(C.mtime.getTime()!==Y.mtime.getTime())return ow(I,C,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let b=pz.getMtime(C.mtimePrecision);G.fs.utimes(C.lockfilePath,b,b,(l)=>{let Q=C.lastUpdate+G.stale<Date.now();if(C.released)return;if(l){if(l.code==="ENOENT"||Q)return ow(I,C,Object.assign(l,{code:"ECOMPROMISED"}));return C.updateDelay=1000,cm(I,G)}C.mtime=b,C.lastUpdate=Date.now(),C.updateDelay=null,cm(I,G)})})},C.updateDelay),C.updateTimeout.unref)C.updateTimeout.unref()}function ow(I,G,C){if(G.released=!0,G.updateTimeout)clearTimeout(G.updateTimeout);if(OY[I]===G)delete OY[I];G.options.onCompromised(C)}function zdI(I,G,C){G={stale:1e4,update:null,realpath:!0,retries:0,fs:Id,onCompromised:(N)=>{throw N},...G},G.retries=G.retries||0,G.retries=typeof G.retries==="number"?{retries:G.retries}:G.retries,G.stale=Math.max(G.stale||0,2000),G.update=G.update==null?G.stale/2:G.update||0,G.update=Math.max(Math.min(G.update,G.stale/2),1000),Gd(I,G,(N,Y)=>{if(N)return C(N);let Z=pdI.operation(G.retries);Z.attempt(()=>{ew(Y,G,(W,b,l)=>{if(Z.retry(W))return;if(W)return C(Z.mainError());let Q=OY[Y]={lockfilePath:Q4(Y,G),mtime:b,mtimePrecision:l,options:G,lastUpdate:Date.now()};cm(Y,G),C(null,(L)=>{if(Q.released)return L&&L(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));Dz(Y,{...G,realpath:!1},L)})})})})}function Dz(I,G,C){G={fs:Id,realpath:!0,...G},Gd(I,G,(N,Y)=>{if(N)return C(N);let Z=OY[Y];if(!Z)return C(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));Z.updateTimeout&&clearTimeout(Z.updateTimeout),Z.released=!0,delete OY[Y],zz(Y,G,C)})}function DdI(I,G,C){G={stale:1e4,realpath:!0,fs:Id,...G},G.stale=Math.max(G.stale||0,2000),Gd(I,G,(N,Y)=>{if(N)return C(N);G.fs.stat(Q4(Y,G),(Z,W)=>{if(Z)return Z.code==="ENOENT"?C(null,!1):C(Z);return C(null,!Ez(W,G))})})}function qdI(){return OY}EdI(()=>{for(let I in OY){let G=OY[I].options;try{G.fs.rmdirSync(Q4(I,G))}catch(C){}}});UdI.lock=zdI;UdI.unlock=Dz;UdI.check=DdI;UdI.getLocks=qdI});var jz=z((MzI,Uz)=>{var MdI=Pw();function SdI(I){let G=["mkdir","realpath","stat","rmdir","utimes"],C={...I};return G.forEach((N)=>{C[N]=(...Y)=>{let Z=Y.pop(),W;try{W=I[`${N}Sync`](...Y)}catch(b){return Z(b)}Z(null,W)}}),C}function ndI(I){return(...G)=>new Promise((C,N)=>{G.push((Y,Z)=>{if(Y)N(Y);else C(Z)}),I(...G)})}function TdI(I){return(...G)=>{let C,N;if(G.push((Y,Z)=>{C=Y,N=Z}),I(...G),C)throw C;return N}}function sdI(I){if(I={...I},I.fs=SdI(I.fs||MdI),typeof I.retries==="number"&&I.retries>0||I.retries&&typeof I.retries.retries==="number"&&I.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return I}Uz.exports={toPromise:ndI,toSync:TdI,toSyncOptions:sdI}});var az=z((SzI,LZ)=>{var Nl=qz(),{toPromise:Om,toSync:Fm,toSyncOptions:Cd}=jz();async function Bz(I,G){let C=await Om(Nl.lock)(I,G);return Om(C)}function idI(I,G){let C=Fm(Nl.lock)(I,Cd(G));return Fm(C)}function PdI(I,G){return Om(Nl.unlock)(I,G)}function fdI(I,G){return Fm(Nl.unlock)(I,Cd(G))}function $dI(I,G){return Om(Nl.check)(I,G)}function tdI(I,G){return Fm(Nl.check)(I,Cd(G))}LZ.exports=Bz;LZ.exports.lock=Bz;LZ.exports.unlock=PdI;LZ.exports.lockSync=idI;LZ.exports.unlockSync=fdI;LZ.exports.check=$dI;LZ.exports.checkSync=tdI});import{createInterface as pOI}from"readline/promises";var Fd={name:"@sunerpy/kiro-provider",version:"3.7.0",description:"OpenAI Responses-compatible AWS KiroRuntime provider with native and stateless fallback transports",homepage:"https://github.com/sunerpy/kiro-provider#readme",bugs:"https://github.com/sunerpy/kiro-provider/issues",license:"MIT",repository:{type:"git",url:"git+https://github.com/sunerpy/kiro-provider.git"},bin:{"kiro-provider":"dist/cli.js"},files:["dist/cli.js","README.md","LICENSE"],type:"module",publishConfig:{access:"public"},scripts:{fmt:"oxfmt --ignore-path .oxfmtignore --write '**/*.{yml,yaml,json,md}' && biome check --write ./src ./scripts ./__tests__",lint:"biome check ./src ./scripts ./__tests__",typecheck:"tsc --noEmit",test:"bun test",build:"bun run build:npm","build:binary":"bun build --compile --minify src/cli/bin.ts --outfile dist/kiro-provider","build:npm":"bun build src/cli/bin.ts --outfile dist/cli.js --target=bun --minify && chmod +x dist/cli.js","probe:projection-fidelity":"bun run scripts/probe-projection-fidelity.ts","probe:v3-fields":"bun run scripts/probe-v3-request-fields.ts","probe:v3-create-response":"bun run scripts/probe-v3-create-response.ts","study:effort":"bun run scripts/effort-study.ts","study:effort:run":"bun run scripts/run-effort-study.ts","study:effort:responses":"bun run scripts/responses-effort-study.ts","e2e:responses":"bun run scripts/responses-live-e2e.ts","diff:kiro-cli-wire":"bun run scripts/kiro-cli-wire-diff.ts",prepublishOnly:"bun run build:npm","docs:links":"bun run scripts/check-markdown-links.ts","fmt:check":"oxfmt --ignore-path .oxfmtignore --check '**/*.{yml,yaml,json,md}' && biome check ./src ./scripts ./__tests__",check:"bun run fmt:check && bun run typecheck && bun run lint && bun run docs:links && bun run test && bun run build"},dependencies:{"@aws-sdk/core":"3.975.3","@aws/codewhisperer-streaming-client":"^1.0.34","@smithy/node-http-handler":"4.9.7",ajv:"8.20.0","https-proxy-agent":"^9.1.0","js-tiktoken":"1.0.21","proper-lockfile":"^4.1.2",zod:"^3.24.0"},devDependencies:{"@ai-sdk/openai":"4.0.66","@biomejs/biome":"2.2.4","@types/bun":"^1.3.6","@types/node":"^20.0.0","@types/proper-lockfile":"^4.1.4",ai:"7.0.99",openai:"7.13.0",oxfmt:"0.64.0",typescript:"^5.7.3"},engines:{bun:">=1.3.14"},packageManager:"bun@1.3.14"};import{existsSync as VU,readFileSync as XU,statSync as RU}from"fs";var w={};PD(w,{void:()=>Eq,util:()=>gI,unknown:()=>yq,union:()=>Uq,undefined:()=>gq,tuple:()=>aq,transformer:()=>$q,symbol:()=>Aq,string:()=>pd,strictObject:()=>qq,setErrorMap:()=>_D,set:()=>Sq,record:()=>xq,quotelessJson:()=>$D,promise:()=>fq,preprocess:()=>rq,pipeline:()=>oq,ostring:()=>eq,optional:()=>tq,onumber:()=>IU,oboolean:()=>GU,objectUtil:()=>Dm,object:()=>Dq,number:()=>Ed,nullable:()=>_q,null:()=>Kq,never:()=>pq,nativeEnum:()=>Pq,nan:()=>vq,map:()=>Mq,makeIssue:()=>Wl,literal:()=>sq,lazy:()=>Tq,late:()=>Oq,isValid:()=>uY,isDirty:()=>w4,isAsync:()=>cW,isAborted:()=>H4,intersection:()=>Bq,instanceof:()=>Fq,getParsedType:()=>FN,getErrorMap:()=>dW,function:()=>nq,enum:()=>iq,effect:()=>$q,discriminatedUnion:()=>jq,defaultErrorMap:()=>_N,datetimeRegex:()=>Kd,date:()=>Jq,custom:()=>yd,coerce:()=>CU,boolean:()=>zd,bigint:()=>uq,array:()=>zq,any:()=>kq,addIssueToContext:()=>P,ZodVoid:()=>ll,ZodUnknown:()=>JY,ZodUnion:()=>AW,ZodUndefined:()=>uW,ZodType:()=>vI,ZodTuple:()=>uN,ZodTransformer:()=>IN,ZodSymbol:()=>bl,ZodString:()=>_C,ZodSet:()=>RZ,ZodSchema:()=>vI,ZodRecord:()=>Ql,ZodReadonly:()=>zW,ZodPromise:()=>hZ,ZodPipeline:()=>Vl,ZodParsedType:()=>T,ZodOptional:()=>oC,ZodObject:()=>GG,ZodNumber:()=>AY,ZodNullable:()=>oN,ZodNull:()=>JW,ZodNever:()=>vN,ZodNativeEnum:()=>yW,ZodNaN:()=>ml,ZodMap:()=>Ll,ZodLiteral:()=>kW,ZodLazy:()=>KW,ZodIssueCode:()=>x,ZodIntersection:()=>gW,ZodFunction:()=>FW,ZodFirstPartyTypeKind:()=>QI,ZodError:()=>PG,ZodEnum:()=>KY,ZodEffects:()=>IN,ZodDiscriminatedUnion:()=>d4,ZodDefault:()=>pW,ZodDate:()=>VZ,ZodCatch:()=>EW,ZodBranded:()=>c4,ZodBoolean:()=>vW,ZodBigInt:()=>gY,ZodArray:()=>rC,ZodAny:()=>XZ,Schema:()=>vI,ParseStatus:()=>FG,OK:()=>EG,NEVER:()=>NU,INVALID:()=>bI,EMPTY_PATH:()=>rD,DIRTY:()=>mZ,BRAND:()=>cq});var gI;(function(I){I.assertEqual=(Y)=>{};function G(Y){}I.assertIs=G;function C(Y){throw Error()}I.assertNever=C,I.arrayToEnum=(Y)=>{let Z={};for(let W of Y)Z[W]=W;return Z},I.getValidEnumValues=(Y)=>{let Z=I.objectKeys(Y).filter((b)=>typeof Y[Y[b]]!=="number"),W={};for(let b of Z)W[b]=Y[b];return I.objectValues(W)},I.objectValues=(Y)=>{return I.objectKeys(Y).map(function(Z){return Y[Z]})},I.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let Z=[];for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))Z.push(W);return Z},I.find=(Y,Z)=>{for(let W of Y)if(Z(W))return W;return},I.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function N(Y,Z=" | "){return Y.map((W)=>typeof W==="string"?`'${W}'`:W).join(Z)}I.joinValues=N,I.jsonStringifyReplacer=(Y,Z)=>{if(typeof Z==="bigint")return Z.toString();return Z}})(gI||(gI={}));var Dm;(function(I){I.mergeShapes=(G,C)=>{return{...G,...C}}})(Dm||(Dm={}));var T=gI.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),FN=(I)=>{switch(typeof I){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(I)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":if(Array.isArray(I))return T.array;if(I===null)return T.null;if(I.then&&typeof I.then==="function"&&I.catch&&typeof I.catch==="function")return T.promise;if(typeof Map<"u"&&I instanceof Map)return T.map;if(typeof Set<"u"&&I instanceof Set)return T.set;if(typeof Date<"u"&&I instanceof Date)return T.date;return T.object;default:return T.unknown}};var x=gI.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$D=(I)=>{return JSON.stringify(I,null,2).replace(/"([^"]+)":/g,"$1:")};class PG extends Error{get errors(){return this.issues}constructor(I){super();this.issues=[],this.addIssue=(C)=>{this.issues=[...this.issues,C]},this.addIssues=(C=[])=>{this.issues=[...this.issues,...C]};let G=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,G);else this.__proto__=G;this.name="ZodError",this.issues=I}format(I){let G=I||function(Y){return Y.message},C={_errors:[]},N=(Y)=>{for(let Z of Y.issues)if(Z.code==="invalid_union")Z.unionErrors.map(N);else if(Z.code==="invalid_return_type")N(Z.returnTypeError);else if(Z.code==="invalid_arguments")N(Z.argumentsError);else if(Z.path.length===0)C._errors.push(G(Z));else{let W=C,b=0;while(b<Z.path.length){let l=Z.path[b];if(b!==Z.path.length-1)W[l]=W[l]||{_errors:[]};else W[l]=W[l]||{_errors:[]},W[l]._errors.push(G(Z));W=W[l],b++}}};return N(this),C}static assert(I){if(!(I instanceof PG))throw Error(`Not a ZodError: ${I}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,gI.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(I=(G)=>G.message){let G={},C=[];for(let N of this.issues)if(N.path.length>0){let Y=N.path[0];G[Y]=G[Y]||[],G[Y].push(I(N))}else C.push(I(N));return{formErrors:C,fieldErrors:G}}get formErrors(){return this.flatten()}}PG.create=(I)=>{return new PG(I)};var tD=(I,G)=>{let C;switch(I.code){case x.invalid_type:if(I.received===T.undefined)C="Required";else C=`Expected ${I.expected}, received ${I.received}`;break;case x.invalid_literal:C=`Invalid literal value, expected ${JSON.stringify(I.expected,gI.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:C=`Unrecognized key(s) in object: ${gI.joinValues(I.keys,", ")}`;break;case x.invalid_union:C="Invalid input";break;case x.invalid_union_discriminator:C=`Invalid discriminator value. Expected ${gI.joinValues(I.options)}`;break;case x.invalid_enum_value:C=`Invalid enum value. Expected ${gI.joinValues(I.options)}, received '${I.received}'`;break;case x.invalid_arguments:C="Invalid function arguments";break;case x.invalid_return_type:C="Invalid function return type";break;case x.invalid_date:C="Invalid date";break;case x.invalid_string:if(typeof I.validation==="object")if("includes"in I.validation){if(C=`Invalid input: must include "${I.validation.includes}"`,typeof I.validation.position==="number")C=`${C} at one or more positions greater than or equal to ${I.validation.position}`}else if("startsWith"in I.validation)C=`Invalid input: must start with "${I.validation.startsWith}"`;else if("endsWith"in I.validation)C=`Invalid input: must end with "${I.validation.endsWith}"`;else gI.assertNever(I.validation);else if(I.validation!=="regex")C=`Invalid ${I.validation}`;else C="Invalid";break;case x.too_small:if(I.type==="array")C=`Array must contain ${I.exact?"exactly":I.inclusive?"at least":"more than"} ${I.minimum} element(s)`;else if(I.type==="string")C=`String must contain ${I.exact?"exactly":I.inclusive?"at least":"over"} ${I.minimum} character(s)`;else if(I.type==="number")C=`Number must be ${I.exact?"exactly equal to ":I.inclusive?"greater than or equal to ":"greater than "}${I.minimum}`;else if(I.type==="bigint")C=`Number must be ${I.exact?"exactly equal to ":I.inclusive?"greater than or equal to ":"greater than "}${I.minimum}`;else if(I.type==="date")C=`Date must be ${I.exact?"exactly equal to ":I.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(I.minimum))}`;else C="Invalid input";break;case x.too_big:if(I.type==="array")C=`Array must contain ${I.exact?"exactly":I.inclusive?"at most":"less than"} ${I.maximum} element(s)`;else if(I.type==="string")C=`String must contain ${I.exact?"exactly":I.inclusive?"at most":"under"} ${I.maximum} character(s)`;else if(I.type==="number")C=`Number must be ${I.exact?"exactly":I.inclusive?"less than or equal to":"less than"} ${I.maximum}`;else if(I.type==="bigint")C=`BigInt must be ${I.exact?"exactly":I.inclusive?"less than or equal to":"less than"} ${I.maximum}`;else if(I.type==="date")C=`Date must be ${I.exact?"exactly":I.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(I.maximum))}`;else C="Invalid input";break;case x.custom:C="Invalid input";break;case x.invalid_intersection_types:C="Intersection results could not be merged";break;case x.not_multiple_of:C=`Number must be a multiple of ${I.multipleOf}`;break;case x.not_finite:C="Number must be finite";break;default:C=G.defaultError,gI.assertNever(I)}return{message:C}},_N=tD;var vd=_N;function _D(I){vd=I}function dW(){return vd}var Wl=(I)=>{let{data:G,path:C,errorMaps:N,issueData:Y}=I,Z=[...C,...Y.path||[]],W={...Y,path:Z};if(Y.message!==void 0)return{...Y,path:Z,message:Y.message};let b="",l=N.filter((Q)=>!!Q).slice().reverse();for(let Q of l)b=Q(W,{data:G,defaultError:b}).message;return{...Y,path:Z,message:b}},rD=[];function P(I,G){let C=dW(),N=Wl({issueData:G,data:I.data,path:I.path,errorMaps:[I.common.contextualErrorMap,I.schemaErrorMap,C,C===_N?void 0:_N].filter((Y)=>!!Y)});I.common.issues.push(N)}class FG{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(I,G){let C=[];for(let N of G){if(N.status==="aborted")return bI;if(N.status==="dirty")I.dirty();C.push(N.value)}return{status:I.value,value:C}}static async mergeObjectAsync(I,G){let C=[];for(let N of G){let Y=await N.key,Z=await N.value;C.push({key:Y,value:Z})}return FG.mergeObjectSync(I,C)}static mergeObjectSync(I,G){let C={};for(let N of G){let{key:Y,value:Z}=N;if(Y.status==="aborted")return bI;if(Z.status==="aborted")return bI;if(Y.status==="dirty")I.dirty();if(Z.status==="dirty")I.dirty();if(Y.value!=="__proto__"&&(typeof Z.value<"u"||N.alwaysSet))C[Y.value]=Z.value}return{status:I.value,value:C}}}var bI=Object.freeze({status:"aborted"}),mZ=(I)=>({status:"dirty",value:I}),EG=(I)=>({status:"valid",value:I}),H4=(I)=>I.status==="aborted",w4=(I)=>I.status==="dirty",uY=(I)=>I.status==="valid",cW=(I)=>typeof Promise<"u"&&I instanceof Promise;var e;(function(I){I.errToObj=(G)=>typeof G==="string"?{message:G}:G||{},I.toString=(G)=>typeof G==="string"?G:G?.message})(e||(e={}));class eC{constructor(I,G,C,N){this._cachedPath=[],this.parent=I,this.data=G,this._path=C,this._key=N}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var ud=(I,G)=>{if(uY(G))return{success:!0,data:G.value};else{if(!I.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let C=new PG(I.common.issues);return this._error=C,this._error}}}};function HI(I){if(!I)return{};let{errorMap:G,invalid_type_error:C,required_error:N,description:Y}=I;if(G&&(C||N))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(G)return{errorMap:G,description:Y};return{errorMap:(W,b)=>{let{message:l}=I;if(W.code==="invalid_enum_value")return{message:l??b.defaultError};if(typeof b.data>"u")return{message:l??N??b.defaultError};if(W.code!=="invalid_type")return{message:b.defaultError};return{message:l??C??b.defaultError}},description:Y}}class vI{get description(){return this._def.description}_getType(I){return FN(I.data)}_getOrReturnCtx(I,G){return G||{common:I.parent.common,data:I.data,parsedType:FN(I.data),schemaErrorMap:this._def.errorMap,path:I.path,parent:I.parent}}_processInputParams(I){return{status:new FG,ctx:{common:I.parent.common,data:I.data,parsedType:FN(I.data),schemaErrorMap:this._def.errorMap,path:I.path,parent:I.parent}}}_parseSync(I){let G=this._parse(I);if(cW(G))throw Error("Synchronous parse encountered promise.");return G}_parseAsync(I){let G=this._parse(I);return Promise.resolve(G)}parse(I,G){let C=this.safeParse(I,G);if(C.success)return C.data;throw C.error}safeParse(I,G){let C={common:{issues:[],async:G?.async??!1,contextualErrorMap:G?.errorMap},path:G?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:FN(I)},N=this._parseSync({data:I,path:C.path,parent:C});return ud(C,N)}"~validate"(I){let G={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:FN(I)};if(!this["~standard"].async)try{let C=this._parseSync({data:I,path:[],parent:G});return uY(C)?{value:C.value}:{issues:G.common.issues}}catch(C){if(C?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;G.common={issues:[],async:!0}}return this._parseAsync({data:I,path:[],parent:G}).then((C)=>uY(C)?{value:C.value}:{issues:G.common.issues})}async parseAsync(I,G){let C=await this.safeParseAsync(I,G);if(C.success)return C.data;throw C.error}async safeParseAsync(I,G){let C={common:{issues:[],contextualErrorMap:G?.errorMap,async:!0},path:G?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:FN(I)},N=this._parse({data:I,path:C.path,parent:C}),Y=await(cW(N)?N:Promise.resolve(N));return ud(C,Y)}refine(I,G){let C=(N)=>{if(typeof G==="string"||typeof G>"u")return{message:G};else if(typeof G==="function")return G(N);else return G};return this._refinement((N,Y)=>{let Z=I(N),W=()=>Y.addIssue({code:x.custom,...C(N)});if(typeof Promise<"u"&&Z instanceof Promise)return Z.then((b)=>{if(!b)return W(),!1;else return!0});if(!Z)return W(),!1;else return!0})}refinement(I,G){return this._refinement((C,N)=>{if(!I(C))return N.addIssue(typeof G==="function"?G(C,N):G),!1;else return!0})}_refinement(I){return new IN({schema:this,typeName:QI.ZodEffects,effect:{type:"refinement",refinement:I}})}superRefine(I){return this._refinement(I)}constructor(I){this.spa=this.safeParseAsync,this._def=I,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(G)=>this["~validate"](G)}}optional(){return oC.create(this,this._def)}nullable(){return oN.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rC.create(this)}promise(){return hZ.create(this,this._def)}or(I){return AW.create([this,I],this._def)}and(I){return gW.create(this,I,this._def)}transform(I){return new IN({...HI(this._def),schema:this,typeName:QI.ZodEffects,effect:{type:"transform",transform:I}})}default(I){let G=typeof I==="function"?I:()=>I;return new pW({...HI(this._def),innerType:this,defaultValue:G,typeName:QI.ZodDefault})}brand(){return new c4({typeName:QI.ZodBranded,type:this,...HI(this._def)})}catch(I){let G=typeof I==="function"?I:()=>I;return new EW({...HI(this._def),innerType:this,catchValue:G,typeName:QI.ZodCatch})}describe(I){return new this.constructor({...this._def,description:I})}pipe(I){return Vl.create(this,I)}readonly(){return zW.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var oD=/^c[^\s-]{8,}$/i,eD=/^[0-9a-z]+$/,Iq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Gq=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Cq=/^[a-z0-9_-]{21}$/i,Nq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yq=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Zq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qm,bq=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lq=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qq=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Lq=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,mq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ad="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Xq=new RegExp(`^${Ad}$`);function gd(I){let G="[0-5]\\d";if(I.precision)G=`${G}\\.\\d{${I.precision}}`;else if(I.precision==null)G=`${G}(\\.\\d+)?`;let C=I.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${G})${C}`}function Rq(I){return new RegExp(`^${gd(I)}$`)}function Kd(I){let G=`${Ad}T${gd(I)}`,C=[];if(C.push(I.local?"Z?":"Z"),I.offset)C.push("([+-]\\d{2}:?\\d{2})");return G=`${G}(${C.join("|")})`,new RegExp(`^${G}$`)}function hq(I,G){if((G==="v4"||!G)&&bq.test(I))return!0;if((G==="v6"||!G)&&Qq.test(I))return!0;return!1}function Hq(I,G){if(!Nq.test(I))return!1;try{let[C]=I.split(".");if(!C)return!1;let N=C.replace(/-/g,"+").replace(/_/g,"/").padEnd(C.length+(4-C.length%4)%4,"="),Y=JSON.parse(atob(N));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(G&&Y.alg!==G)return!1;return!0}catch{return!1}}function wq(I,G){if((G==="v4"||!G)&&lq.test(I))return!0;if((G==="v6"||!G)&&Lq.test(I))return!0;return!1}class _C extends vI{_parse(I){if(this._def.coerce)I.data=String(I.data);if(this._getType(I)!==T.string){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_type,expected:T.string,received:Y.parsedType}),bI}let C=new FG,N=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(I.data.length<Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),C.dirty()}else if(Y.kind==="max"){if(I.data.length>Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),C.dirty()}else if(Y.kind==="length"){let Z=I.data.length>Y.value,W=I.data.length<Y.value;if(Z||W){if(N=this._getOrReturnCtx(I,N),Z)P(N,{code:x.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(W)P(N,{code:x.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});C.dirty()}}else if(Y.kind==="email"){if(!Zq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"email",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="emoji"){if(!qm)qm=new RegExp(Wq,"u");if(!qm.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"emoji",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="uuid"){if(!Gq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"uuid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="nanoid"){if(!Cq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"nanoid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="cuid"){if(!oD.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"cuid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="cuid2"){if(!eD.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"cuid2",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="ulid"){if(!Iq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"ulid",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="url")try{new URL(I.data)}catch{N=this._getOrReturnCtx(I,N),P(N,{validation:"url",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"regex",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="trim")I.data=I.data.trim();else if(Y.kind==="includes"){if(!I.data.includes(Y.value,Y.position))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),C.dirty()}else if(Y.kind==="toLowerCase")I.data=I.data.toLowerCase();else if(Y.kind==="toUpperCase")I.data=I.data.toUpperCase();else if(Y.kind==="startsWith"){if(!I.data.startsWith(Y.value))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:{startsWith:Y.value},message:Y.message}),C.dirty()}else if(Y.kind==="endsWith"){if(!I.data.endsWith(Y.value))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:{endsWith:Y.value},message:Y.message}),C.dirty()}else if(Y.kind==="datetime"){if(!Kd(Y).test(I.data))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:"datetime",message:Y.message}),C.dirty()}else if(Y.kind==="date"){if(!Xq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:"date",message:Y.message}),C.dirty()}else if(Y.kind==="time"){if(!Rq(Y).test(I.data))N=this._getOrReturnCtx(I,N),P(N,{code:x.invalid_string,validation:"time",message:Y.message}),C.dirty()}else if(Y.kind==="duration"){if(!Yq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"duration",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="ip"){if(!hq(I.data,Y.version))N=this._getOrReturnCtx(I,N),P(N,{validation:"ip",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="jwt"){if(!Hq(I.data,Y.alg))N=this._getOrReturnCtx(I,N),P(N,{validation:"jwt",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="cidr"){if(!wq(I.data,Y.version))N=this._getOrReturnCtx(I,N),P(N,{validation:"cidr",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="base64"){if(!mq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"base64",code:x.invalid_string,message:Y.message}),C.dirty()}else if(Y.kind==="base64url"){if(!Vq.test(I.data))N=this._getOrReturnCtx(I,N),P(N,{validation:"base64url",code:x.invalid_string,message:Y.message}),C.dirty()}else gI.assertNever(Y);return{status:C.value,value:I.data}}_regex(I,G,C){return this.refinement((N)=>I.test(N),{validation:G,code:x.invalid_string,...e.errToObj(C)})}_addCheck(I){return new _C({...this._def,checks:[...this._def.checks,I]})}email(I){return this._addCheck({kind:"email",...e.errToObj(I)})}url(I){return this._addCheck({kind:"url",...e.errToObj(I)})}emoji(I){return this._addCheck({kind:"emoji",...e.errToObj(I)})}uuid(I){return this._addCheck({kind:"uuid",...e.errToObj(I)})}nanoid(I){return this._addCheck({kind:"nanoid",...e.errToObj(I)})}cuid(I){return this._addCheck({kind:"cuid",...e.errToObj(I)})}cuid2(I){return this._addCheck({kind:"cuid2",...e.errToObj(I)})}ulid(I){return this._addCheck({kind:"ulid",...e.errToObj(I)})}base64(I){return this._addCheck({kind:"base64",...e.errToObj(I)})}base64url(I){return this._addCheck({kind:"base64url",...e.errToObj(I)})}jwt(I){return this._addCheck({kind:"jwt",...e.errToObj(I)})}ip(I){return this._addCheck({kind:"ip",...e.errToObj(I)})}cidr(I){return this._addCheck({kind:"cidr",...e.errToObj(I)})}datetime(I){if(typeof I==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:I});return this._addCheck({kind:"datetime",precision:typeof I?.precision>"u"?null:I?.precision,offset:I?.offset??!1,local:I?.local??!1,...e.errToObj(I?.message)})}date(I){return this._addCheck({kind:"date",message:I})}time(I){if(typeof I==="string")return this._addCheck({kind:"time",precision:null,message:I});return this._addCheck({kind:"time",precision:typeof I?.precision>"u"?null:I?.precision,...e.errToObj(I?.message)})}duration(I){return this._addCheck({kind:"duration",...e.errToObj(I)})}regex(I,G){return this._addCheck({kind:"regex",regex:I,...e.errToObj(G)})}includes(I,G){return this._addCheck({kind:"includes",value:I,position:G?.position,...e.errToObj(G?.message)})}startsWith(I,G){return this._addCheck({kind:"startsWith",value:I,...e.errToObj(G)})}endsWith(I,G){return this._addCheck({kind:"endsWith",value:I,...e.errToObj(G)})}min(I,G){return this._addCheck({kind:"min",value:I,...e.errToObj(G)})}max(I,G){return this._addCheck({kind:"max",value:I,...e.errToObj(G)})}length(I,G){return this._addCheck({kind:"length",value:I,...e.errToObj(G)})}nonempty(I){return this.min(1,e.errToObj(I))}trim(){return new _C({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _C({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _C({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((I)=>I.kind==="datetime")}get isDate(){return!!this._def.checks.find((I)=>I.kind==="date")}get isTime(){return!!this._def.checks.find((I)=>I.kind==="time")}get isDuration(){return!!this._def.checks.find((I)=>I.kind==="duration")}get isEmail(){return!!this._def.checks.find((I)=>I.kind==="email")}get isURL(){return!!this._def.checks.find((I)=>I.kind==="url")}get isEmoji(){return!!this._def.checks.find((I)=>I.kind==="emoji")}get isUUID(){return!!this._def.checks.find((I)=>I.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((I)=>I.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((I)=>I.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((I)=>I.kind==="cuid2")}get isULID(){return!!this._def.checks.find((I)=>I.kind==="ulid")}get isIP(){return!!this._def.checks.find((I)=>I.kind==="ip")}get isCIDR(){return!!this._def.checks.find((I)=>I.kind==="cidr")}get isBase64(){return!!this._def.checks.find((I)=>I.kind==="base64")}get isBase64url(){return!!this._def.checks.find((I)=>I.kind==="base64url")}get minLength(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I}get maxLength(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I}}_C.create=(I)=>{return new _C({checks:[],typeName:QI.ZodString,coerce:I?.coerce??!1,...HI(I)})};function dq(I,G){let C=(I.toString().split(".")[1]||"").length,N=(G.toString().split(".")[1]||"").length,Y=C>N?C:N,Z=Number.parseInt(I.toFixed(Y).replace(".","")),W=Number.parseInt(G.toFixed(Y).replace(".",""));return Z%W/10**Y}class AY extends vI{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(I){if(this._def.coerce)I.data=Number(I.data);if(this._getType(I)!==T.number){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_type,expected:T.number,received:Y.parsedType}),bI}let C=void 0,N=new FG;for(let Y of this._def.checks)if(Y.kind==="int"){if(!gI.isInteger(I.data))C=this._getOrReturnCtx(I,C),P(C,{code:x.invalid_type,expected:"integer",received:"float",message:Y.message}),N.dirty()}else if(Y.kind==="min"){if(Y.inclusive?I.data<Y.value:I.data<=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),N.dirty()}else if(Y.kind==="max"){if(Y.inclusive?I.data>Y.value:I.data>=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),N.dirty()}else if(Y.kind==="multipleOf"){if(dq(I.data,Y.value)!==0)C=this._getOrReturnCtx(I,C),P(C,{code:x.not_multiple_of,multipleOf:Y.value,message:Y.message}),N.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(I.data))C=this._getOrReturnCtx(I,C),P(C,{code:x.not_finite,message:Y.message}),N.dirty()}else gI.assertNever(Y);return{status:N.value,value:I.data}}gte(I,G){return this.setLimit("min",I,!0,e.toString(G))}gt(I,G){return this.setLimit("min",I,!1,e.toString(G))}lte(I,G){return this.setLimit("max",I,!0,e.toString(G))}lt(I,G){return this.setLimit("max",I,!1,e.toString(G))}setLimit(I,G,C,N){return new AY({...this._def,checks:[...this._def.checks,{kind:I,value:G,inclusive:C,message:e.toString(N)}]})}_addCheck(I){return new AY({...this._def,checks:[...this._def.checks,I]})}int(I){return this._addCheck({kind:"int",message:e.toString(I)})}positive(I){return this._addCheck({kind:"min",value:0,inclusive:!1,message:e.toString(I)})}negative(I){return this._addCheck({kind:"max",value:0,inclusive:!1,message:e.toString(I)})}nonpositive(I){return this._addCheck({kind:"max",value:0,inclusive:!0,message:e.toString(I)})}nonnegative(I){return this._addCheck({kind:"min",value:0,inclusive:!0,message:e.toString(I)})}multipleOf(I,G){return this._addCheck({kind:"multipleOf",value:I,message:e.toString(G)})}finite(I){return this._addCheck({kind:"finite",message:e.toString(I)})}safe(I){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:e.toString(I)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:e.toString(I)})}get minValue(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I}get maxValue(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I}get isInt(){return!!this._def.checks.find((I)=>I.kind==="int"||I.kind==="multipleOf"&&gI.isInteger(I.value))}get isFinite(){let I=null,G=null;for(let C of this._def.checks)if(C.kind==="finite"||C.kind==="int"||C.kind==="multipleOf")return!0;else if(C.kind==="min"){if(G===null||C.value>G)G=C.value}else if(C.kind==="max"){if(I===null||C.value<I)I=C.value}return Number.isFinite(G)&&Number.isFinite(I)}}AY.create=(I)=>{return new AY({checks:[],typeName:QI.ZodNumber,coerce:I?.coerce||!1,...HI(I)})};class gY extends vI{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(I){if(this._def.coerce)try{I.data=BigInt(I.data)}catch{return this._getInvalidInput(I)}if(this._getType(I)!==T.bigint)return this._getInvalidInput(I);let C=void 0,N=new FG;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?I.data<Y.value:I.data<=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),N.dirty()}else if(Y.kind==="max"){if(Y.inclusive?I.data>Y.value:I.data>=Y.value)C=this._getOrReturnCtx(I,C),P(C,{code:x.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),N.dirty()}else if(Y.kind==="multipleOf"){if(I.data%Y.value!==BigInt(0))C=this._getOrReturnCtx(I,C),P(C,{code:x.not_multiple_of,multipleOf:Y.value,message:Y.message}),N.dirty()}else gI.assertNever(Y);return{status:N.value,value:I.data}}_getInvalidInput(I){let G=this._getOrReturnCtx(I);return P(G,{code:x.invalid_type,expected:T.bigint,received:G.parsedType}),bI}gte(I,G){return this.setLimit("min",I,!0,e.toString(G))}gt(I,G){return this.setLimit("min",I,!1,e.toString(G))}lte(I,G){return this.setLimit("max",I,!0,e.toString(G))}lt(I,G){return this.setLimit("max",I,!1,e.toString(G))}setLimit(I,G,C,N){return new gY({...this._def,checks:[...this._def.checks,{kind:I,value:G,inclusive:C,message:e.toString(N)}]})}_addCheck(I){return new gY({...this._def,checks:[...this._def.checks,I]})}positive(I){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:e.toString(I)})}negative(I){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:e.toString(I)})}nonpositive(I){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:e.toString(I)})}nonnegative(I){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:e.toString(I)})}multipleOf(I,G){return this._addCheck({kind:"multipleOf",value:I,message:e.toString(G)})}get minValue(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I}get maxValue(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I}}gY.create=(I)=>{return new gY({checks:[],typeName:QI.ZodBigInt,coerce:I?.coerce??!1,...HI(I)})};class vW extends vI{_parse(I){if(this._def.coerce)I.data=Boolean(I.data);if(this._getType(I)!==T.boolean){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.boolean,received:C.parsedType}),bI}return EG(I.data)}}vW.create=(I)=>{return new vW({typeName:QI.ZodBoolean,coerce:I?.coerce||!1,...HI(I)})};class VZ extends vI{_parse(I){if(this._def.coerce)I.data=new Date(I.data);if(this._getType(I)!==T.date){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_type,expected:T.date,received:Y.parsedType}),bI}if(Number.isNaN(I.data.getTime())){let Y=this._getOrReturnCtx(I);return P(Y,{code:x.invalid_date}),bI}let C=new FG,N=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(I.data.getTime()<Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),C.dirty()}else if(Y.kind==="max"){if(I.data.getTime()>Y.value)N=this._getOrReturnCtx(I,N),P(N,{code:x.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),C.dirty()}else gI.assertNever(Y);return{status:C.value,value:new Date(I.data.getTime())}}_addCheck(I){return new VZ({...this._def,checks:[...this._def.checks,I]})}min(I,G){return this._addCheck({kind:"min",value:I.getTime(),message:e.toString(G)})}max(I,G){return this._addCheck({kind:"max",value:I.getTime(),message:e.toString(G)})}get minDate(){let I=null;for(let G of this._def.checks)if(G.kind==="min"){if(I===null||G.value>I)I=G.value}return I!=null?new Date(I):null}get maxDate(){let I=null;for(let G of this._def.checks)if(G.kind==="max"){if(I===null||G.value<I)I=G.value}return I!=null?new Date(I):null}}VZ.create=(I)=>{return new VZ({checks:[],coerce:I?.coerce||!1,typeName:QI.ZodDate,...HI(I)})};class bl extends vI{_parse(I){if(this._getType(I)!==T.symbol){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.symbol,received:C.parsedType}),bI}return EG(I.data)}}bl.create=(I)=>{return new bl({typeName:QI.ZodSymbol,...HI(I)})};class uW extends vI{_parse(I){if(this._getType(I)!==T.undefined){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.undefined,received:C.parsedType}),bI}return EG(I.data)}}uW.create=(I)=>{return new uW({typeName:QI.ZodUndefined,...HI(I)})};class JW extends vI{_parse(I){if(this._getType(I)!==T.null){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.null,received:C.parsedType}),bI}return EG(I.data)}}JW.create=(I)=>{return new JW({typeName:QI.ZodNull,...HI(I)})};class XZ extends vI{constructor(){super(...arguments);this._any=!0}_parse(I){return EG(I.data)}}XZ.create=(I)=>{return new XZ({typeName:QI.ZodAny,...HI(I)})};class JY extends vI{constructor(){super(...arguments);this._unknown=!0}_parse(I){return EG(I.data)}}JY.create=(I)=>{return new JY({typeName:QI.ZodUnknown,...HI(I)})};class vN extends vI{_parse(I){let G=this._getOrReturnCtx(I);return P(G,{code:x.invalid_type,expected:T.never,received:G.parsedType}),bI}}vN.create=(I)=>{return new vN({typeName:QI.ZodNever,...HI(I)})};class ll extends vI{_parse(I){if(this._getType(I)!==T.undefined){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.void,received:C.parsedType}),bI}return EG(I.data)}}ll.create=(I)=>{return new ll({typeName:QI.ZodVoid,...HI(I)})};class rC extends vI{_parse(I){let{ctx:G,status:C}=this._processInputParams(I),N=this._def;if(G.parsedType!==T.array)return P(G,{code:x.invalid_type,expected:T.array,received:G.parsedType}),bI;if(N.exactLength!==null){let Z=G.data.length>N.exactLength.value,W=G.data.length<N.exactLength.value;if(Z||W)P(G,{code:Z?x.too_big:x.too_small,minimum:W?N.exactLength.value:void 0,maximum:Z?N.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:N.exactLength.message}),C.dirty()}if(N.minLength!==null){if(G.data.length<N.minLength.value)P(G,{code:x.too_small,minimum:N.minLength.value,type:"array",inclusive:!0,exact:!1,message:N.minLength.message}),C.dirty()}if(N.maxLength!==null){if(G.data.length>N.maxLength.value)P(G,{code:x.too_big,maximum:N.maxLength.value,type:"array",inclusive:!0,exact:!1,message:N.maxLength.message}),C.dirty()}if(G.common.async)return Promise.all([...G.data].map((Z,W)=>{return N.type._parseAsync(new eC(G,Z,G.path,W))})).then((Z)=>{return FG.mergeArray(C,Z)});let Y=[...G.data].map((Z,W)=>{return N.type._parseSync(new eC(G,Z,G.path,W))});return FG.mergeArray(C,Y)}get element(){return this._def.type}min(I,G){return new rC({...this._def,minLength:{value:I,message:e.toString(G)}})}max(I,G){return new rC({...this._def,maxLength:{value:I,message:e.toString(G)}})}length(I,G){return new rC({...this._def,exactLength:{value:I,message:e.toString(G)}})}nonempty(I){return this.min(1,I)}}rC.create=(I,G)=>{return new rC({type:I,minLength:null,maxLength:null,exactLength:null,typeName:QI.ZodArray,...HI(G)})};function OW(I){if(I instanceof GG){let G={};for(let C in I.shape){let N=I.shape[C];G[C]=oC.create(OW(N))}return new GG({...I._def,shape:()=>G})}else if(I instanceof rC)return new rC({...I._def,type:OW(I.element)});else if(I instanceof oC)return oC.create(OW(I.unwrap()));else if(I instanceof oN)return oN.create(OW(I.unwrap()));else if(I instanceof uN)return uN.create(I.items.map((G)=>OW(G)));else return I}class GG extends vI{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let I=this._def.shape(),G=gI.objectKeys(I);return this._cached={shape:I,keys:G},this._cached}_parse(I){if(this._getType(I)!==T.object){let l=this._getOrReturnCtx(I);return P(l,{code:x.invalid_type,expected:T.object,received:l.parsedType}),bI}let{status:C,ctx:N}=this._processInputParams(I),{shape:Y,keys:Z}=this._getCached(),W=[];if(!(this._def.catchall instanceof vN&&this._def.unknownKeys==="strip")){for(let l in N.data)if(!Z.includes(l))W.push(l)}let b=[];for(let l of Z){let Q=Y[l],L=N.data[l];b.push({key:{status:"valid",value:l},value:Q._parse(new eC(N,L,N.path,l)),alwaysSet:l in N.data})}if(this._def.catchall instanceof vN){let l=this._def.unknownKeys;if(l==="passthrough")for(let Q of W)b.push({key:{status:"valid",value:Q},value:{status:"valid",value:N.data[Q]}});else if(l==="strict"){if(W.length>0)P(N,{code:x.unrecognized_keys,keys:W}),C.dirty()}else if(l==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let Q of W){let L=N.data[Q];b.push({key:{status:"valid",value:Q},value:l._parse(new eC(N,L,N.path,Q)),alwaysSet:Q in N.data})}}if(N.common.async)return Promise.resolve().then(async()=>{let l=[];for(let Q of b){let L=await Q.key,m=await Q.value;l.push({key:L,value:m,alwaysSet:Q.alwaysSet})}return l}).then((l)=>{return FG.mergeObjectSync(C,l)});else return FG.mergeObjectSync(C,b)}get shape(){return this._def.shape()}strict(I){return e.errToObj,new GG({...this._def,unknownKeys:"strict",...I!==void 0?{errorMap:(G,C)=>{let N=this._def.errorMap?.(G,C).message??C.defaultError;if(G.code==="unrecognized_keys")return{message:e.errToObj(I).message??N};return{message:N}}}:{}})}strip(){return new GG({...this._def,unknownKeys:"strip"})}passthrough(){return new GG({...this._def,unknownKeys:"passthrough"})}extend(I){return new GG({...this._def,shape:()=>({...this._def.shape(),...I})})}merge(I){return new GG({unknownKeys:I._def.unknownKeys,catchall:I._def.catchall,shape:()=>({...this._def.shape(),...I._def.shape()}),typeName:QI.ZodObject})}setKey(I,G){return this.augment({[I]:G})}catchall(I){return new GG({...this._def,catchall:I})}pick(I){let G={};for(let C of gI.objectKeys(I))if(I[C]&&this.shape[C])G[C]=this.shape[C];return new GG({...this._def,shape:()=>G})}omit(I){let G={};for(let C of gI.objectKeys(this.shape))if(!I[C])G[C]=this.shape[C];return new GG({...this._def,shape:()=>G})}deepPartial(){return OW(this)}partial(I){let G={};for(let C of gI.objectKeys(this.shape)){let N=this.shape[C];if(I&&!I[C])G[C]=N;else G[C]=N.optional()}return new GG({...this._def,shape:()=>G})}required(I){let G={};for(let C of gI.objectKeys(this.shape))if(I&&!I[C])G[C]=this.shape[C];else{let Y=this.shape[C];while(Y instanceof oC)Y=Y._def.innerType;G[C]=Y}return new GG({...this._def,shape:()=>G})}keyof(){return kd(gI.objectKeys(this.shape))}}GG.create=(I,G)=>{return new GG({shape:()=>I,unknownKeys:"strip",catchall:vN.create(),typeName:QI.ZodObject,...HI(G)})};GG.strictCreate=(I,G)=>{return new GG({shape:()=>I,unknownKeys:"strict",catchall:vN.create(),typeName:QI.ZodObject,...HI(G)})};GG.lazycreate=(I,G)=>{return new GG({shape:I,unknownKeys:"strip",catchall:vN.create(),typeName:QI.ZodObject,...HI(G)})};class AW extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C=this._def.options;function N(Y){for(let W of Y)if(W.result.status==="valid")return W.result;for(let W of Y)if(W.result.status==="dirty")return G.common.issues.push(...W.ctx.common.issues),W.result;let Z=Y.map((W)=>new PG(W.ctx.common.issues));return P(G,{code:x.invalid_union,unionErrors:Z}),bI}if(G.common.async)return Promise.all(C.map(async(Y)=>{let Z={...G,common:{...G.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:G.data,path:G.path,parent:Z}),ctx:Z}})).then(N);else{let Y=void 0,Z=[];for(let b of C){let l={...G,common:{...G.common,issues:[]},parent:null},Q=b._parseSync({data:G.data,path:G.path,parent:l});if(Q.status==="valid")return Q;else if(Q.status==="dirty"&&!Y)Y={result:Q,ctx:l};if(l.common.issues.length)Z.push(l.common.issues)}if(Y)return G.common.issues.push(...Y.ctx.common.issues),Y.result;let W=Z.map((b)=>new PG(b));return P(G,{code:x.invalid_union,unionErrors:W}),bI}}get options(){return this._def.options}}AW.create=(I,G)=>{return new AW({options:I,typeName:QI.ZodUnion,...HI(G)})};var rN=(I)=>{if(I instanceof KW)return rN(I.schema);else if(I instanceof IN)return rN(I.innerType());else if(I instanceof kW)return[I.value];else if(I instanceof KY)return I.options;else if(I instanceof yW)return gI.objectValues(I.enum);else if(I instanceof pW)return rN(I._def.innerType);else if(I instanceof uW)return[void 0];else if(I instanceof JW)return[null];else if(I instanceof oC)return[void 0,...rN(I.unwrap())];else if(I instanceof oN)return[null,...rN(I.unwrap())];else if(I instanceof c4)return rN(I.unwrap());else if(I instanceof zW)return rN(I.unwrap());else if(I instanceof EW)return rN(I._def.innerType);else return[]};class d4 extends vI{_parse(I){let{ctx:G}=this._processInputParams(I);if(G.parsedType!==T.object)return P(G,{code:x.invalid_type,expected:T.object,received:G.parsedType}),bI;let C=this.discriminator,N=G.data[C],Y=this.optionsMap.get(N);if(!Y)return P(G,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[C]}),bI;if(G.common.async)return Y._parseAsync({data:G.data,path:G.path,parent:G});else return Y._parseSync({data:G.data,path:G.path,parent:G})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(I,G,C){let N=new Map;for(let Y of G){let Z=rN(Y.shape[I]);if(!Z.length)throw Error(`A discriminator value for key \`${I}\` could not be extracted from all schema options`);for(let W of Z){if(N.has(W))throw Error(`Discriminator property ${String(I)} has duplicate value ${String(W)}`);N.set(W,Y)}}return new d4({typeName:QI.ZodDiscriminatedUnion,discriminator:I,options:G,optionsMap:N,...HI(C)})}}function Um(I,G){let C=FN(I),N=FN(G);if(I===G)return{valid:!0,data:I};else if(C===T.object&&N===T.object){let Y=gI.objectKeys(G),Z=gI.objectKeys(I).filter((b)=>Y.indexOf(b)!==-1),W={...I,...G};for(let b of Z){let l=Um(I[b],G[b]);if(!l.valid)return{valid:!1};W[b]=l.data}return{valid:!0,data:W}}else if(C===T.array&&N===T.array){if(I.length!==G.length)return{valid:!1};let Y=[];for(let Z=0;Z<I.length;Z++){let W=I[Z],b=G[Z],l=Um(W,b);if(!l.valid)return{valid:!1};Y.push(l.data)}return{valid:!0,data:Y}}else if(C===T.date&&N===T.date&&+I===+G)return{valid:!0,data:I};else return{valid:!1}}class gW extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I),N=(Y,Z)=>{if(H4(Y)||H4(Z))return bI;let W=Um(Y.value,Z.value);if(!W.valid)return P(C,{code:x.invalid_intersection_types}),bI;if(w4(Y)||w4(Z))G.dirty();return{status:G.value,value:W.data}};if(C.common.async)return Promise.all([this._def.left._parseAsync({data:C.data,path:C.path,parent:C}),this._def.right._parseAsync({data:C.data,path:C.path,parent:C})]).then(([Y,Z])=>N(Y,Z));else return N(this._def.left._parseSync({data:C.data,path:C.path,parent:C}),this._def.right._parseSync({data:C.data,path:C.path,parent:C}))}}gW.create=(I,G,C)=>{return new gW({left:I,right:G,typeName:QI.ZodIntersection,...HI(C)})};class uN extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.array)return P(C,{code:x.invalid_type,expected:T.array,received:C.parsedType}),bI;if(C.data.length<this._def.items.length)return P(C,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bI;if(!this._def.rest&&C.data.length>this._def.items.length)P(C,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G.dirty();let Y=[...C.data].map((Z,W)=>{let b=this._def.items[W]||this._def.rest;if(!b)return null;return b._parse(new eC(C,Z,C.path,W))}).filter((Z)=>!!Z);if(C.common.async)return Promise.all(Y).then((Z)=>{return FG.mergeArray(G,Z)});else return FG.mergeArray(G,Y)}get items(){return this._def.items}rest(I){return new uN({...this._def,rest:I})}}uN.create=(I,G)=>{if(!Array.isArray(I))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new uN({items:I,typeName:QI.ZodTuple,rest:null,...HI(G)})};class Ql extends vI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.object)return P(C,{code:x.invalid_type,expected:T.object,received:C.parsedType}),bI;let N=[],Y=this._def.keyType,Z=this._def.valueType;for(let W in C.data)N.push({key:Y._parse(new eC(C,W,C.path,W)),value:Z._parse(new eC(C,C.data[W],C.path,W)),alwaysSet:W in C.data});if(C.common.async)return FG.mergeObjectAsync(G,N);else return FG.mergeObjectSync(G,N)}get element(){return this._def.valueType}static create(I,G,C){if(G instanceof vI)return new Ql({keyType:I,valueType:G,typeName:QI.ZodRecord,...HI(C)});return new Ql({keyType:_C.create(),valueType:I,typeName:QI.ZodRecord,...HI(G)})}}class Ll extends vI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.map)return P(C,{code:x.invalid_type,expected:T.map,received:C.parsedType}),bI;let N=this._def.keyType,Y=this._def.valueType,Z=[...C.data.entries()].map(([W,b],l)=>{return{key:N._parse(new eC(C,W,C.path,[l,"key"])),value:Y._parse(new eC(C,b,C.path,[l,"value"]))}});if(C.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let b of Z){let l=await b.key,Q=await b.value;if(l.status==="aborted"||Q.status==="aborted")return bI;if(l.status==="dirty"||Q.status==="dirty")G.dirty();W.set(l.value,Q.value)}return{status:G.value,value:W}})}else{let W=new Map;for(let b of Z){let{key:l,value:Q}=b;if(l.status==="aborted"||Q.status==="aborted")return bI;if(l.status==="dirty"||Q.status==="dirty")G.dirty();W.set(l.value,Q.value)}return{status:G.value,value:W}}}}Ll.create=(I,G,C)=>{return new Ll({valueType:G,keyType:I,typeName:QI.ZodMap,...HI(C)})};class RZ extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.parsedType!==T.set)return P(C,{code:x.invalid_type,expected:T.set,received:C.parsedType}),bI;let N=this._def;if(N.minSize!==null){if(C.data.size<N.minSize.value)P(C,{code:x.too_small,minimum:N.minSize.value,type:"set",inclusive:!0,exact:!1,message:N.minSize.message}),G.dirty()}if(N.maxSize!==null){if(C.data.size>N.maxSize.value)P(C,{code:x.too_big,maximum:N.maxSize.value,type:"set",inclusive:!0,exact:!1,message:N.maxSize.message}),G.dirty()}let Y=this._def.valueType;function Z(b){let l=new Set;for(let Q of b){if(Q.status==="aborted")return bI;if(Q.status==="dirty")G.dirty();l.add(Q.value)}return{status:G.value,value:l}}let W=[...C.data.values()].map((b,l)=>Y._parse(new eC(C,b,C.path,l)));if(C.common.async)return Promise.all(W).then((b)=>Z(b));else return Z(W)}min(I,G){return new RZ({...this._def,minSize:{value:I,message:e.toString(G)}})}max(I,G){return new RZ({...this._def,maxSize:{value:I,message:e.toString(G)}})}size(I,G){return this.min(I,G).max(I,G)}nonempty(I){return this.min(1,I)}}RZ.create=(I,G)=>{return new RZ({valueType:I,minSize:null,maxSize:null,typeName:QI.ZodSet,...HI(G)})};class FW extends vI{constructor(){super(...arguments);this.validate=this.implement}_parse(I){let{ctx:G}=this._processInputParams(I);if(G.parsedType!==T.function)return P(G,{code:x.invalid_type,expected:T.function,received:G.parsedType}),bI;function C(W,b){return Wl({data:W,path:G.path,errorMaps:[G.common.contextualErrorMap,G.schemaErrorMap,dW(),_N].filter((l)=>!!l),issueData:{code:x.invalid_arguments,argumentsError:b}})}function N(W,b){return Wl({data:W,path:G.path,errorMaps:[G.common.contextualErrorMap,G.schemaErrorMap,dW(),_N].filter((l)=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:b}})}let Y={errorMap:G.common.contextualErrorMap},Z=G.data;if(this._def.returns instanceof hZ){let W=this;return EG(async function(...b){let l=new PG([]),Q=await W._def.args.parseAsync(b,Y).catch((V)=>{throw l.addIssue(C(b,V)),l}),L=await Reflect.apply(Z,this,Q);return await W._def.returns._def.type.parseAsync(L,Y).catch((V)=>{throw l.addIssue(N(L,V)),l})})}else{let W=this;return EG(function(...b){let l=W._def.args.safeParse(b,Y);if(!l.success)throw new PG([C(b,l.error)]);let Q=Reflect.apply(Z,this,l.data),L=W._def.returns.safeParse(Q,Y);if(!L.success)throw new PG([N(Q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...I){return new FW({...this._def,args:uN.create(I).rest(JY.create())})}returns(I){return new FW({...this._def,returns:I})}implement(I){return this.parse(I)}strictImplement(I){return this.parse(I)}static create(I,G,C){return new FW({args:I?I:uN.create([]).rest(JY.create()),returns:G||JY.create(),typeName:QI.ZodFunction,...HI(C)})}}class KW extends vI{get schema(){return this._def.getter()}_parse(I){let{ctx:G}=this._processInputParams(I);return this._def.getter()._parse({data:G.data,path:G.path,parent:G})}}KW.create=(I,G)=>{return new KW({getter:I,typeName:QI.ZodLazy,...HI(G)})};class kW extends vI{_parse(I){if(I.data!==this._def.value){let G=this._getOrReturnCtx(I);return P(G,{received:G.data,code:x.invalid_literal,expected:this._def.value}),bI}return{status:"valid",value:I.data}}get value(){return this._def.value}}kW.create=(I,G)=>{return new kW({value:I,typeName:QI.ZodLiteral,...HI(G)})};function kd(I,G){return new KY({values:I,typeName:QI.ZodEnum,...HI(G)})}class KY extends vI{_parse(I){if(typeof I.data!=="string"){let G=this._getOrReturnCtx(I),C=this._def.values;return P(G,{expected:gI.joinValues(C),received:G.parsedType,code:x.invalid_type}),bI}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(I.data)){let G=this._getOrReturnCtx(I),C=this._def.values;return P(G,{received:G.data,code:x.invalid_enum_value,options:C}),bI}return EG(I.data)}get options(){return this._def.values}get enum(){let I={};for(let G of this._def.values)I[G]=G;return I}get Values(){let I={};for(let G of this._def.values)I[G]=G;return I}get Enum(){let I={};for(let G of this._def.values)I[G]=G;return I}extract(I,G=this._def){return KY.create(I,{...this._def,...G})}exclude(I,G=this._def){return KY.create(this.options.filter((C)=>!I.includes(C)),{...this._def,...G})}}KY.create=kd;class yW extends vI{_parse(I){let G=gI.getValidEnumValues(this._def.values),C=this._getOrReturnCtx(I);if(C.parsedType!==T.string&&C.parsedType!==T.number){let N=gI.objectValues(G);return P(C,{expected:gI.joinValues(N),received:C.parsedType,code:x.invalid_type}),bI}if(!this._cache)this._cache=new Set(gI.getValidEnumValues(this._def.values));if(!this._cache.has(I.data)){let N=gI.objectValues(G);return P(C,{received:C.data,code:x.invalid_enum_value,options:N}),bI}return EG(I.data)}get enum(){return this._def.values}}yW.create=(I,G)=>{return new yW({values:I,typeName:QI.ZodNativeEnum,...HI(G)})};class hZ extends vI{unwrap(){return this._def.type}_parse(I){let{ctx:G}=this._processInputParams(I);if(G.parsedType!==T.promise&&G.common.async===!1)return P(G,{code:x.invalid_type,expected:T.promise,received:G.parsedType}),bI;let C=G.parsedType===T.promise?G.data:Promise.resolve(G.data);return EG(C.then((N)=>{return this._def.type.parseAsync(N,{path:G.path,errorMap:G.common.contextualErrorMap})}))}}hZ.create=(I,G)=>{return new hZ({type:I,typeName:QI.ZodPromise,...HI(G)})};class IN extends vI{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===QI.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(I){let{status:G,ctx:C}=this._processInputParams(I),N=this._def.effect||null,Y={addIssue:(Z)=>{if(P(C,Z),Z.fatal)G.abort();else G.dirty()},get path(){return C.path}};if(Y.addIssue=Y.addIssue.bind(Y),N.type==="preprocess"){let Z=N.transform(C.data,Y);if(C.common.async)return Promise.resolve(Z).then(async(W)=>{if(G.value==="aborted")return bI;let b=await this._def.schema._parseAsync({data:W,path:C.path,parent:C});if(b.status==="aborted")return bI;if(b.status==="dirty")return mZ(b.value);if(G.value==="dirty")return mZ(b.value);return b});else{if(G.value==="aborted")return bI;let W=this._def.schema._parseSync({data:Z,path:C.path,parent:C});if(W.status==="aborted")return bI;if(W.status==="dirty")return mZ(W.value);if(G.value==="dirty")return mZ(W.value);return W}}if(N.type==="refinement"){let Z=(W)=>{let b=N.refinement(W,Y);if(C.common.async)return Promise.resolve(b);if(b instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if(C.common.async===!1){let W=this._def.schema._parseSync({data:C.data,path:C.path,parent:C});if(W.status==="aborted")return bI;if(W.status==="dirty")G.dirty();return Z(W.value),{status:G.value,value:W.value}}else return this._def.schema._parseAsync({data:C.data,path:C.path,parent:C}).then((W)=>{if(W.status==="aborted")return bI;if(W.status==="dirty")G.dirty();return Z(W.value).then(()=>{return{status:G.value,value:W.value}})})}if(N.type==="transform")if(C.common.async===!1){let Z=this._def.schema._parseSync({data:C.data,path:C.path,parent:C});if(!uY(Z))return bI;let W=N.transform(Z.value,Y);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:G.value,value:W}}else return this._def.schema._parseAsync({data:C.data,path:C.path,parent:C}).then((Z)=>{if(!uY(Z))return bI;return Promise.resolve(N.transform(Z.value,Y)).then((W)=>({status:G.value,value:W}))});gI.assertNever(N)}}IN.create=(I,G,C)=>{return new IN({schema:I,typeName:QI.ZodEffects,effect:G,...HI(C)})};IN.createWithPreprocess=(I,G,C)=>{return new IN({schema:G,effect:{type:"preprocess",transform:I},typeName:QI.ZodEffects,...HI(C)})};class oC extends vI{_parse(I){if(this._getType(I)===T.undefined)return EG(void 0);return this._def.innerType._parse(I)}unwrap(){return this._def.innerType}}oC.create=(I,G)=>{return new oC({innerType:I,typeName:QI.ZodOptional,...HI(G)})};class oN extends vI{_parse(I){if(this._getType(I)===T.null)return EG(null);return this._def.innerType._parse(I)}unwrap(){return this._def.innerType}}oN.create=(I,G)=>{return new oN({innerType:I,typeName:QI.ZodNullable,...HI(G)})};class pW extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C=G.data;if(G.parsedType===T.undefined)C=this._def.defaultValue();return this._def.innerType._parse({data:C,path:G.path,parent:G})}removeDefault(){return this._def.innerType}}pW.create=(I,G)=>{return new pW({innerType:I,typeName:QI.ZodDefault,defaultValue:typeof G.default==="function"?G.default:()=>G.default,...HI(G)})};class EW extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C={...G,common:{...G.common,issues:[]}},N=this._def.innerType._parse({data:C.data,path:C.path,parent:{...C}});if(cW(N))return N.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new PG(C.common.issues)},input:C.data})}});else return{status:"valid",value:N.status==="valid"?N.value:this._def.catchValue({get error(){return new PG(C.common.issues)},input:C.data})}}removeCatch(){return this._def.innerType}}EW.create=(I,G)=>{return new EW({innerType:I,typeName:QI.ZodCatch,catchValue:typeof G.catch==="function"?G.catch:()=>G.catch,...HI(G)})};class ml extends vI{_parse(I){if(this._getType(I)!==T.nan){let C=this._getOrReturnCtx(I);return P(C,{code:x.invalid_type,expected:T.nan,received:C.parsedType}),bI}return{status:"valid",value:I.data}}}ml.create=(I)=>{return new ml({typeName:QI.ZodNaN,...HI(I)})};var cq=Symbol("zod_brand");class c4 extends vI{_parse(I){let{ctx:G}=this._processInputParams(I),C=G.data;return this._def.type._parse({data:C,path:G.path,parent:G})}unwrap(){return this._def.type}}class Vl extends vI{_parse(I){let{status:G,ctx:C}=this._processInputParams(I);if(C.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:C.data,path:C.path,parent:C});if(Y.status==="aborted")return bI;if(Y.status==="dirty")return G.dirty(),mZ(Y.value);else return this._def.out._parseAsync({data:Y.value,path:C.path,parent:C})})();else{let N=this._def.in._parseSync({data:C.data,path:C.path,parent:C});if(N.status==="aborted")return bI;if(N.status==="dirty")return G.dirty(),{status:"dirty",value:N.value};else return this._def.out._parseSync({data:N.value,path:C.path,parent:C})}}static create(I,G){return new Vl({in:I,out:G,typeName:QI.ZodPipeline})}}class zW extends vI{_parse(I){let G=this._def.innerType._parse(I),C=(N)=>{if(uY(N))N.value=Object.freeze(N.value);return N};return cW(G)?G.then((N)=>C(N)):C(G)}unwrap(){return this._def.innerType}}zW.create=(I,G)=>{return new zW({innerType:I,typeName:QI.ZodReadonly,...HI(G)})};function Jd(I,G){let C=typeof I==="function"?I(G):typeof I==="string"?{message:I}:I;return typeof C==="string"?{message:C}:C}function yd(I,G={},C){if(I)return XZ.create().superRefine((N,Y)=>{let Z=I(N);if(Z instanceof Promise)return Z.then((W)=>{if(!W){let b=Jd(G,N),l=b.fatal??C??!0;Y.addIssue({code:"custom",...b,fatal:l})}});if(!Z){let W=Jd(G,N),b=W.fatal??C??!0;Y.addIssue({code:"custom",...W,fatal:b})}return});return XZ.create()}var Oq={object:GG.lazycreate},QI;(function(I){I.ZodString="ZodString",I.ZodNumber="ZodNumber",I.ZodNaN="ZodNaN",I.ZodBigInt="ZodBigInt",I.ZodBoolean="ZodBoolean",I.ZodDate="ZodDate",I.ZodSymbol="ZodSymbol",I.ZodUndefined="ZodUndefined",I.ZodNull="ZodNull",I.ZodAny="ZodAny",I.ZodUnknown="ZodUnknown",I.ZodNever="ZodNever",I.ZodVoid="ZodVoid",I.ZodArray="ZodArray",I.ZodObject="ZodObject",I.ZodUnion="ZodUnion",I.ZodDiscriminatedUnion="ZodDiscriminatedUnion",I.ZodIntersection="ZodIntersection",I.ZodTuple="ZodTuple",I.ZodRecord="ZodRecord",I.ZodMap="ZodMap",I.ZodSet="ZodSet",I.ZodFunction="ZodFunction",I.ZodLazy="ZodLazy",I.ZodLiteral="ZodLiteral",I.ZodEnum="ZodEnum",I.ZodEffects="ZodEffects",I.ZodNativeEnum="ZodNativeEnum",I.ZodOptional="ZodOptional",I.ZodNullable="ZodNullable",I.ZodDefault="ZodDefault",I.ZodCatch="ZodCatch",I.ZodPromise="ZodPromise",I.ZodBranded="ZodBranded",I.ZodPipeline="ZodPipeline",I.ZodReadonly="ZodReadonly"})(QI||(QI={}));var Fq=(I,G={message:`Input not instance of ${I.name}`})=>yd((C)=>C instanceof I,G),pd=_C.create,Ed=AY.create,vq=ml.create,uq=gY.create,zd=vW.create,Jq=VZ.create,Aq=bl.create,gq=uW.create,Kq=JW.create,kq=XZ.create,yq=JY.create,pq=vN.create,Eq=ll.create,zq=rC.create,Dq=GG.create,qq=GG.strictCreate,Uq=AW.create,jq=d4.create,Bq=gW.create,aq=uN.create,xq=Ql.create,Mq=Ll.create,Sq=RZ.create,nq=FW.create,Tq=KW.create,sq=kW.create,iq=KY.create,Pq=yW.create,fq=hZ.create,$q=IN.create,tq=oC.create,_q=oN.create,rq=IN.createWithPreprocess,oq=Vl.create,eq=()=>pd().optional(),IU=()=>Ed().optional(),GU=()=>zd().optional(),CU={string:(I)=>_C.create({...I,coerce:!0}),number:(I)=>AY.create({...I,coerce:!0}),boolean:(I)=>vW.create({...I,coerce:!0}),bigint:(I)=>gY.create({...I,coerce:!0}),date:(I)=>VZ.create({...I,coerce:!0})};var NU=bI;import{createHash as YU}from"crypto";var Dd={debug:0,info:1,warn:2,error:3},ZU="info",jm=ZU;function Xl(I){jm=I}function qd(){return jm}function a(I){return YU("sha256").update("kiro-provider-audit-v1\x00").update(I).digest("hex").slice(0,16)}function y(I,G,C={}){if(Dd[I]<Dd[jm])return;let N=Object.fromEntries(Object.entries(C).filter((Y)=>Y[1]!==void 0));console.error(JSON.stringify({timestamp:new Date().toISOString(),level:I,event:G,...N}))}import{existsSync as WU}from"fs";import{homedir as Ud}from"os";import{posix as bU,win32 as lU}from"path";function Bm(I){return I===void 0||I.trim().length===0?void 0:I}function eN(I,...G){return I==="win32"?lU.join(...G):bU.join(...G)}function IY(I={}){let G=I.env??process.env,C=I.platform??process.platform,N=I.homeDirectory??Ud();return C==="win32"?Bm(G.APPDATA)??eN(C,N,"AppData","Roaming"):Bm(G.XDG_CONFIG_HOME)??eN(C,N,".config")}function QU(I={}){let G=I.env??process.env,C=I.platform??process.platform,N=I.homeDirectory??Ud();return Bm(G.XDG_CONFIG_HOME)??eN(C,N,".config")}function jd(I={}){let G=I.exists??WU,C=I.platform??process.platform,N=eN(C,IY(I),"kiro-provider","config.json");if(C!=="win32")return N;let Y=eN(C,QU(I),"kiro-provider","config.json");if(Y!==N&&!G(N)&&G(Y))return Y;return N}var O4=w.enum(["low","medium","high","xhigh","max"]),kC=w.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var LU=w.array(w.string()).transform((I)=>I.map((G)=>G.trim()).filter((G)=>G.length>0)).refine((I)=>I.length>0,{message:"api_keys must contain at least one non-empty key"}),mU=w.preprocess((I)=>typeof I==="string"&&I.trim().length===0?null:I,w.string().trim().refine((I)=>URL.canParse(I),{message:"proxy_url must be a valid URL"}).refine((I)=>{if(!URL.canParse(I))return!1;let G=new URL(I).protocol;return G==="http:"||G==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),am=w.preprocess((I)=>typeof I==="string"&&I.trim().length===0?null:I,w.string().trim().min(1).nullable()).default(null),F4=w.object({host:w.string().trim().min(1).default("127.0.0.1"),port:w.number().int().min(0).max(65535).default(8787),api_keys:LU,enable_legacy_chat_completions:w.boolean().default(!1),protocol_projection_mode:w.enum(["v3-auto","safe","native-context-safe","legacy-user-prefix"]).default("v3-auto"),responses_fidelity_mode:w.enum(["compatible","strict"]).default("compatible"),responses_instruction_lift:w.enum(["auto","off","experimental"]).default("auto"),responses_native_tool_bridge:w.enum(["auto","off","experimental"]).default("auto"),session_affinity_mode:w.enum(["explicit-only","legacy-initial-input"]).default("explicit-only"),kiro_prompt_cache_mode:w.enum(["server-auto","explicit-checkpoints","off"]).default("server-auto"),proxy_url:mU,sdk_http_keep_alive:w.boolean().default(!1),enforce_single_instance:w.boolean().default(!0),instance_lock_path:am,runtime_endpoint_mode:w.enum(["legacy-q","kiro-runtime"]).default("kiro-runtime"),dynamic_model_catalog:w.boolean().default(!0),model_catalog_ttl_ms:w.number().int().min(1).max(2147483647).default(900000),model_catalog_stale_ttl_ms:w.number().int().min(1).max(2147483647).default(86400000),model_catalog_request_timeout_ms:w.number().int().min(1).max(2147483647).default(1e4),auth_source:w.enum(["local","opencode-shared"]).default("local"),opencode_auth_db_path:am,default_region:kC.default("us-east-1"),account_selection_strategy:w.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),account_inference_concurrency:w.number().int().min(1).max(10).default(10),rate_limit_max_retries:w.number().int().min(0).max(100).default(3),rate_limit_retry_delay_ms:w.number().int().min(1).max(2147483647).default(5000),quota_recheck_interval_ms:w.number().int().min(1).max(2147483647).default(900000),stop_on_overage:w.boolean().default(!0),overage_threshold:w.number().int().min(0).max(1e6).default(0),quota_recheck_timeout_ms:w.number().int().min(1).max(2147483647).default(1e4),quota_recheck_concurrency:w.number().int().min(1).max(32).default(4),account_maintenance_enabled:w.boolean().default(!0),account_maintenance_interval_ms:w.number().int().min(1000).max(2147483647).default(60000),account_maintenance_timeout_ms:w.number().int().min(1000).max(2147483647).default(120000),account_maintenance_concurrency:w.number().int().min(1).max(32).default(4),usage_refresh_interval_ms:w.number().int().min(1000).max(2147483647).default(900000),max_request_iterations:w.number().int().min(1).max(1000).default(20),request_timeout_ms:w.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:w.number().int().min(1).max(2147483647).default(60000),stream_max_attempts:w.number().int().min(1).max(10).default(3),retry_empty_completion:w.boolean().default(!0),max_request_body_bytes:w.number().int().min(1).max(2147483647).default(33554432),max_inflight_requests:w.number().int().min(1).max(1e4).default(16),max_inflight_request_body_bytes:w.number().int().min(1).max(2147483647).default(134217728),token_expiry_buffer_ms:w.number().int().min(1).max(2147483647).default(300000),session_affinity_ttl_ms:w.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:w.number().int().min(1).max(1e6).default(1e4),session_affinity_stall_failover_threshold:w.number().int().min(0).max(100).default(2),session_affinity_stall_window_ms:w.number().int().min(1).max(2147483647).default(600000),reasoning_replay_key_path:am,reasoning_replay_keys:w.array(w.string().trim().min(1)).default([]),reasoning_replay_token_format:w.enum(["portable-v2","database-v1"]).default("portable-v2"),reasoning_replay_account_failover:w.enum(["verified","strict"]).default("verified"),reasoning_replay_legacy_account_failover:w.enum(["strict","verified-current-cell"]).default("strict"),reasoning_replay_ttl_ms:w.number().int().min(1).max(2147483647).default(86400000),reasoning_replay_max_entries:w.number().int().min(1).max(1e6).default(1e4),effort:O4.nullable().default(null),auto_effort_mapping:w.boolean().default(!0),log_level:w.enum(["debug","info","warn","error"]).default("info"),test_upstream_endpoint:w.string().url().optional()});var xm='auth_source "opencode-shared" was removed in kiro-provider 0.7.0. Copy the OpenCode accounts once with "kiro-provider accounts import [--from <path>]", then set auth_source to "local" or delete the key; the provider-owned store (~/.config/kiro-provider/accounts.db) is the only authentication authority.';function hU(I){if(I.auth_source==="opencode-shared")throw new GY(xm);if(I.opencode_auth_db_path!==null)y("warn","config_opencode_auth_db_path_deprecated",{hint:"opencode_auth_db_path is ignored since 0.7.0 and will be removed; pass --from to kiro-provider accounts import instead"});return I}class GY extends Error{constructor(I,G){super(I,G);this.name="ConfigLoadError"}}var HU=F4.partial().strict(),wU=Object.keys(F4.shape),dU=[{env:"KIRO_PROVIDER_HOST",field:"host",kind:"string"},{env:"KIRO_PROVIDER_PORT",field:"port",kind:"integer"},{env:"KIRO_PROVIDER_API_KEYS",field:"api_keys",kind:"list"},{env:"KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS",field:"enable_legacy_chat_completions",kind:"boolean"},{env:"KIRO_PROVIDER_PROTOCOL_PROJECTION_MODE",field:"protocol_projection_mode",kind:"string"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_MODE",field:"session_affinity_mode",kind:"string"},{env:"KIRO_PROVIDER_PROMPT_CACHE_MODE",field:"kiro_prompt_cache_mode",kind:"string"},{env:"KIRO_PROVIDER_RESPONSES_FIDELITY_MODE",field:"responses_fidelity_mode",kind:"string"},{env:"KIRO_PROVIDER_RESPONSES_INSTRUCTION_LIFT",field:"responses_instruction_lift",kind:"string"},{env:"KIRO_PROVIDER_RESPONSES_NATIVE_TOOL_BRIDGE",field:"responses_native_tool_bridge",kind:"string"},{env:"KIRO_PROVIDER_PROXY_URL",field:"proxy_url",kind:"string"},{env:"KIRO_PROVIDER_SDK_HTTP_KEEP_ALIVE",field:"sdk_http_keep_alive",kind:"boolean"},{env:"KIRO_PROVIDER_ENFORCE_SINGLE_INSTANCE",field:"enforce_single_instance",kind:"boolean"},{env:"KIRO_PROVIDER_INSTANCE_LOCK_PATH",field:"instance_lock_path",kind:"string"},{env:"KIRO_PROVIDER_RUNTIME_ENDPOINT_MODE",field:"runtime_endpoint_mode",kind:"string"},{env:"KIRO_PROVIDER_DYNAMIC_MODEL_CATALOG",field:"dynamic_model_catalog",kind:"boolean"},{env:"KIRO_PROVIDER_MODEL_CATALOG_TTL_MS",field:"model_catalog_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_MODEL_CATALOG_STALE_TTL_MS",field:"model_catalog_stale_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_MODEL_CATALOG_REQUEST_TIMEOUT_MS",field:"model_catalog_request_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_AUTH_SOURCE",field:"auth_source",kind:"string"},{env:"KIRO_PROVIDER_OPENCODE_AUTH_DB_PATH",field:"opencode_auth_db_path",kind:"string"},{env:"KIRO_PROVIDER_DEFAULT_REGION",field:"default_region",kind:"string"},{env:"KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY",field:"account_selection_strategy",kind:"string"},{env:"KIRO_PROVIDER_ACCOUNT_INFERENCE_CONCURRENCY",field:"account_inference_concurrency",kind:"integer"},{env:"KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES",field:"rate_limit_max_retries",kind:"integer"},{env:"KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS",field:"rate_limit_retry_delay_ms",kind:"integer"},{env:"KIRO_PROVIDER_QUOTA_RECHECK_INTERVAL_MS",field:"quota_recheck_interval_ms",kind:"integer"},{env:"KIRO_PROVIDER_STOP_ON_OVERAGE",field:"stop_on_overage",kind:"boolean"},{env:"KIRO_PROVIDER_OVERAGE_THRESHOLD",field:"overage_threshold",kind:"integer"},{env:"KIRO_PROVIDER_QUOTA_RECHECK_TIMEOUT_MS",field:"quota_recheck_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_QUOTA_RECHECK_CONCURRENCY",field:"quota_recheck_concurrency",kind:"integer"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_ENABLED",field:"account_maintenance_enabled",kind:"boolean"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_INTERVAL_MS",field:"account_maintenance_interval_ms",kind:"integer"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_TIMEOUT_MS",field:"account_maintenance_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_ACCOUNT_MAINTENANCE_CONCURRENCY",field:"account_maintenance_concurrency",kind:"integer"},{env:"KIRO_PROVIDER_USAGE_REFRESH_INTERVAL_MS",field:"usage_refresh_interval_ms",kind:"integer"},{env:"KIRO_PROVIDER_MAX_REQUEST_ITERATIONS",field:"max_request_iterations",kind:"integer"},{env:"KIRO_PROVIDER_REQUEST_TIMEOUT_MS",field:"request_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS",field:"stream_idle_timeout_ms",kind:"integer"},{env:"KIRO_PROVIDER_STREAM_MAX_ATTEMPTS",field:"stream_max_attempts",kind:"integer"},{env:"KIRO_PROVIDER_RETRY_EMPTY_COMPLETION",field:"retry_empty_completion",kind:"boolean"},{env:"KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES",field:"max_request_body_bytes",kind:"integer"},{env:"KIRO_PROVIDER_MAX_INFLIGHT_REQUESTS",field:"max_inflight_requests",kind:"integer"},{env:"KIRO_PROVIDER_MAX_INFLIGHT_REQUEST_BODY_BYTES",field:"max_inflight_request_body_bytes",kind:"integer"},{env:"KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS",field:"token_expiry_buffer_ms",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_TTL_MS",field:"session_affinity_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_MAX_ENTRIES",field:"session_affinity_max_entries",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_STALL_FAILOVER_THRESHOLD",field:"session_affinity_stall_failover_threshold",kind:"integer"},{env:"KIRO_PROVIDER_SESSION_AFFINITY_STALL_WINDOW_MS",field:"session_affinity_stall_window_ms",kind:"integer"},{env:"KIRO_PROVIDER_REASONING_REPLAY_KEY_PATH",field:"reasoning_replay_key_path",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_KEYS",field:"reasoning_replay_keys",kind:"list"},{env:"KIRO_PROVIDER_REASONING_REPLAY_TOKEN_FORMAT",field:"reasoning_replay_token_format",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_ACCOUNT_FAILOVER",field:"reasoning_replay_account_failover",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_LEGACY_ACCOUNT_FAILOVER",field:"reasoning_replay_legacy_account_failover",kind:"string"},{env:"KIRO_PROVIDER_REASONING_REPLAY_TTL_MS",field:"reasoning_replay_ttl_ms",kind:"integer"},{env:"KIRO_PROVIDER_REASONING_REPLAY_MAX_ENTRIES",field:"reasoning_replay_max_entries",kind:"integer"},{env:"KIRO_PROVIDER_EFFORT",field:"effort",kind:"string"},{env:"KIRO_PROVIDER_AUTO_EFFORT_MAPPING",field:"auto_effort_mapping",kind:"boolean"},{env:"KIRO_PROVIDER_LOG_LEVEL",field:"log_level",kind:"string"},{env:"KIRO_PROVIDER_TEST_UPSTREAM",field:"test_upstream_endpoint",kind:"string"}];function cU(I){return I===void 0||I.trim().length===0?void 0:I}var OU=/^[+-]?\d+$/;function FU(I,G){let C=G.trim();if(!OU.test(C))throw new GY(`Invalid environment variable ${I}: expected a decimal integer, got "${G}"`);let N=Number(C);if(!Number.isSafeInteger(N))throw new GY(`Invalid environment variable ${I}: integer out of range, got "${G}"`);return N}function vU(I){let G=I.trim().toLowerCase();if(G==="true"||G==="1")return!0;if(G==="false"||G==="0")return!1;return I}function uU(I){return I.split(",").map((G)=>G.trim()).filter((G)=>G.length>0)}function JU(I){let G={},C=new Map;for(let{env:N,field:Y,kind:Z}of dU){let W=cU(I[N]);if(W===void 0)continue;switch(Z){case"integer":G[Y]=FU(N,W);break;case"boolean":G[Y]=vU(W);break;case"list":G[Y]=uU(W);break;case"string":G[Y]=W.trim();break}C.set(Y,N)}return{values:G,sources:C}}function AU(I,G){let C=Array.from({length:G.length+1},(N,Y)=>Y);for(let N=1;N<=I.length;N+=1){let Y=C[0];C[0]=N;for(let Z=1;Z<=G.length;Z+=1){let W=C[Z],b=C[Z-1],l=I[N-1]===G[Z-1]?0:1;C[Z]=Math.min(W+1,b+1,Y+l),Y=W}}return C[G.length]}function gU(I){let G=I.toLowerCase(),C;for(let Y of wU){let Z=AU(G,Y);if(C===void 0||Z<C.distance)C={field:Y,distance:Z}}if(!C)return;let N=C.field.startsWith(G)||G.startsWith(C.field);return C.distance<=3||N?C.field:void 0}function KU(I){let G=I.map((C)=>{let N=gU(C);return N?`"${C}" (did you mean "${N}"?)`:`"${C}"`});return`unknown key${I.length===1?"":"s"} ${G.join(", ")}`}function kU(I,G){if(I.code===w.ZodIssueCode.unrecognized_keys)return KU(I.keys);let C=I.path.length>0?I.path.join("."):"config",N=G?.get(String(I.path[0]));return`${C}: ${I.message}${N?` (from ${N})`:""}`}function Bd(I,G){return I.issues.map((C)=>kU(C,G)).join(", ")}function yU(I,G){if(G==="win32")return;let C;try{C=RU(I).mode&511}catch{return}if((C&63)===0)return;y("warn","config_file_permissions_loose",{path:I,mode:`0${C.toString(8)}`,recommended_mode:"0600",hint:"the file may contain api_keys; run chmod 600 on it"})}function pU(I,G){if(!VU(I))return{};yU(I,G);try{let C=JSON.parse(XU(I,"utf8"));return HU.parse(C)}catch(C){if(C instanceof w.ZodError)throw new GY(`Invalid configuration file ${I}: ${Bd(C)}`,{cause:C});if(C instanceof Error)throw new GY(`Unable to read configuration file ${I}: ${C.message}`,{cause:C});throw C}}function ad(I={}){let G=I.env??process.env,C=I.platform??process.platform,N=I.configPath??jd({env:G,platform:C}),Y;try{let Z=pU(N,C),W=JU(G);Y=new Map([...W.sources].filter(([l])=>!(l in(I.overrides??{}))));let b=F4.parse({...Z,...W.values,...I.overrides});if(b.max_inflight_request_body_bytes<b.max_request_body_bytes)throw new GY("max_inflight_request_body_bytes must be at least max_request_body_bytes");return hU(b)}catch(Z){if(Z instanceof GY)throw Z;if(Z instanceof w.ZodError)throw new GY(`Invalid configuration: ${Bd(Z,Y)}`,{cause:Z});throw Z}}var EU=["invalid_grant","invalid_client","unauthorized_client","InvalidGrantException","InvalidClientException","UnauthorizedClientException","ExpiredTokenException","InvalidTokenException","ExpiredClientException","Invalid refresh token","Invalid grant provided","Client is expired"],zU=["MISSING_CREDENTIALS","INVALID_RESPONSE"];function DU(I){return zU.some((G)=>I===G||I.startsWith(`${G}:`)||I.includes(` ${G}:`))}function GN(I){if(!I)return!1;if(DU(I))return!0;return EU.some((G)=>I.includes(G))}function JN(I){if(!I)return!1;let G=I.toLowerCase();return G.includes("bearer token included in the request is invalid")||G.includes("access token has expired")||G.includes("access_token expired")||G.includes("the access token expired")}var mG={stopOnOverage:!0,overageThreshold:0};function DW(I){return{stopOnOverage:I.stop_on_overage,overageThreshold:I.overage_threshold}}function Rl(I){let G=I.usedCount??0,C=I.limitCount??0;return Number.isFinite(G)&&Number.isFinite(C)&&C>0&&G>=C}function qU(I){return typeof I==="object"&&I!==null&&typeof I.stopOnOverage==="boolean"&&typeof I.overageThreshold==="number"?I:mG}function hl(I,G){let C=qU(G);if(!C.stopOnOverage)return!1;let N=I.overageCount??0;return Number.isFinite(N)&&N>C.overageThreshold}function nI(I,G){return hl(I,G)||Rl(I)}function xG(I){return GN(I)}function AN(I){let G=I&&I.length>0?I:"Account needs re-authentication";return GN(G)?G:`InvalidTokenException: ${G}`}class VG extends Error{code;originalError;constructor(I,G,C){super(I);this.name="KiroTokenRefreshError",this.code=G,this.originalError=C}}function v4(I){let G=I.split("|"),C=G[0]??"";if(G.length<2)return{refreshToken:C,authMethod:"desktop"};if(G.at(-1)==="idc")return{refreshToken:C,clientId:G[1],clientSecret:G[2],authMethod:"idc"};return{refreshToken:C,authMethod:"desktop"}}function Hl(I,G=120000){if(!I.access||!I.expires)return!0;return Date.now()>=I.expires-G}function qW(I){if(I.authMethod==="idc"){if(!I.clientId||!I.clientSecret)throw new VG("Missing credentials","MISSING_CREDENTIALS");return`${I.refreshToken}|${I.clientId}|${I.clientSecret}|idc`}return`${I.refreshToken}|desktop`}function xd(I){return typeof I==="object"&&I!==null&&"code"in I&&typeof I.code==="string"?I.code:void 0}function UW(I){let G=xd(I),C=I instanceof Error?I.message:String(I);return G?`${G}: ${C}`:C}function wl(I){return{error_name:I instanceof Error?I.name:"UnknownError",error_code:xd(I)}}function Md(I){if(typeof I==="object"&&I!==null&&"unref"in I&&typeof I.unref==="function")I.unref()}class Mm{options;initialTimer;intervalTimer;lifecycleController=new AbortController;inFlight;constructor(I){this.options=I}start(){if(!this.options.enabled||this.initialTimer!==void 0||this.intervalTimer!==void 0)return;this.lifecycleController=new AbortController;let I=()=>{this.runOnce(this.lifecycleController.signal).catch((G)=>{if(this.lifecycleController.signal.aborted)return;y("warn","account_maintenance_pass_failed",{...wl(G)})})};this.initialTimer=setTimeout(()=>{this.initialTimer=void 0,I()},this.options.initialDelayMs??5000),this.intervalTimer=setInterval(I,this.options.intervalMs),Md(this.initialTimer),Md(this.intervalTimer),y("info","account_maintenance_started",{interval_ms:this.options.intervalMs,timeout_ms:this.options.timeoutMs,concurrency:this.options.concurrency})}stop(){if(this.initialTimer!==void 0)clearTimeout(this.initialTimer),this.initialTimer=void 0;if(this.intervalTimer!==void 0)clearInterval(this.intervalTimer),this.intervalTimer=void 0;if(!this.lifecycleController.signal.aborted)this.lifecycleController.abort(new DOMException("Account maintenance stopped","AbortError"));y("info","account_maintenance_stopped",{})}runOnce(I){if(!this.options.enabled)return Promise.resolve();if(this.inFlight)return this.inFlight;let G=this.runPass(I).finally(()=>{if(this.inFlight===G)this.inFlight=void 0});return this.inFlight=G,G}async runPass(I){let G=Date.now(),C=AbortSignal.timeout(this.options.timeoutMs),N=I?AbortSignal.any([I,C]):C,Y=this.options.accountManager.reconcileFromDb(),Z=this.overagePolicy(),W=0,b=0,l=[];for(let X of Y){if(xG(X.unhealthyReason)||nI(X,Z))continue;let R=this.authDetails(X);if(R===void 0){b+=1;continue}if(Hl(R,this.options.tokenExpiryBufferMs))l.push({account:X,auth:R})}let Q=0,L=async()=>{for(;;){if(N.aborted)throw N.reason;let X=l[Q];if(Q+=1,!X)return;try{await this.options.tokenRefresher.refreshIfNeeded(X.account,X.auth,N),W+=1}catch(R){b+=1,this.recordTokenFailure(X.account,R)}}};await Promise.all(Array.from({length:Math.min(this.options.concurrency,l.length)},L));let m=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.recheckDueAccounts(m,N);let V=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.syncDueAccounts(V,N),y("info","account_maintenance_pass_completed",{account_count:V.length,token_due_count:l.length,token_refreshed_count:W,token_failed_count:b,duration_ms:Date.now()-G})}overagePolicy(){return this.options.overagePolicy??this.options.accountManager.getOveragePolicy?.()??mG}authDetails(I){try{return this.options.accountManager.toAuthDetails(I)}catch(G){this.recordTokenFailure(I,G);return}}recordTokenFailure(I,G){let C=UW(G);if(GN(C))try{this.options.accountManager.markUnhealthy(I,AN(C))}catch{}y("warn","account_maintenance_token_refresh_failed",{account_hash:a(I.id),...wl(G)})}}function Sd(I,G){if(!G)return I;G.start();let C=I.stop.bind(I),N=(Y)=>{try{G.stop()}finally{C(Y)}};try{Object.defineProperty(I,"stop",{configurable:!0,value:N})}catch(Y){try{G.stop()}finally{C(!0)}throw Y}return I}function UU(I){throw TypeError(`Unsupported account selection strategy: ${String(I)}`)}function HC(I,G,C=mG){if(xG(I.unhealthyReason))return!1;if(nI(I,C))return!1;if(I.rateLimitResetTime>G)return!1;return nd(I,G)}function nd(I,G){if(I.isHealthy||JN(I.unhealthyReason))return!0;return I.recoveryTime!==void 0&&I.recoveryTime<=G}function Td(I,G,C=mG){if(!hl(I,C))return!1;if(xG(I.unhealthyReason))return!1;if(Rl(I))return!1;return nd(I,G)}function sd(I,G,C,N=mG){return I.filter((Y)=>HC(Y,G,N)).filter((Y)=>C?.has(Y.id)??!0).sort((Y,Z)=>Y.id.localeCompare(Z.id))}function id(I,G,C,N=mG){return I.filter((Y)=>HC(Y,G,N)&&(C?.has(Y.id)??!0)).length}class Sm{strategy;stickyId;roundRobinCursor=0;constructor(I){this.strategy=I}pick(I,G){return I.find(({id:C})=>C===G)??this.pickByStrategy(I)}retainSticky(I){if(this.stickyId&&!I.some(({id:G})=>G===this.stickyId))this.stickyId=void 0}forget(I){if(this.stickyId===I)this.stickyId=void 0}pickByStrategy(I){switch(this.strategy){case"sticky":{let C=I.find(({id:N})=>N===this.stickyId)??I[0];if(!C)throw RangeError("Candidate list cannot be empty");return this.stickyId=C.id,C}case"round-robin":{let G=I[this.roundRobinCursor%I.length];if(!G)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,G}case"lowest-usage":{let G=[...I].sort((C,N)=>(C.usedCount??0)-(N.usedCount??0)||(C.lastUsed??0)-(N.lastUsed??0)||C.id.localeCompare(N.id))[0];if(!G)throw RangeError("Candidate list cannot be empty");return G}default:return UU(this.strategy)}}}import{createHash as JJ}from"crypto";import{Agent as eCI}from"http";import{Agent as INI}from"https";var jY=NI(NN(),1);var Tl=NI(NN(),1);var sl=NI(NN(),1);var QY=NI(NN(),1);var wC=NI(NN(),1);var xI=NI($G(),1);var bb=NI(UY(),1),WJ=NI(kY(),1);var cX=NI(e4(),1);var il=NI(_G(),1);var yC=NI(cZ(),1);var fI=NI(Sl(),1);var uI=NI(YY(),1);var _W=NI(UY(),1);var tW=NI(YY(),1);var e5=async(I,G,C)=>{return{operation:tW.getSmithyContext(G).operation}};function Hf(I){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:G,filepath:C,configFilepath:N,ignoreCache:Y},Z)=>({identityProperties:{profile:G,filepath:C,configFilepath:N,ignoreCache:Y}})}}var I1=(I)=>{let G=[];switch(I.operation){default:G.push(Hf(I))}return G},G1=(I)=>{let G=_W.memoizeIdentityProvider(I.token,_W.isIdentityExpired,_W.doesIdentityRequireRefresh);return Object.assign(I,{authSchemePreference:tW.normalizeProvider(I.authSchemePreference??[]),token:G})};var C1=(I)=>{return Object.assign(I,{useDualstackEndpoint:I.useDualstackEndpoint??!1,useFipsEndpoint:I.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},N1={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var Y1={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var eu=NI(NN(),1),IJ=NI(zX(),1);var Yb=NI($G(),1);var oG=NI($G(),1);var T1=300000,oW="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var du=async(I,G={},C)=>{let{SSOOIDCClient:N}=await Promise.resolve().then(() => NI(hR(),1)),Y=(W)=>G.clientConfig?.[W]??G.parentClientConfig?.[W]??C?.[W];return new N(Object.assign({},G.clientConfig??{},{region:I??G.clientConfig?.region,logger:Y("logger"),userAgentAppId:Y("userAgentAppId")}))};var cu=async(I,G,C={},N)=>{let{CreateTokenCommand:Y}=await Promise.resolve().then(() => NI(hR(),1));return(await du(G,C,N)).send(new Y({clientId:I.clientId,clientSecret:I.clientSecret,refreshToken:I.refreshToken,grantType:"refresh_token"}))};var Ou=NI($G(),1);var HR=(I)=>{if(I.expiration&&I.expiration.getTime()<Date.now())throw new Ou.TokenProviderError(`Token is expired. ${oW}`,!1)};var Fu=NI($G(),1);var xY=(I,G,C=!1)=>{if(typeof G>"u")throw new Fu.TokenProviderError(`Value not present for '${I}' in SSO Token${C?". Cannot refresh":""}. ${oW}`,!1)};var vu=NI($G(),1);import{promises as Te}from"fs";var{writeFile:se}=Te,uu=(I,G)=>{let C=vu.getSSOTokenFilepath(I),N=JSON.stringify(G,null,2);return se(C,N)};var Ju=new Date(0),Au=(I={})=>async({callerClientConfig:G}={})=>{I.logger?.debug("@aws-sdk/token-providers - fromSso");let C=await oG.parseKnownFiles(I),N=oG.getProfileName({profile:I.profile??G?.profile}),Y=C[N];if(!Y)throw new oG.TokenProviderError(`Profile '${N}' could not be found in shared credentials file.`,!1);else if(!Y.sso_session)throw new oG.TokenProviderError(`Profile '${N}' is missing required property 'sso_session'.`);let Z=Y.sso_session,b=(await oG.loadSsoSessionData(I))[Z];if(!b)throw new oG.TokenProviderError(`Sso session '${Z}' could not be found in shared credentials file.`,!1);for(let R of["sso_start_url","sso_region"])if(!b[R])throw new oG.TokenProviderError(`Sso session '${Z}' is missing required property '${R}'.`,!1);let{sso_start_url:l,sso_region:Q}=b,L;try{L=await oG.getSSOTokenFromFile(Z)}catch(R){throw new oG.TokenProviderError(`The SSO session token associated with profile=${N} was not found or is invalid. ${oW}`,!1)}xY("accessToken",L.accessToken),xY("expiresAt",L.expiresAt);let{accessToken:m,expiresAt:V}=L,X={token:m,expiration:new Date(V)};if(X.expiration.getTime()-Date.now()>T1)return X;if(Date.now()-Ju.getTime()<30000)return HR(X),X;xY("clientId",L.clientId,!0),xY("clientSecret",L.clientSecret,!0),xY("refreshToken",L.refreshToken,!0);try{Ju.setTime(Date.now());let R=await cu(L,Q,I,G);xY("accessToken",R.accessToken),xY("expiresIn",R.expiresIn);let h=new Date(Date.now()+R.expiresIn*1000);try{await uu(Z,{...L,accessToken:R.accessToken,expiresAt:h.toISOString(),refreshToken:R.refreshToken})}catch(H){}return{token:R.accessToken,expiration:h}}catch(R){return HR(X),X}};var wR=(I={})=>Yb.memoize(Yb.chain(Au(I),async()=>{throw new Yb.TokenProviderError("Could not load token from any providers",!1)}),(G)=>G.expiration!==void 0&&G.expiration.getTime()-Date.now()<300000,(G)=>G.expiration!==void 0);var UN=NI(NN(),1);var GJ=NI(UY(),1);var iQ=NI(e4(),1);var dR=NI(tG(),1);var LY=NI($G(),1);var YL=NI(vQ(),1);var cR=NI(tG(),1);var OR=NI($G(),1);var HG=NI(Sl(),1);var _u=NI(EQ(),1),ru=NI(UY(),1);var FR=NI(_G(),1);var Zb=NI(tG(),1);var kZ=NI(tG(),1);var DG=NI(cZ(),1);var G0="ref",yZ=-1,PQ=!0,gu="isSet",pu="PartitionResult",fQ="booleanEquals",vR="getAttr",Ku={[G0]:"Endpoint"},uR={[G0]:pu},Wb={},ku=[{[G0]:"Region"}],yu={conditions:[[gu,[Ku]],[gu,ku],["aws.partition",ku,pu],[fQ,[{[G0]:"UseFIPS"},PQ]],[fQ,[{[G0]:"UseDualStack"},PQ]],[fQ,[{fn:vR,argv:[uR,"supportsDualStack"]},PQ]],[fQ,[{fn:vR,argv:[uR,"supportsFIPS"]},PQ]],["stringEquals",[{fn:vR,argv:[uR,"name"]},"aws-us-gov"]]],results:[[yZ],[yZ,"Invalid Configuration: FIPS and custom endpoint are not supported"],[yZ,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[Ku,Wb],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Wb],[yZ,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",Wb],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",Wb],[yZ,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",Wb],[yZ,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",Wb],[yZ,"Invalid Configuration: Missing Region"]]},ie=2,eG=1e8,Pe=new Int32Array([-1,1,-1,0,13,3,1,4,eG+12,2,5,eG+12,3,8,6,4,7,eG+11,5,eG+9,eG+10,4,11,9,6,10,eG+8,7,eG+6,eG+7,5,12,eG+5,6,eG+4,eG+5,3,eG+1,14,4,eG+2,eG+3]),Eu=DG.BinaryDecisionDiagram.from(Pe,ie,yu.conditions,yu.results);var fe=new DG.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),zu=(I,G={})=>{return fe.get(I,()=>DG.decideEndpoint(Eu,{endpointParams:I,logger:G.logger}))};DG.customEndpointFunctions.aws=wC.awsEndpointFunctions;var gR=NI(kY(),1);class IC extends uI.ServiceException{constructor(I){super(I);Object.setPrototypeOf(this,IC.prototype)}}class $Q extends IC{name="AccessDeniedException";$fault="client";reason;constructor(I){super({name:"AccessDeniedException",$fault:"client",...I});Object.setPrototypeOf(this,$Q.prototype),this.reason=I.reason}}class tQ extends IC{name="ConflictException";$fault="client";reason;constructor(I){super({name:"ConflictException",$fault:"client",...I});Object.setPrototypeOf(this,tQ.prototype),this.reason=I.reason}}class _Q extends IC{name="InternalServerException";$fault="server";$retryable={};reason;constructor(I){super({name:"InternalServerException",$fault:"server",...I});Object.setPrototypeOf(this,_Q.prototype),this.reason=I.reason}}class rQ extends IC{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(I){super({name:"ThrottlingException",$fault:"client",...I});Object.setPrototypeOf(this,rQ.prototype),this.reason=I.reason}}class oQ extends IC{name="ValidationException";$fault="client";reason;constructor(I){super({name:"ValidationException",$fault:"client",...I});Object.setPrototypeOf(this,oQ.prototype),this.reason=I.reason}}class eQ extends IC{name="ResourceNotFoundException";$fault="client";constructor(I){super({name:"ResourceNotFoundException",$fault:"client",...I});Object.setPrototypeOf(this,eQ.prototype)}}class IL extends IC{name="ServiceUnavailableException";$fault="server";constructor(I){super({name:"ServiceUnavailableException",$fault:"server",...I});Object.setPrototypeOf(this,IL.prototype)}}class GL extends IC{name="ServiceQuotaExceededException";$fault="client";reason;constructor(I){super({name:"ServiceQuotaExceededException",$fault:"client",...I});Object.setPrototypeOf(this,GL.prototype),this.reason=I.reason}}class CL extends IC{name="DryRunOperationException";$fault="client";responseCode;constructor(I){super({name:"DryRunOperationException",$fault:"client",...I});Object.setPrototypeOf(this,CL.prototype),this.responseCode=I.responseCode}}var Du=gR.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),$e=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];Du.registerError($e,IC);var jN=gR.TypeRegistry.for("com.amazon.aws.codewhisperer"),te=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];jN.registerError(te,$Q);var _e=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];jN.registerError(_e,tQ);var re=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];jN.registerError(re,CL);var qu=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];jN.registerError(qu,_Q);var oe=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];jN.registerError(oe,eQ);var ee=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];jN.registerError(ee,GL);var III=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];jN.registerError(III,IL);var GII=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];jN.registerError(GII,rQ);var CII=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];jN.registerError(CII,oQ);var Uu=[Du,jN];var KR=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],CI=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],NII=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],NL=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],aI=[0,"com.amazon.aws.q","SensitiveString",8,0],YII=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>CI,0],[()=>CI,0],[()=>CI,0]],2],ZII=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>CI,0],[()=>CI,0],[()=>CI,0],[()=>CI,0]],3],WII=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>CI,0],0],1],bII=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>CI,0],0,[()=>fu,0],()=>Pu,[()=>ju,0],[()=>MGI,0],()=>kR,[()=>LCI,0]],1];var kR=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],lII=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>NCI,[()=>CI,0],[()=>CI,0]],2],QII=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],LII=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>CI,0]],1],mII=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>CI,0]],1],VII=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>Pu]],XII=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>CI,0],0,0,0,[()=>CI,0],[()=>CI,0]]],RII=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],hII=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>$u,0],0,0,0,[()=>yGI,0],0,0,0],2],HII=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>CI,0],()=>yR],2],wII=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>HII,0],[()=>CI,0]],2],dII=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>bCI,0]],3],cII=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>CI,0],[()=>CI,0],[()=>WCI,0],[()=>zGI,0]]],OII=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],FII=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>CI,0]]],JR=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],vII=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>CI,0],[()=>CI,0]]],uII=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],JII=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],AII=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>xu,0],()=>YCI,[()=>UGI,0],2,[()=>SGI,0]]],gII=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>CI,0],[()=>CI,0]]],KII=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>CI,0],[()=>DGI,0],1]],ju=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>CI,0],0],1],kII=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>ju,0]]],yII=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>CI,0]]],pII=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>lCI,0]],2],EII=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>ICI,0]]],zII=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],DII=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],qII=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>IGI]],UII=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],AR=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],Bu=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],yR=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>AR,()=>AR],2],jII=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>CI,0],21,[()=>CI,0]]],BII=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>CI,0],[()=>CI,0]],1],aII=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>au]],xII=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>CI,0],()=>Bu,[()=>CI,0],()=>iu,0],1],MII=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>CI,0],0,[()=>CI,0]],3],SII=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>CI,0],[()=>CI,0],1,[()=>CI,0],[()=>CI,0]],1],nII=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>jGI,0]],1],au=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],TII=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>CI,0],[()=>CI,0],[()=>CI,0]],2],sII=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>fu,0]]],xu=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>CI,0],()=>Bu,[()=>CI,0],()=>iu],1],iII=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>xu,0],()=>yR,[()=>CI,0],0,[()=>CI,0],[()=>CI,0],[()=>LII,0],64,[()=>pGI,0],[()=>CI,0]],5],PII=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>KR,0]]],Mu=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>BGI,0],0,[()=>NL,0]],2],fII=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>Mu,0]]],$II=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>PII,0],[()=>NL,0],[()=>NII,0]],2],tII=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>NL,0],[()=>KR,0]],3],_II=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>NL,0],[()=>CI,0],2],2];var rII=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>CI,0],[()=>oII,0],0,0,[()=>qGI,0],[()=>EGI,0],0,()=>kR,()=>QII],1],oII=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>AII,0],[()=>nII,0],[()=>yII,0],[()=>KII,0],[()=>ZII,0],[()=>ZCI,0],[()=>XII,0],()=>eII,[()=>kGI,0],[()=>aGI,0],[()=>xGI,0]]],eII=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var IGI=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var GGI=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>hII,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],CGI=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>CCI,16]],2];var NGI=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>iGI,0]],1],pR=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>KGI,0],[()=>XGI,0]]],ER=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>nGI,0]],2],YGI=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>C0,0]]],ZGI=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>sGI,0],2],1],WGI=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>aI,0],[()=>aI,0]],2],bGI=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>aI,0],[()=>TGI,0],2,2],2],lGI=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>aI,0],[()=>aI,0],[()=>aI,0]],2],Su=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>QGI,0]]],QGI=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>aI,0],[()=>aI,0]],2],LGI=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0]],4],mGI=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>C0,0],[()=>ER,0],[()=>Su,0],[()=>nu,0],[()=>su,0],[()=>JGI,0],()=>gGI,[()=>cGI,0],[()=>hGI,0],[()=>zR,0],[()=>Tu,0],[()=>pR,0],[()=>ZGI,0],[()=>LGI,0]]],VGI=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>mGI,0],0],1],XGI=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>lGI,0]]],nu=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>PGI,0]],1],RGI=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>su,0]]],zR=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0],[()=>aI,0]],6],Tu=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>fGI,0],[()=>pR,0]],1],hGI=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>aI,0],[()=>$GI,0],[()=>pR,0]],2],HGI=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>C0,0],[()=>ER,0],[()=>zR,0],[()=>Tu,0]]],su=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>aI,0],[()=>tGI,0]],3],wGI=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>C0,0]]],dGI=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>aI,0]],1],cGI=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>_GI,0]],1],OGI=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>aI,0],[()=>GCI,0],[()=>vGI,0],2,2,[()=>FGI,0]],2],FGI=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>aI,0]]],vGI=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>aI,0],0],1],uGI=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>C0,0],[()=>Su,0],[()=>ER,0],[()=>nu,0]]],JGI=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>AGI,0],[()=>oGI,0],[()=>rGI,0]],2],AGI=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>aI,0],[()=>aI,0]],2],gGI=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],C0=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>aI,0]],1],KGI=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>aI,0],[()=>aI,0]],2];var kGI=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>YII,0]],yGI=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>$u,0]],pGI=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>wII,0]];var EGI=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>dII,0]],zGI=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>FII,0]],iu=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>uII],DGI=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>gII,0]],qGI=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>pII,0]],Pu=[1,"com.amazon.aws.codewhisperer","References",0,()=>aII],UGI=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>xII,0]],jGI=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>SII,0]],fu=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>TII,0]],BGI=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>VCI,0]],aGI=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>Mu,0]],xGI=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>mCI,0]],MGI=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>tII,0]],SGI=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>CI,0]],nGI=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>YGI,0]],TGI=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>WGI,0]],sGI=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>bGI,0]],iGI=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>VGI,0]],PGI=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>RGI,0]],fGI=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>zR,0]],$GI=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>HGI,0]],tGI=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>wGI,0]],_GI=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>dGI,0]],rGI=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>OGI,0]],oGI=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>uGI,0]],eGI=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>QCI],ICI=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>eGI,0]],GCI=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>aI,0]],$u=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>rII,0],[()=>bII,0]]],CCI=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>DII,[()=>WII,0],[()=>jII,0],()=>JII,()=>VII,[()=>sII,0],[()=>kII,0],[()=>mII,0],[()=>EII,0],[()=>NGI,0],[()=>_II,0],[()=>fII,0],()=>qII,()=>UII,()=>RII,[()=>lII,0],[()=>cII,0],()=>zII,[()=>qu,0]]],NCI=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>au]],YCI=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>AR,()=>yR]],ZCI=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>iII,0],[()=>MII,0]]],WCI=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>JR,()=>JR,()=>JR,()=>OII,[()=>vII,0]]],bCI=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var lCI=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],QCI=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],LCI=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>BII,0],21]];var mCI=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>$II,0],()=>kR]],VCI=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>CI,0],[()=>KR,0]]];var tu=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>GGI,()=>CGI];var ou=(I)=>{return{apiVersion:"2023-11-27",base64Decoder:I?.base64Decoder??Zb.fromBase64,base64Encoder:I?.base64Encoder??Zb.toBase64,disableHostPrefix:I?.disableHostPrefix??!1,endpointProvider:I?.endpointProvider??zu,extensions:I?.extensions??[],httpAuthSchemeProvider:I?.httpAuthSchemeProvider??I1,httpAuthSchemes:I?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(G)=>G.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new ru.HttpBearerAuthSigner}],logger:I?.logger??new uI.NoOpLogger,protocol:I?.protocol??_u.AwsRestJsonProtocol,protocolSettings:I?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:Uu,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:I?.serviceId??"CodeWhispererStreaming",urlParser:I?.urlParser??FR.parseUrl,utf8Decoder:I?.utf8Decoder??kZ.fromUtf8,utf8Encoder:I?.utf8Encoder??kZ.toUtf8}};var CJ=(I)=>{uI.emitWarningIfUnsupportedVersion(process.version);let G=OR.resolveDefaultsModeConfig(I),C=()=>G().then(uI.loadConfigsForDefaultMode),N=ou(I);eu.emitWarningIfUnsupportedVersion(process.version);let Y={profile:I?.profile,logger:N.logger};return{...N,...I,runtime:"node",defaultsMode:G,authSchemePreference:I?.authSchemePreference??LY.loadConfig(IJ.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,Y),bodyLengthChecker:I?.bodyLengthChecker??cR.calculateBodyLength,defaultUserAgentProvider:I?.defaultUserAgentProvider??UN.createDefaultUserAgentProvider({serviceId:N.serviceId,clientVersion:Y1.version}),eventStreamSerdeProvider:I?.eventStreamSerdeProvider??iQ.eventStreamSerdeProvider,httpAuthSchemes:I?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(Z)=>Z.getIdentityProvider("smithy.api#httpBearerAuth")||(async(W)=>{return await wR(W)(W)}),signer:new GJ.HttpBearerAuthSigner}],maxAttempts:I?.maxAttempts??LY.loadConfig(fI.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,I),region:I?.region??LY.loadConfig(xI.NODE_REGION_CONFIG_OPTIONS,{...xI.NODE_REGION_CONFIG_FILE_OPTIONS,...Y}),requestHandler:YL.NodeHttpHandler.create(I?.requestHandler??C),retryMode:I?.retryMode??LY.loadConfig({...fI.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await C()).retryMode||HG.DEFAULT_RETRY_MODE},I),sha256:I?.sha256??dR.Hash.bind(null,"sha256"),streamCollector:I?.streamCollector??YL.streamCollector,useDualstackEndpoint:I?.useDualstackEndpoint??LY.loadConfig(xI.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,Y),useFipsEndpoint:I?.useFipsEndpoint??LY.loadConfig(xI.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,Y),userAgentAppId:I?.userAgentAppId??LY.loadConfig(UN.NODE_APP_ID_CONFIG_OPTIONS,Y)}};var dC=NI(NN(),1);var GC=NI(_G(),1);var NJ=(I)=>{let{httpAuthSchemes:G,httpAuthSchemeProvider:C,token:N}=I;return{setHttpAuthScheme(Y){let Z=G.findIndex((W)=>W.schemeId===Y.schemeId);if(Z===-1)G.push(Y);else G.splice(Z,1,Y)},httpAuthSchemes(){return G},setHttpAuthSchemeProvider(Y){C=Y},httpAuthSchemeProvider(){return C},setToken(Y){N=Y},token(){return N}}},YJ=(I)=>{return{httpAuthSchemes:I.httpAuthSchemes(),httpAuthSchemeProvider:I.httpAuthSchemeProvider(),token:I.token()}};var ZJ=(I,G)=>{let C=Object.assign(dC.getAwsRegionExtensionConfiguration(I),uI.getDefaultExtensionConfiguration(I),GC.getHttpHandlerExtensionConfiguration(I),NJ(I));return G.forEach((N)=>N.configure(C)),Object.assign(I,dC.resolveAwsRegionExtensionConfiguration(C),uI.resolveDefaultRuntimeConfig(C),GC.resolveHttpHandlerRuntimeConfig(C),YJ(C))};class DR extends uI.Client{config;constructor(...[I]){let G=CJ(I||{});super(G);this.initConfig=G;let C=C1(G),N=QY.resolveUserAgentConfig(C),Y=fI.resolveRetryConfig(N),Z=xI.resolveRegionConfig(Y),W=jY.resolveHostHeaderConfig(Z),b=yC.resolveEndpointConfig(W),l=wC.resolveDefaultAwsRegionalEndpointsConfig(b),Q=cX.resolveEventStreamSerdeConfig(l),L=G1(Q),m=ZJ(L,I?.extensions||[]);this.config=m,this.middlewareStack.use(WJ.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(QY.getUserAgentPlugin(this.config)),this.middlewareStack.use(fI.getRetryPlugin(this.config)),this.middlewareStack.use(il.getContentLengthPlugin(this.config)),this.middlewareStack.use(jY.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Tl.getLoggerPlugin(this.config)),this.middlewareStack.use(sl.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(bb.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:e5,identityProviderConfigProvider:async(V)=>new bb.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":V.token})})),this.middlewareStack.use(bb.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class qR extends uI.Command.classBuilder().ep(N1).m(function(I,G,C,N){return[yC.getEndpointPlugin(C,I.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(tu).build(){}var DC={CONTENT_LENGTH_EXCEEDS_THRESHOLD:"CONTENT_LENGTH_EXCEEDS_THRESHOLD",DOCUMENT_COUNT_EXCEEDED:"DOCUMENT_COUNT_EXCEEDED",DOCUMENT_DUPLICATE_NAME:"DOCUMENT_DUPLICATE_NAME",DOCUMENT_MAXIMUM_PAGES_EXCEEDED:"DOCUMENT_MAXIMUM_PAGES_EXCEEDED",DOCUMENT_MODEL_NOT_SUPPORTED:"DOCUMENT_MODEL_NOT_SUPPORTED",DOCUMENT_PASSWORD_PROTECTED:"DOCUMENT_PASSWORD_PROTECTED",DOCUMENT_SIZE_EXCEEDED:"DOCUMENT_SIZE_EXCEEDED",IMAGE_COUNT_EXCEEDED:"IMAGE_COUNT_EXCEEDED",IMAGE_DIMENSION_EXCEEDED:"IMAGE_DIMENSION_EXCEEDED",IMAGE_FORMAT_UNSUPPORTED:"IMAGE_FORMAT_UNSUPPORTED",IMAGE_MIME_MISMATCH:"IMAGE_MIME_MISMATCH",IMAGE_SIZE_EXCEEDED:"IMAGE_SIZE_EXCEEDED",INVALID_CONVERSATION_ID:"INVALID_CONVERSATION_ID",INVALID_KMS_GRANT:"INVALID_KMS_GRANT",INVALID_MODEL_ID:"INVALID_MODEL_ID",PROMPT_TOO_LONG:"PROMPT_TOO_LONG",REQUEST_BODY_INVALID:"REQUEST_BODY_INVALID",REQUEST_BODY_INVALID_JSON:"REQUEST_BODY_INVALID_JSON",THINKING_SIGNATURE_INVALID:"THINKING_SIGNATURE_INVALID",TOOL_CONFIG_MISSING:"TOOL_CONFIG_MISSING",TOOL_DUPLICATE:"TOOL_DUPLICATE",TOOL_SCHEMA_INVALID:"TOOL_SCHEMA_INVALID",TOOL_USE_RESULT_MISMATCH:"TOOL_USE_RESULT_MISMATCH"},ZL={CONVERSATION_LIMIT_EXCEEDED:"CONVERSATION_LIMIT_EXCEEDED",MONTHLY_REQUEST_COUNT:"MONTHLY_REQUEST_COUNT",OVERAGE_REQUEST_LIMIT_EXCEEDED:"OVERAGE_REQUEST_LIMIT_EXCEEDED"};var AJ=NI(EQ(),1),gJ=NI(vQ(),1);var FJ=NI(BR(),1);import*as aN from"net";import*as Y0 from"tls";import $CI from"assert";import*as HJ from"net";import*as wJ from"http";import{Agent as fCI}from"https";var BN=Symbol("AgentBaseInternalState");class aR extends wJ.Agent{constructor(I){super(I);this[BN]={}}isSecureEndpoint(I){if(I){if(typeof I.secureEndpoint==="boolean")return I.secureEndpoint;if(typeof I.protocol==="string")return I.protocol==="https:"}let{stack:G}=Error();if(typeof G!=="string")return!1;return G.split(`
|
|
58
58
|
`).some((C)=>C.indexOf("(https.js:")!==-1||C.indexOf("node:https:")!==-1)}incrementSockets(I){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[I])this.sockets[I]=[];let G=new HJ.Socket({writable:!1});return this.sockets[I].push(G),this.totalSocketCount++,G}decrementSockets(I,G){if(!this.sockets[I]||G===null)return;let C=this.sockets[I],N=C.indexOf(G);if(N!==-1){if(C.splice(N,1),this.totalSocketCount--,C.length===0)delete this.sockets[I]}}getName(I){if(this.isSecureEndpoint(I))return fCI.prototype.getName.call(this,I);return super.getName(I)}createSocket(I,G,C){let N={...G,secureEndpoint:this.isSecureEndpoint(G)},Y=this.getName(N),Z=this.incrementSockets(Y);Promise.resolve().then(()=>this.connect(I,N)).then((W)=>{if(this.decrementSockets(Y,Z),typeof W.addRequest==="function")try{return W.addRequest(I,N)}catch(b){return C(b)}this[BN].currentSocket=W,super.createSocket(I,G,C)},(W)=>{this.decrementSockets(Y,Z),C(W)})}createConnection(){let I=this[BN].currentSocket;if(this[BN].currentSocket=void 0,!I)throw Error("No socket was returned in the `connect()` function");return I}get defaultPort(){return this[BN].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(I){if(this[BN])this[BN].defaultPort=I}get protocol(){return this[BN].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(I){if(this[BN])this[BN].protocol=I}}import{URL as tCI}from"url";var dJ=NI(BR(),1),LL=dJ.default("https-proxy-agent:parse-proxy-response");function xR(I){return new Promise((G,C)=>{let N=0,Y=[];function Z(){let L=I.read();if(L)Q(L);else I.once("readable",Z)}function W(){I.removeListener("end",b),I.removeListener("error",l),I.removeListener("readable",Z)}function b(){W(),LL("onend"),C(Error("Proxy connection ended before receiving CONNECT response"))}function l(L){W(),LL("onerror %o",L),C(L)}function Q(L){Y.push(L),N+=L.length;let m=Buffer.concat(Y,N),V=m.indexOf(`\r
|
|
59
59
|
\r
|
|
60
60
|
`);if(V===-1){LL("have not received end of HTTP headers yet..."),Z();return}let X=m.slice(0,V).toString("ascii").split(`\r
|
|
@@ -372,7 +372,7 @@ ${_Y([V])}`).join(`
|
|
|
372
372
|
`:"";if(R[J]={...u,content:[...u.content,TI(`${g}${v}`,F.path)]},m.length>0&&O>=Q)X=u.role==="user"?"append_user":"append_tool"}else H.push(F);continue}let c=qh(F);if(H.length>0)if(F.role==="user"||F.role==="tool"){if(c={...c,content:[TI(`${_Y(H)}
|
|
373
373
|
|
|
374
374
|
`,H[0]?.path??"instructions"),...c.content]},H=[],l===void 0)V="prepend_first_user"}else d();h.set(O,R.length),R.push(c)}return d(m.length>0),{messages:R,projectedIndexByOriginal:h,...l===void 0?{}:{systemPrompt:l},diagnostics:{projectionMode:I.projectionMode,instructionChannel:C.length===0?"none":l===void 0?"legacy-user-prefix":"kiro-runtime-system-prompt+inline-user",inputMessageCount:I.messages.length,outputMessageCount:R.length,prefixInstructionCount:b.length,intermediateInstructionCount:C.length-b.length-m.length,trailingInstructionCount:m.length,prefixAction:V,suffixAction:X}}}function abI(I,G,C){let N=Kb(I,G,{includeToolUseParts:!0,allowHistoricalWithoutDeclarations:C});if(!N)return;switch(N.kind){case"missing_tool_declaration":throw new ZI(`Tool call ${N.callId} references ${N.toolName} without an exact declaration`,N.code,N.path);case"duplicate_tool_call":throw new ZI(`Duplicate tool call id ${N.callId}`,N.code,N.path);case"orphan_tool_result":throw new ZI(`Tool result ${N.toolCallId} has no earlier unique matching call`,N.code,N.path)}}function xbI(I){for(let G of I)if(G.description===void 0||G.description.trim().length===0)throw new ZI(`Tool ${G.path} requires a non-empty description for Kiro`,"missing_tool_description",G.descriptionPath??G.path);return I.flatMap((G)=>[{toolSpecification:{name:G.wireName,description:G.description,inputSchema:{json:{...G.inputSchema}}}},...G.cachePoint?[{cachePoint:{type:"default"}}]:[]])}function pg(I,G){for(let C of I){if(C.userInputMessage)delete C.userInputMessage.cachePoint;if(C.assistantResponseMessage)delete C.assistantResponseMessage.cachePoint}for(let C=G.length-1;C>=0;C-=1)if("cachePoint"in(G[C]??{}))G.splice(C,1)}function MbI(I,G){return I.filter((C)=>C.userInputMessage?.cachePoint!==void 0||C.assistantResponseMessage?.cachePoint!==void 0).length+G.filter((C)=>("cachePoint"in C)).length}function SbI(I,G,C,N,Y){let Z=I.promptCaching;if(Z?.mode!=="explicit-checkpoints"||Z.supported!==!0){pg(G,N);return}let W=Z.maximumCheckpoints??4,b=MbI(G,N);if(b>W)throw new ZI(`Request has ${b} cache checkpoints but Kiro allows at most ${W}`,"too_many_cache_checkpoints");if(aL({conversationState:{chatTriggerType:DI.CHAT_TRIGGER_TYPE_MANUAL,conversationId:"cache-estimate",currentMessage:C,...G.length>0?{history:G}:{}},...Y!==void 0?{systemPrompt:Y}:{}})<(Z.minimumTokens??1)){pg(G,N);return}if(b<W&&N.some((Q)=>("toolSpecification"in Q))&&!N.some((Q)=>("cachePoint"in Q)))N.push({cachePoint:{type:"default"}}),b+=1;if(b<W){let Q=G.at(-1);if(Q?.userInputMessage)Q.userInputMessage.cachePoint={type:"default"};else if(Q?.assistantResponseMessage)Q.assistantResponseMessage.cachePoint={type:"default"}}}function nbI(I){return I.content.length>0||(I.images?.length??0)>0||(I.documents?.length??0)>0||(I.userInputMessageContext?.toolResults?.length??0)>0}function Dg(I,G,C,N={}){if(!Ob(I))throw new ZI("CanonicalRequest is required before Kiro projection","canonical_request_required");let Y=I;if(Y.model!==G)throw new ZI(`CanonicalRequest model ${Y.model} does not match pipeline model ${G}`,"canonical_model_mismatch");if(Y.messages.length===0)throw new ZI("No messages","empty_input");jbI(Y.messages);let Z,W;try{let J=lG(G);Z=J.wireId,W=J.effort}catch(J){if(J instanceof Error&&J.message.startsWith("Unsupported model:"))throw new ZI(J.message,"unsupported_model","model");throw J}let b=Y.protocol==="anthropic-messages"&&Y.model==="claude-fable-5-1"&&Y.projectionMode==="v3-auto"?(N.resolvedReasoningReplays??[]).flatMap((J)=>J.instructionProjection?.legacyPrefixMessages===void 0?[]:[J.instructionProjection.legacyPrefixMessages]):[],l=b.reduce((J,u)=>Math.min(J,u),1/0),Q=(b.length>0?BbI(Y,N.nativeSystemPromptEnabled===!0,l,(N.resolvedReasoningReplays??[]).filter((J)=>J.instructionProjection?.legacyPrefixMessages===l).every((J)=>J.legacyProjectionUnversioned===!0)):void 0)??zg(Y,N.nativeSystemPromptEnabled===!0);if(Q.messages.length===0)throw new ZI("No executable messages","empty_input");abI(Q.messages,Y.tools,Y.protocol==="responses"||Y.protocol==="anthropic-messages");let L=(N.resolvedReasoningReplays??[]).map((J)=>{let u=Q.projectedIndexByOriginal.get(J.insertBeforeMessage);if(u===void 0)throw new ZI("Reasoning replay does not reference an assistant output message","invalid_reasoning_replay");return{...J,insertBeforeMessage:u}}),m=Q.messages.at(-1);if(!m)throw new ZI("No executable messages","empty_input");if(m.role==="assistant")throw new ZI("Request ends with an assistant message and has no current user input","missing_current_input",m.path);if(m.role!=="user"&&m.role!=="tool")throw new ZI(`Request ends with ${m.role} and has no current user input`,"missing_current_input",m.path);let V=Q.messages.slice(0,-1),X=L.filter((J)=>J.insertBeforeMessage<V.length),R=Hg(V,Z,X),h=wg(m,Z);if(!nbI(h))throw new ZI("Current input contains no text bytes, image, document, or tool result","missing_current_input",m.path);let H=Y.toolChoice==="auto"?xbI(Y.tools):[];if(H.length>0)h.userInputMessageContext??={},h.userInputMessageContext.tools=H;let d={userInputMessage:h};SbI(N,R,d,H,Q.systemPrompt);let O=N.conversationId??yg(),F={conversationState:{chatTriggerType:DI.CHAT_TRIGGER_TYPE_MANUAL,conversationId:O,agentContinuationId:yg(),agentTaskType:"vibe",currentMessage:d,...R.length>0?{history:R}:{}},...C.profileArn?{profileArn:C.profileArn}:{}},c={projection:Q.diagnostics,history:{historyMessageCount:R.length,currentRole:m.role,currentTextChars:h.content.length,currentImageCount:h.images?.length??0,currentDocumentCount:h.documents?.length??0,currentToolResultCount:h.userInputMessageContext?.toolResults?.length??0,reasoningReplayCount:X.length}},v={request:F,resolved:Z,convId:O,...Q.systemPrompt!==void 0?{systemPrompt:Q.systemPrompt}:{},diagnostics:c};return W===void 0?v:{...v,variantEffort:W}}function qg(I,G,C,N=!1,Y=20000,Z){let{request:W,resolved:b,convId:l,systemPrompt:Q,diagnostics:L}=Dg(I,G,C,{conversationId:Z?.conversationId,nativeSystemPromptEnabled:Z?.nativeSystemPromptEnabled,resolvedReasoningReplays:Z?.resolvedReasoningReplays,promptCaching:Z?.promptCaching}),m=Wg({model:G,think:N,budget:Y,reasoningEffort:I.protocol==="responses"&&I.requestedReasoningEffort==="none"?"none":I.reasoningEffort,requestFirst:I.protocol==="responses",configEffort:Z?.effort,autoEffortMapping:Z?.autoEffortMapping}),V=I.outputTokenLimit,X=V===void 0?void 0:fY(G,V);if(X?.ok===!1)throw new ZI(X.message,X.code);let R={...X?.ok===!0?X.additionalModelRequestFields:{},...I.temperature!==void 0?{temperature:I.temperature}:{}};return{conversationState:W.conversationState,...W.profileArn?{profileArn:W.profileArn}:{},...Q!==void 0?{systemPrompt:Q}:{},runtimeProtocol:Q!==void 0||I.projectionMode==="v3-auto"||I.projectionMode==="native-context-safe"?"kiro-runtime":"codewhisperer",...Object.keys(R).length>0?{additionalModelRequestFields:R}:{},streaming:!0,effectiveModel:b,conversationId:l,region:W0(C.profileArn)??C.region,...m?{effort:m}:{},diagnostics:L}}function xL(I){let G=0;for(let C=0;C<I.length;C++){let N=I.charCodeAt(C);if(N<128)G++;else if(N<2048)G+=2;else if(Ug(N)&&jg(I.charCodeAt(C+1)))G+=4,C++;else G+=3}return G}function ML(I,G){let C=xL(G);if(Ug(I.charCodeAt(I.length-1))&&jg(G.charCodeAt(0)))return C-2;return C}function Ug(I){return I>=55296&&I<=56319}function jg(I){return I>=56320&&I<=57343}var TbI=new Set(["assistantResponseEvent","codeReferenceEvent","contextUsageEvent","messageMetadataEvent","metadataEvent","meteringEvent","reasoningContentEvent","toolUseEvent"]);class LN extends Error{name="SemanticStreamTruncationError";code="upstream_stream_incomplete";constructor(){super("Kiro event stream ended before an authoritative completion witness")}}class J0 extends Error{name="OutputPersistenceError";code="local_output_persistence_failed";constructor(I){super("Recording provider-local stream output failed",I)}}class kI extends Error{code;name="SdkStreamProtocolError";constructor(I,G,C){super(I,C);this.code=G}}class OC extends Error{code;violationKind;name="ToolCallViolation";toolIdHash;toolNameHash;argumentLength;argumentHash;fragmentCount;constructor(I,G,C,N){super(I);this.code=G;this.violationKind=C;if(N.toolUseId!==void 0)this.toolIdHash=a(N.toolUseId);if(N.toolName!==void 0)this.toolNameHash=a(N.toolName);this.argumentLength=Buffer.byteLength(N.argumentsText,"utf8"),this.argumentHash=a(N.argumentsText),this.fragmentCount=N.fragmentCount}}function jh(I){let G=I,C=Object.keys(G).filter((N)=>(N.endsWith("Event")||N==="error"||N==="$unknown")&&G[N]!==void 0).sort();return C.length>0?C:["unknown"]}function SL(I){let G=I.metadataEvent?.tokenUsage;return typeof G==="object"&&G!==null}function Bh(I){let G=I.meteringEvent;return typeof G?.usage==="number"&&Number.isFinite(G.usage)&&G.usage>=0&&typeof G.unit==="string"&&G.unit.length>0}function Bg(I){let G=jh(I);if(I.error!==void 0)throw new kI("Kiro returned an embedded stream error","upstream_stream_error",{cause:I.error});if(I.invalidStateEvent!==void 0)throw new kI("Kiro returned an invalid stream state","upstream_invalid_state",{cause:I.invalidStateEvent});if(I.$unknown!==void 0||G.includes("unknown"))throw new kI("Kiro returned an unknown stream event","unsupported_upstream_event");let C=G.find((N)=>!TbI.has(N));if(C!==void 0)throw new kI(`Kiro returned unsupported stream event type ${C}`,"unsupported_upstream_event")}function ag(){return{text:"",signature:"",signatureConflict:!1,redactedChunks:[]}}function xg(I,G){if(!G)return;if(I.text+=G.text??"",G.signature!==void 0&&G.signature.length>0){if(I.signature.length>0&&I.signature!==G.signature)I.signatureConflict=!0;I.signature=G.signature}if(G.redactedContent&&G.redactedContent.byteLength>0)I.redactedChunks.push(G.redactedContent)}function nL(I){let G=I.redactedChunks.reduce((W,b)=>W+b.byteLength,0),C;if(G>0){C=new Uint8Array(G);let W=0;for(let b of I.redactedChunks)C.set(b,W),W+=b.byteLength}let N=I.text.length>0&&C!==void 0,Y=I.signature.length>0&&!I.signatureConflict&&C===void 0,Z=I.text.length===0&&C!==void 0;return{text:I.text,...Y?{signature:I.signature}:{},...!N&&Z?{redactedContent:C}:{}}}async function ah(I,G){if(G?.aborted)return{kind:"aborted"};let C=I.next();if(!G)return{kind:"event",result:await C};return new Promise((N,Y)=>{let Z=()=>N({kind:"aborted"});G.addEventListener("abort",Z,{once:!0}),C.then((W)=>{G.removeEventListener("abort",Z),N({kind:"event",result:W})},(W)=>{G.removeEventListener("abort",Z),Y(W)})})}function Mg(I,G){if(!G)return;if(!G.name||!G.toolUseId)throw new OC("Kiro emitted a tool call without both name and toolUseId","invalid_upstream_tool_call","missing_identity",{...G.toolUseId!==void 0?{toolUseId:G.toolUseId}:{},...G.name!==void 0?{toolName:G.name}:{},argumentsText:G.input??"",fragmentCount:1});let C=I.get(G.toolUseId);if(C){if(C.name!==G.name)throw new OC("Kiro changed a tool name while streaming one tool call","invalid_upstream_tool_call","name_changed",{toolUseId:C.toolUseId,toolName:C.name,argumentsText:C.input+(G.input??""),fragmentCount:C.fragmentCount+1});if(C.stopped&&(G.input??"").length>0)throw new OC("Kiro emitted tool arguments after the tool call stopped","invalid_upstream_tool_call","arguments_after_stop",{toolUseId:C.toolUseId,toolName:C.name,argumentsText:C.input+(G.input??""),fragmentCount:C.fragmentCount+1});C.input+=G.input??"",C.inputReceived||=G.input!==void 0,C.stopped||=G.stop===!0,C.fragmentCount+=1;return}I.set(G.toolUseId,{toolUseId:G.toolUseId,name:G.name,input:G.input??"",inputReceived:G.input!==void 0,stopped:G.stop===!0,fragmentCount:1})}function Sg(I,G){for(let C of I.values()){if(!C.stopped)throw new OC("Kiro ended before a streamed tool call emitted its stop marker","incomplete_upstream_tool_call","missing_stop",{toolUseId:C.toolUseId,toolName:C.name,argumentsText:C.input,fragmentCount:C.fragmentCount});if(!C.inputReceived)C.input="{}";let N;try{N=JSON.parse(C.input)}catch{throw new OC("Kiro returned malformed JSON arguments for a completed tool call","malformed_upstream_tool_arguments","malformed_arguments",{toolUseId:C.toolUseId,toolName:C.name,argumentsText:C.input,fragmentCount:C.fragmentCount})}G?.(C.name,N)}}function ng(I,G){let C=G.metadataEvent?.tokenUsage;if(C)for(let N of pL)if(C[N]===void 0)delete I[N];else I[N]=C[N];if(I.contextUsagePercentage=G.contextUsageEvent?.contextUsagePercentage??G.metadataEvent?.contextUsagePercentage??C?.contextUsagePercentage??I.contextUsagePercentage,Bh(G))I.metering={value:G.meteringEvent?.usage,unit:G.meteringEvent?.unit}}function Tg(I,G,C,N={}){let Y;try{Y=Ab(I)}catch(h){if(h instanceof NC)throw new kI(h.message,h.code,{cause:h});throw h}let Z=Y.outputTokens===void 0?kg(G,N.toolCalls,Y.reasoningTokens===void 0?N.reasoning:void 0):{outputTokens:Y.outputTokens},W=Y.outputTokens??Z.outputTokens+(Y.reasoningTokens??0),b=(Y.uncachedInputTokens??0)+(Y.cacheReadInputTokens??0)+(Y.cacheWriteInputTokens??0),l=Y.inputTokens??(typeof N.inputTokenEstimate==="function"?N.inputTokenEstimate():N.inputTokenEstimate)??0;l=Math.max(l,b);let Q=I.contextUsagePercentage,L=N.contextUsageWindow,m=Q!==void 0&&Number.isFinite(Q)&&Q>=0&&Q<=100&&L!==void 0&&Number.isSafeInteger(L)&&L>0,V=m?Math.round(L*Q/100):void 0,X=m&&Q===100,R=Y.totalTokens!==void 0?"upstream":N.inputTokenEstimate!==void 0?"tokenizer":"unavailable";if(Y.totalTokens===void 0&&V!==void 0){let h=Y.outputTokens??Y.reasoningTokens??0,H=(Y.inputTokens??b)+h;if(!X&&V>0&&V>=H)if(R="percentage",Y.inputTokens!==void 0)W=V-l;else W=Math.min(W,V-b),l=V-W;else{let d=Math.max(l+W,V);if(d===V&&X)R="percentage_lower_bound";if(Y.inputTokens!==void 0)W=d-l;else l=d-W}}if(Y.totalTokens!==void 0)if(Y.inputTokens===void 0)W=Math.min(W,Y.totalTokens-b),l=Y.totalTokens-W;else W=Y.totalTokens-Y.inputTokens;return{inputTokens:l,outputTokens:W,totalTokens:l+W,reported:Y,accounting:{input:Y.inputTokens!==void 0?"upstream":"estimated",output:Y.outputTokens!==void 0?"upstream":"estimated",context:R,...Q!==void 0&&Number.isFinite(Q)&&Q>=0?{contextUsagePercentage:Q}:{},...m?{contextUsageWindow:L,percentageSaturated:X}:{},...I.metering?{metering:I.metering}:{}}}}var fg={upstream_tool_choice_violation:{disposition:"fatal",message:"Upstream called a tool despite tool_choice=none"},upstream_tool_schema_violation:{disposition:"fatal",message:"Upstream tool arguments do not match the declared schema"},upstream_tool_arguments_too_large:{disposition:"fatal",message:"Upstream tool arguments exceeded the configured request-body budget"},structured_output_unexpected_tool_call:{disposition:"fatal",message:"Upstream returned a tool call for a local structured output request"},structured_output_validation_failed:{disposition:"fatal",message:"Upstream output could not satisfy the local structured output profile"},structured_output_buffer_exceeded:{disposition:"fatal",message:"Upstream output exceeded the local structured output buffer limit"},invalid_upstream_response:{disposition:"fatal",message:"Upstream returned an invalid response"},request_deadline_exceeded:{disposition:"retryable",message:"Request deadline exceeded"},upstream_stream_error:{disposition:"retryable",message:"Upstream stream error"},upstream_stream_incomplete:{disposition:"retryable",message:"Upstream stream ended before completion"},upstream_stream_idle_timeout:{disposition:"retryable",message:"Upstream stream idle timeout"},malformed_upstream_tool_arguments:{disposition:"retryable",message:"Upstream returned malformed tool arguments"},incomplete_upstream_tool_call:{disposition:"fatal",message:"Upstream returned an incomplete tool call"},invalid_custom_tool_input:{disposition:"fatal",message:"Upstream returned invalid custom tool input"},invalid_upstream_reasoning:{disposition:"fatal",message:"Upstream returned invalid reasoning metadata"},invalid_upstream_usage:{disposition:"fatal",message:"Upstream returned invalid token usage"},invalid_upstream_tool_call:{disposition:"fatal",message:"Upstream returned an invalid tool call"},missing_upstream_stream:{disposition:"fatal",message:"Upstream response did not include a stream"},unknown_upstream_tool:{disposition:"fatal",message:"Upstream returned an undeclared tool call"},unsupported_upstream_event:{disposition:"fatal",message:"Upstream returned an unsupported stream event"},upstream_invalid_state:{disposition:"fatal",message:"Upstream returned an invalid stream state"},upstream_protocol_error:{disposition:"fatal",message:"Upstream stream protocol error"}};function TL(I,G){if(typeof I!=="object"||I===null)return;try{return Reflect.get(I,G)}catch{return}}function iN(I,G){let C=TL(I,G);return typeof C==="string"&&C.length>0?C:void 0}function sg(I){let G=iN(I,"code");return G!==void 0&&Object.hasOwn(fg,G)?G:void 0}function ig(I){let G=iN(I,"code");return G!==void 0&&/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(G)?G:void 0}function Pg(I,G){let C=TL(I,G);return typeof C==="number"&&Number.isFinite(C)?C:void 0}function FC(I,G){let C=fg[I];return{code:I,disposition:C.disposition,message:G??C.message}}function PN(I,G="upstream_stream_error"){let C=sg(I)??sg(TL(I,"cause"));return FC(C??G)}function rY(I,G){let C=(d)=>d!==void 0&&/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(d)?G?G.identifier(d):d:void 0,N=PN(I),Y=iN(I,"message"),Z=C(ig(I)),W=TL(I,"cause"),b=C(iN(W,"name")),l=C(ig(W)),Q=iN(W,"message"),L=I instanceof OC?I:W instanceof OC?W:void 0,m=iN(L,"violationKind"),V=iN(L,"toolIdHash"),X=iN(L,"toolNameHash"),R=Pg(L,"argumentLength"),h=iN(L,"argumentHash"),H=Pg(L,"fragmentCount");return{error_type:C(iN(I,"name"))??(I instanceof Error?"Error":typeof I),error_code:N.code,error_disposition:N.disposition,...Y!==void 0?{error_message_hash:a(Y)}:{},...Z!==void 0?{source_error_code:Z}:{},...b!==void 0?{error_cause_type:b}:{},...l!==void 0?{error_cause_code:l}:{},...Q!==void 0?{error_cause_message_hash:a(Q)}:{},...m!==void 0?{violation_kind:m}:{},...V!==void 0?{tool_id_hash:V}:{},...X!==void 0?{tool_name_hash:X}:{},...R!==void 0?{tool_arguments_length:R}:{},...h!==void 0?{tool_arguments_hash:h}:{},...H!==void 0?{tool_fragment_count:H}:{}}}var sbI=128,$g=1048576;function kb(I){throw new kI(I,"invalid_upstream_reasoning")}async function tg(I){let G=[],C,N=!1,Y=!0,Z=0,W=0,b=0,l=(Q=!1,L=!1)=>({events:G,done:Q,aborted:L,omitted:N,reasoningEvents:Z,prefixEvents:W,prefixBytes:b});while(!0){let Q=await I();if(Q.kind==="aborted")return l(!1,!0);if(Q.result.done){if(N)throw new LN;return l(!0)}let L=Q.result.value,m=Boolean(L.assistantResponseEvent?.content)||L.toolUseEvent!==void 0,V=SL(L);if(m||V){if(L.reasoningContentEvent!==void 0)kb("Kiro mixed reasoning and assistant/completion event payloads");if(N&&!m)kb("Kiro completed a conflicting reasoning prefix without assistant output");return G.push(L),l()}if(++W>sbI)kb("Kiro reasoning prefix exceeded its event budget");let X=L.reasoningContentEvent;if((typeof X?.signature==="string"?Buffer.byteLength(X.signature,"utf8"):0)+(typeof X?.text==="string"?Buffer.byteLength(X.text,"utf8"):0)+(X?.redactedContent?.byteLength??0)>$g-b)kb("Kiro reasoning prefix exceeded its byte budget");if(b+=Buffer.byteLength(JSON.stringify(L),"utf8"),b>$g)kb("Kiro reasoning prefix exceeded its byte budget");let h=L.reasoningContentEvent;if(h!==void 0){Z++;let H=h.signature,d=typeof H==="string"&&H.length>0;if(Y&&=d&&(h.text===void 0||h.text==="")&&h.redactedContent===void 0,d&&C!==void 0&&C!==H)N=!0,C=void 0,G=G.filter((O)=>O.reasoningContentEvent===void 0);if(N&&!Y)kb("Kiro emitted conflicting reasoning outside the empty-signature prefix");if(N)continue;if(d)C=H}G.push(L)}}var ibI=128,PbI=1048576;class sL extends Error{name="MissingSdkOutputStreamError";code="missing_upstream_stream";constructor(){super("SDK response has no event stream")}}function fbI(I){let G=0;for(let C of I.values())if(C.stopped)G+=1;return{open:I.size-G,stopped:G}}function $bI(I){try{let G=I.return?.();return Promise.resolve(G).then(()=>{return},()=>{return})}catch{return Promise.resolve()}}async function*iL(I,G,C,N,Y={}){let Z=I.generateAssistantResponseResponse;if(!Z)throw new sL;let W=new Map,b=new Map,l=new Map,Q={},L=[],m=ag(),V=Z[Symbol.asyncIterator](),X="",R=!1,h=!1,H=!1,d=!1,O=!1,F=!1,c=()=>{let LI=$bI(V);Y.onIteratorCleanup?.(LI)},v,J=0,u=Y.bufferLateGptReasoning===!0&&Y.emitAnthropicReasoningMetadata===!0&&cC(G),g=[],A=0,p=!u,D=!1,q=[],k=0,K=(LI)=>{Y.onRawEvent?.(jh(LI)),Bg(LI)},B=(LI)=>{let LG=Buffer.byteLength(JSON.stringify(LI),"utf8");if(g.length>=ibI||A+LG>PbI)throw new kI("Kiro delayed GPT reasoning metadata beyond the bounded assistant preface","invalid_upstream_reasoning");g.push(LI),A+=LG},M=()=>{let LI=g.splice(0);return A=0,LI};try{if(Y.prefetchFableReasoning===!0&&Y.emitAnthropicReasoningMetadata===!0&&nY(G)){let LI=await tg(async()=>{let LG=await ah(V,N);if(LG.kind==="event"&&!LG.result.done)K(LG.result.value);return LG});if(LI.aborted)return;if(q=LI.events,O=LI.done,D=LI.omitted,D){if(Y.reasoningReplayDecision)Y.reasoningReplayDecision.mode="conflict-omitted";y("warn","anthropic_output_reasoning_conflict_omitted",{model:"claude-fable-5-1",direction:"output",reasoning_event_count:LI.reasoningEvents,prefix_event_count:LI.prefixEvents,prefix_bytes:LI.prefixBytes})}}yield{canonicalOutputVersion:$I,type:"started",conversationId:C,model:G,createdAt:Math.floor(Date.now()/1000)};while(!0){let LI,LG=!1;try{if(k<q.length){let n=q[k];delete q[k++],LG=!0,LI={kind:"event",result:{done:!1,value:n}}}else if(O)break;else LI=await ah(V,N)}catch(n){if(v===void 0)throw n;y("warn","sdk_stream_transport_error_after_completion",{model:G,conversation_hash:a(C),witness_kind:v,...rY(n,Y.diagnostics)}),F=!0,c();break}if(LI.kind==="aborted"){c(),F=!0;return}if(LI.result.done){O=!0;break}let BI=LI.result.value;if(!LG)K(BI);if(D&&BI.reasoningContentEvent!==void 0&&((BI.reasoningContentEvent.text?.length??0)>0||(BI.reasoningContentEvent.signature?.length??0)>0||BI.reasoningContentEvent.redactedContent!==void 0))throw new kI("Kiro emitted reasoning after the omitted prefix ended","invalid_upstream_reasoning");if(BI.codeReferenceEvent!==void 0){let n=BI.codeReferenceEvent,E=_(n)&&Object.keys(n).every((o)=>o==="references")?Jb(n.references===void 0?[]:n.references):void 0,U=E===void 0?void 0:Jb([...L,...E]);if(U===void 0)throw new kI("Kiro returned invalid code reference metadata","invalid_upstream_response");L=U}ng(Q,BI),xg(m,BI.reasoningContentEvent);let KG=BI.reasoningContentEvent?.text??"",kG=u&&h&&!p&&KG.length>0&&SY(G,m.text);if(SL(BI)){v="token-usage-metadata",Y.onCompletionWitness?.(v),F=!0,c();break}if(Bh(BI))v="metering-clean-eof";if(Y.emitAnthropicReasoningMetadata){if(m.signatureConflict)throw new kI("Kiro emitted conflicting reasoning signatures","invalid_upstream_reasoning");if(m.text.length>0&&m.redactedChunks.length>0)throw new kI("Kiro mixed visible and redacted reasoning payloads","invalid_upstream_reasoning");let n=h&&BI.reasoningContentEvent?.signature!==void 0&&BI.reasoningContentEvent.signature.length>0,E=n&&u&&!p&&g.length>0&&(R||m.text.length===0||QN(G,m.text))&&m.redactedChunks.length===0;if(n&&!E)throw new kI("Kiro emitted a reasoning signature after assistant output began","invalid_upstream_reasoning");if(u&&h&&!p&&(!kG&&KG.length>0||(BI.reasoningContentEvent?.redactedContent?.byteLength??0)>0))throw new kI("Kiro emitted visible GPT reasoning after assistant output began","invalid_upstream_reasoning");if(E){if(p=!0,!R)R=!0,yield{canonicalOutputVersion:$I,type:"reasoning_delta",text:""};H=!0,yield{canonicalOutputVersion:$I,type:"reasoning_signature",signature:BI.reasoningContentEvent?.signature};for(let U of M())yield U}}let ON=BI.reasoningContentEvent?.text;if(ON&&!kG)R=!0,yield{canonicalOutputVersion:$I,type:"reasoning_delta",text:ON};let f=BI.assistantResponseEvent?.content;if(f){if(Y.emitAnthropicReasoningMetadata){let E=nL(m);if(!R&&E.signature!==void 0)R=!0,yield{canonicalOutputVersion:$I,type:"reasoning_delta",text:""};if(R&&!H&&E.signature!==void 0)H=!0,yield{canonicalOutputVersion:$I,type:"reasoning_signature",signature:E.signature};if(!R&&!d&&E.redactedContent!==void 0)d=!0,yield{canonicalOutputVersion:$I,type:"reasoning_redacted",data:Buffer.from(E.redactedContent).toString("base64")};if(E.signature!==void 0||E.redactedContent!==void 0)p=!0}h=!0,X+=f;let n={canonicalOutputVersion:$I,type:"text_delta",text:f};if(u&&!p)B(n);else yield n}if(BI.toolUseEvent){if(Y.emitAnthropicReasoningMetadata){let pG=nL(m);if(!R&&pG.signature!==void 0)R=!0,yield{canonicalOutputVersion:$I,type:"reasoning_delta",text:""};if(R&&!H&&pG.signature!==void 0)H=!0,yield{canonicalOutputVersion:$I,type:"reasoning_signature",signature:pG.signature};if(pG.signature!==void 0)p=!0}h=!0;let n=BI.toolUseEvent,E=n.toolUseId?W.get(n.toolUseId):void 0;J+=Buffer.byteLength(n.input??"","utf8");let U=l.get(n.toolUseId??"")??"",o=n.input?.charCodeAt(0);if(U&&o!==void 0&&o>=56320&&o<=57343)J-=2;if(!E)J+=Buffer.byteLength(n.name??"","utf8")+Buffer.byteLength(n.toolUseId??"","utf8");if(Y.maxToolArgumentsBytes!==void 0&&J>Y.maxToolArgumentsBytes)throw new OC("Upstream tool arguments exceeded the configured request-body budget","upstream_tool_arguments_too_large","arguments_too_large",{toolUseId:n.toolUseId,toolName:n.name,argumentsText:(E?.input??"")+(n.input??""),fragmentCount:(E?.fragmentCount??0)+1});Mg(W,BI.toolUseEvent),Y.onToolCallProgress?.(fbI(W)),Y.validateToolArguments?.assertName(BI.toolUseEvent.name);let yI=BI.toolUseEvent.toolUseId,wI=!b.has(yI);if(wI)b.set(yI,b.size);let zI=U+(n.input??""),yG=zI.charCodeAt(zI.length-1),hC=yG>=55296&&yG<=56319,iG=hC?zI.slice(0,-1):zI;l.set(yI,hC?zI.slice(-1):"");for(let pG of iG){let wW=pG.codePointAt(0);if(wW>=55296&&wW<=57343)throw new kI("Upstream tool arguments contain an invalid Unicode scalar","malformed_upstream_tool_arguments")}if(wI||iG.length>0){let pG={canonicalOutputVersion:$I,type:"tool_call_delta",index:b.get(yI),...wI?{id:yI,name:BI.toolUseEvent.name}:{},arguments:iG};if(u&&!p)B(pG);else yield pG}}}}finally{if(!O&&!F&&V.return)c()}if(v===void 0)throw new LN;if(v==="metering-clean-eof")Y.onCompletionWitness?.(v);Sg(W,Y.validateToolArguments);let j=nL(m);if(Y.emitAnthropicReasoningMetadata){if(!R&&j.signature!==void 0)R=!0,yield{canonicalOutputVersion:$I,type:"reasoning_delta",text:""};if(R&&!H&&j.signature!==void 0)yield{canonicalOutputVersion:$I,type:"reasoning_signature",signature:j.signature};if(!d&&j.redactedContent!==void 0)yield{canonicalOutputVersion:$I,type:"reasoning_redacted",data:Buffer.from(j.redactedContent).toString("base64")}}if(u&&g.length>0&&(R||j.text.length>0)&&j.signature===void 0)throw new kI("Kiro completed GPT reasoning without a signature before buffered assistant output","invalid_upstream_reasoning");for(let LI of M())yield LI;for(let LI of W.values())if(!LI.inputReceived)yield{canonicalOutputVersion:$I,type:"tool_call_delta",index:b.get(LI.toolUseId),arguments:LI.input};let WI={text:X,toolCalls:[...W.values()].map((LI)=>({id:LI.toolUseId,name:LI.name,input:LI.input}))},r=(Y.fingerprintOutput??jC)(WI),GI;try{if(!D)GI=Y.captureReasoning?.(j,r);Y.captureOutput?.(WI,r)}catch(LI){throw new J0({cause:LI})}if(Y.emitEncryptedReasoning&&GI!==void 0)yield{canonicalOutputVersion:$I,type:"reasoning_encrypted",encryptedContent:GI};let XI=Tg(Q,X,G,{inputTokenEstimate:Y.inputTokenEstimate,contextUsageWindow:Y.contextUsageWindow,toolCalls:WI.toolCalls,reasoning:{...j.signature!==void 0?{reasoningText:{text:j.text,signature:j.signature}}:{},...j.redactedContent!==void 0?{redactedContent:j.redactedContent}:{}}}),iI=XI.reported?.cacheReadInputTokens,sG=XI.reported?.cacheWriteInputTokens,JI=XI.reported?.inputTokens,eI=JI!==void 0&&JI>0&&iI!==void 0?iI/JI:void 0;y("info","sdk_usage_resolved",{request_id:Y.diagnostics?.requestId,model:G,input_source:XI.accounting?.input,output_source:XI.accounting?.output,context_source:XI.accounting?.context,input_tokens:XI.inputTokens,output_tokens:XI.outputTokens,context_tokens:XI.totalTokens,context_usage_percentage:XI.accounting?.contextUsagePercentage,context_usage_window:XI.accounting?.contextUsageWindow,percentage_saturated:XI.accounting?.percentageSaturated,metering_value:XI.accounting?.metering?.value,metering_unit:XI.accounting?.metering?.unit,cache_read_input_tokens:iI,cache_write_input_tokens:sG,cache_hit_ratio:eI}),yield{canonicalOutputVersion:$I,type:"completed",finishReason:W.size>0?"tool_calls":"stop",usage:XI,...L.length>0?{codeReferences:L}:{}}}class _g extends Error{name="MissingSdkEventStreamError";code="missing_upstream_stream";constructor(){super("SDK response has no event stream")}}async function rg(I,G,C,N,Y={}){if(!I.generateAssistantResponseResponse)throw new _g;let Z,W="",b=0,l="",Q=!1,L,m,V,X=new Map,R,{onCanonicalEvent:h,textLimit:H,...d}=Y;try{for await(let c of iL(I,G,C,N,d))switch(h?.(c),c.type){case"started":Z=c.createdAt;break;case"reasoning_delta":Q=!0,l+=c.text;break;case"reasoning_signature":L=c.signature;break;case"reasoning_redacted":m=c.data;break;case"reasoning_encrypted":V=c.encryptedContent;break;case"text_delta":if(H!==void 0){let v=ML(W,c.text);if(b+v>H.maxBytes)throw new kI(H.message,H.code);b+=v}W+=c.text;break;case"tool_call_delta":{let v=X.get(c.index);if(v){if(v.arguments+=c.arguments,c.id!==void 0)v.id=c.id;if(c.name!==void 0)v.name=c.name}else X.set(c.index,{id:c.id,name:c.name,arguments:c.arguments});break}case"completed":R=c;break}}catch(c){if(c instanceof LN&&N?.aborted)throw N.reason;throw c}if(N?.aborted)throw N.reason;if(R===void 0)throw new LN;let O=[];for(let c of X.values()){if(c.id===void 0||c.name===void 0)throw new kI("Canonical tool call completed without an id and name","upstream_protocol_error");O.push({id:c.id,name:c.name,input:c.arguments})}let F={...Q?{text:l}:{},...L!==void 0?{signature:L}:{},...m!==void 0?{redactedContent:m}:{},...V!==void 0?{encryptedContent:V}:{}};return{canonicalOutputVersion:$I,conversationId:C,model:G,createdAt:Z??Math.floor(Date.now()/1000),text:W,...Object.keys(F).length>0?{reasoning:F}:{},toolCalls:O,finishReason:R.finishReason,usage:R.usage,...R.codeReferences!==void 0?{codeReferences:R.codeReferences}:{}}}class og{#I=new Map;get size(){return this.#I.size}record(I,G,C,N,Y){let Z=this.#I.get(I),W=Z!==void 0&&G-Z.lastAt<=C,b=new Set(W?Z.accountIds:[]);if(Y!==void 0)b.add(Y);let l=W&&Z!==void 0?{count:Z.count+1,firstAt:Z.firstAt,lastAt:G,accountIds:b}:{count:1,firstAt:G,lastAt:G,accountIds:b};if(this.#I.set(I,l),this.#I.size>N)this.#G(G,C,N,I);return l}peek(I,G,C){let N=this.#I.get(I);if(N===void 0)return;if(G-N.lastAt>C){this.#I.delete(I);return}return N}clear(I){this.#I.delete(I)}reset(){this.#I.clear()}#G(I,G,C,N){for(let[Z,W]of this.#I)if(I-W.lastAt>G)this.#I.delete(Z);if(this.#I.size<=C)return;let Y=[...this.#I.entries()].filter(([Z])=>Z!==N).sort((Z,W)=>Z[1].lastAt-W[1].lastAt);for(let[Z]of Y){if(this.#I.size<=C)return;this.#I.delete(Z)}}}var PL=new og;class tZ extends Error{timeoutMs;name="StreamIdleTimeoutError";code="upstream_stream_idle_timeout";constructor(I){super(`SDK stream idle timeout after ${I}ms`);this.timeoutMs=I}}var tbI=new Set(["reasoning_delta","reasoning_redacted","text_delta","tool_call_delta","completed"]);function _bI(I){return tbI.has(I.type)}var rbI=1000;class IK{model;conversationId;mode;context;#I=new Set;#G=new Set;watchIdle(I,G){this.upstreamReadStartedAt=this.#C();let C,N=()=>{clearTimeout(C),C=setTimeout(G,I)};return this.#I.add(N),N(),()=>{clearTimeout(C),this.#I.delete(N)}}eventTypeCounts=new Map;rawEventCount=0;lastEventType;firstFrameAt;lastFrameAt;upstreamReadStartedAt;canonicalEventCount=0;reasoningChars=0;visibleChars=0;toolCount=0;reasoningRedacted=!1;reasoningSigned=!1;reasoningEncrypted=!1;openToolIntents=0;stoppedToolIntents=0;toolDeltaCount=0;witnessKind;completed;terminalEmitted=!1;semantic=!1;constructor(I,G,C,N={}){this.model=I;this.conversationId=G;this.mode=C;this.context=N}get semanticSeen(){return this.semantic}get completionWitnessed(){return this.witnessKind!==void 0}get completedSeen(){return this.completed!==void 0}get collectorSemanticSeen(){return this.reasoningChars>0||this.visibleChars>0||this.reasoningRedacted||this.completed!==void 0}observeCanonicalEvent(I){if(this.canonicalEventCount+=1,_bI(I))this.semantic=!0;switch(I.type){case"reasoning_delta":this.reasoningChars+=I.text.length;break;case"reasoning_redacted":this.reasoningRedacted=!0;break;case"reasoning_signature":this.reasoningSigned=!0;break;case"reasoning_encrypted":this.reasoningEncrypted=!0;break;case"text_delta":this.visibleChars+=I.text.length;break;case"tool_call_delta":this.#G.add(I.index),this.toolDeltaCount+=1;break;case"completed":this.toolCount=this.#G.size,this.completed=I;break;case"started":break}}onRawEvent(I){this.context.diagnostics?.rawFrame();for(let G of this.#I)G();this.rawEventCount+=1,this.lastFrameAt=this.#C(),this.firstFrameAt??=this.lastFrameAt,this.lastEventType=I.join("+");for(let G of I)this.eventTypeCounts.set(G,(this.eventTypeCounts.get(G)??0)+1)}onUpstreamReadSettled(){this.upstreamReadStartedAt=void 0}onCompletionWitness(I){this.context.diagnostics?.witness(),this.witnessKind=I,y("info","sdk_stream_completion_witness",{request_id:this.context.requestId,attempt:this.context.attempt,model:this.model,conversation_hash:a(this.conversationId),effort:this.context.effort,account_hash:this.context.accountHash,witness_kind:I,mode:this.mode})}onToolCallProgress(I){this.openToolIntents=I.open,this.stoppedToolIntents=I.stopped}isEmptyCompletion(){return this.completed!==void 0&&this.completionWitnessed&&this.reasoningChars===0&&this.visibleChars===0&&this.toolCount===0&&!this.reasoningRedacted&&!this.reasoningSigned&&!this.reasoningEncrypted}#C(){return(this.context.now??Date.now)()}upstreamWentQuiet(){if(this.upstreamReadStartedAt===void 0)return!1;let I=Math.max(this.upstreamReadStartedAt,this.lastFrameAt??0),G=Math.max(0,this.#C()-I);if(G<rbI)return!1;let C=this.firstFrameAt===void 0||this.lastFrameAt===void 0?0:Math.max(0,this.lastFrameAt-this.firstFrameAt);return G>=C}stallFields(){return{last_frame_age_ms:this.lastFrameAt===void 0?void 0:Math.max(0,this.#C()-this.lastFrameAt),canonical_event_count:this.canonicalEventCount,reasoning_chars:this.reasoningChars,visible_chars:this.visibleChars,tool_count:this.toolCount,tool_delta_count:this.toolDeltaCount,tool_intent_count:this.openToolIntents+this.stoppedToolIntents,tool_intent_open_count:this.openToolIntents,tool_intent_stopped_count:this.stoppedToolIntents,tool_intent_open:this.openToolIntents>0,tool_intent_all_stopped:this.openToolIntents===0&&this.stoppedToolIntents>0,completion_witnessed:this.completionWitnessed}}auditFields(){return{request_id:this.context.requestId,attempt:this.context.attempt,model:this.model,conversation_hash:a(this.conversationId),effort:this.context.effort,account_hash:this.context.accountHash,mode:this.mode,raw_event_count:this.rawEventCount,last_event_type:this.lastEventType,event_type_counts:JSON.stringify(Object.fromEntries([...this.eventTypeCounts.entries()].sort()))}}terminalFields(I){return{...this.auditFields(),terminal_provenance:I,completion_witnessed:this.completionWitnessed,witness_kind:this.witnessKind,canonical_event_count:this.canonicalEventCount,reasoning_chars:this.reasoningChars,visible_chars:this.visibleChars,tool_count:this.toolCount,tool_delta_count:this.toolDeltaCount,tool_intent_count:this.openToolIntents+this.stoppedToolIntents,tool_intent_open_count:this.openToolIntents,tool_intent_stopped_count:this.stoppedToolIntents,tool_intent_open:this.openToolIntents>0,reasoning_redacted:this.reasoningRedacted,finish_reason:this.completed?.finishReason,finish_reason_synthesized:this.completed===void 0?void 0:!0}}emitTerminal(I){if(this.terminalEmitted)return!1;return this.terminalEmitted=!0,y("info","sdk_stream_terminal",this.terminalFields(I)),!0}}function xh(I,G,C,N={}){return new IK(I,G,C,N)}function Mh(I,G){let C=xh(I.model,I.conversationId,"stream",I.telemetryContext),N=new AbortController,Y=AbortSignal.any([G,N.signal]),Z=Promise.resolve();return{iterator:iL(I.sdkResponse,I.model,I.conversationId,Y,{inputTokenEstimate:I.inputTokenEstimate,contextUsageWindow:I.contextUsageWindow,...I.captureReasoning?{captureReasoning:I.captureReasoning}:{},emitEncryptedReasoning:I.emitEncryptedReasoning,emitAnthropicReasoningMetadata:I.emitAnthropicReasoningMetadata,bufferLateGptReasoning:I.bufferLateGptReasoning,prefetchFableReasoning:I.prefetchFableReasoning,reasoningReplayDecision:I.reasoningReplayDecision,...I.fingerprintOutput?{fingerprintOutput:I.fingerprintOutput}:{},...I.captureOutput?{captureOutput:I.captureOutput}:{},onCompletionWitness:(b)=>C.onCompletionWitness(b),onRawEvent:(b)=>C.onRawEvent(b),onIteratorCleanup:(b)=>{Z=b},onToolCallProgress:(b)=>C.onToolCallProgress(b),maxToolArgumentsBytes:I.maxToolArgumentsBytes,validateToolArguments:I.validateToolArguments,diagnostics:I.telemetryContext?.diagnostics})[Symbol.asyncIterator](),streamAbort:N,composedSignal:Y,telemetry:C,prefetched:[],upstreamCleanup:()=>Z}}function GK(I){return FI(async()=>{try{await I.iterator.return?.(void 0)}finally{await I.upstreamCleanup?.()}})}function fL(I,G,C){return WG(()=>{if(!I.streamAbort.signal.aborted)I.streamAbort.abort(C)},()=>G?.(C)),GK(I)}var eg={"normal-complete":"normal_complete","external-abort":"external_abort","consumer-cancel":"consumer_cancel","idle-timeout":"idle_timeout","upstream-error":"upstream_error"};function CK(I,G,C,N){let Y=I.prepared??Mh(I,G),{iterator:Z,streamAbort:W,composedSignal:b,telemetry:l}=Y,Q=Y.prefetched.splice(0),L=Q.length>0?void 0:Z.next(),m=new TextEncoder,V=(J)=>m.encode(`${JSON.stringify(J)}
|
|
375
|
-
`),X,R,h,H,d=()=>{h?.(),h=void 0},O=(J)=>{if(X!==void 0)return!1;return X=J,!0},F=()=>{b.removeEventListener("abort",v)},c=(J,u,g=!1)=>{if(!O(J))return R??Promise.resolve();let A=()=>{},p=new Promise((q)=>{A=q});R=p;let D={provenance:eg[J],requestDeadline:g,upstreamQuiet:l.upstreamWentQuiet(),localPersistence:u instanceof J0};if(WG(()=>l.emitTerminal(eg[J])),WG(()=>I.onTerminal?.(D)),WG(F,d,()=>{if(J==="normal-complete")H?.close();else if(J!=="consumer-cancel")H?.error(u)},()=>{if(J!=="normal-complete")I.abortUpstream?.(u)},()=>N(p)),J!=="normal-complete")WG(()=>{if(!W.signal.aborted)W.abort(u)});return GK(Y).then(A,A),R},v=()=>{let J=b.reason instanceof Error&&b.reason.name==="TimeoutError";I.telemetryContext?.diagnostics?.cancel(J?"request_deadline":"external_abort"),c("external-abort",_I(b),J)};return new Response(new ReadableStream({start(J){if(H=J,b.addEventListener("abort",v,{once:!0}),b.aborted){v();return}for(let u of Q)J.enqueue(V(u))},async pull(J){if(X!==void 0)return;h=l.watchIdle(C,()=>{let u=new tZ(C);I.telemetryContext?.diagnostics?.failure(u,"upstream_stream"),y("warn","sdk_stream_idle_timeout",{...l.auditFields(),...l.stallFields(),...rY(u,I.telemetryContext?.diagnostics),idle_timeout_ms:C}),c("idle-timeout",u)});try{let u=L??Z.next();L=void 0;let g=await u;if(l.onUpstreamReadSettled(),X!==void 0)return;if(d(),g.done){y("info","sdk_stream_completed",l.auditFields()),await c("normal-complete");return}l.observeCanonicalEvent(g.value),J.enqueue(V(g.value))}catch(u){if(l.onUpstreamReadSettled(),X!==void 0)return;let g=u instanceof Error?u:TypeError("SDK stream failed with a non-Error reason",{cause:u});y("warn","sdk_stream_upstream_error",{...l.auditFields(),...rY(g,I.telemetryContext?.diagnostics)}),I.telemetryContext?.diagnostics?.failure(g,"upstream_stream"),await c("upstream-error",g)}},cancel(J){if(H=void 0,l.completedSeen)return c("normal-complete");if(!l.completionWitnessed)I.telemetryContext?.diagnostics?.cancel("consumer_cancel");return c("consumer-cancel",J)}}),{headers:{"Content-Type":MA,...I.reasoningReplayDecision?.mode==="conflict-omitted"?{"x-kiro-reasoning-replay-mode":"conflict-omitted"}:{}}})}async function NK(I,G,C){let N=Promise.withResolvers(),Y=Promise.resolve().then(()=>I.send(G,{...C,onResponseHeaders(W){C.onResponseHeaders?.(W);let b=Object.entries(W.headers).find(([l])=>l.toLowerCase()==="content-type")?.[1];if(W.status>=200&&W.status<300&&b?.split(";")[0]?.trim().toLowerCase()==="application/vnd.amazon.eventstream")N.resolve(W);else if(W.status>=200&&W.status<300)N.reject(new kI("Upstream did not return an AWS EventStream response","invalid_upstream_response"))}}));Y.catch(()=>{return});let Z=await Promise.race([Y.then((W)=>({kind:"decoded",response:W})),N.promise.then((W)=>({kind:"accepted",metadata:W}))]);if(Z.kind==="decoded")return Z.response;return{generateAssistantResponseResponse:{async*[Symbol.asyncIterator](){let b=(await Y).generateAssistantResponseResponse;if(!b)throw new sL;yield*b}}}}var O9=NI(PH(),1),F9=NI(Z9(),1),v9=NI(c9(),1);function D2(I,G=!0,C){let N=new Map,Y=new Map;for(let[b,l]of I.entries())try{if(l.schema.$async===!0||N.has(l.name))throw Error("invalid schema");if(l.publicType==="custom"){N.set(l.name,()=>!0);continue}let Q=typeof l.schema.$schema==="string"?l.schema.$schema:"",L=Q.includes("2020-12")?"2020":Q.includes("2019-09")?"2019":"7",m=Y.get(L);if(!m){let V={strict:!1,allErrors:!1,validateFormats:!1,ownProperties:!0,coerceTypes:!1,useDefaults:!1,removeAdditional:!1,addUsedSchema:!1};m=L==="2020"?new v9.default(V):L==="2019"?new F9.default(V):new O9.default(V),Y.set(L,m)}N.set(l.name,m.compile(l.schema))}catch{throw new ZI("Tool schema cannot be validated; external references and asynchronous schemas are not supported","invalid_tool_schema",l.path??`tools[${b}].parameters`)}let Z=(b)=>{if(C!==void 0)throw new kI(C.message,C.code);if(!G)throw new kI("Upstream called a tool despite tool_choice=none","upstream_tool_choice_violation");if(!N.has(b))throw new kI("Upstream returned an undeclared tool call","unknown_upstream_tool")};return Object.assign((b,l)=>{if(Z(b),!N.get(b)(l))throw new kI("Upstream tool arguments do not match the declared schema","upstream_tool_schema_violation")},{assertName:Z})}function LhI(I){return I.messages.some((G)=>G.role==="system"||G.role==="developer")}function q2(I){return typeof I==="object"&&I!==null&&!Array.isArray(I)}function mhI(I){if(!q2(I))return!1;let G=I.conversationState;return q2(G)&&typeof G.conversationId==="string"&&q2(G.currentMessage)&&typeof G.chatTriggerType==="string"}function VhI(I,G){return{think:G.endsWith("-thinking")||I.thinking?.enabled===!0,budget:I.thinking?.budgetTokens??20000}}function HN(I,G,C){return s(I,G,"upstream_error",C)}function Yw(I){return I instanceof LN||I instanceof kI||I instanceof OC}function u9(I){return I instanceof VG||I instanceof Rb}function p9(I){let G=I instanceof VG?I.code:void 0;return G?`${G}: ${I.message}`:I.message}var XhI=/invalid\s+`?signature`?\s+in\s+`?thinking`?\s+block/i,RhI="THINKING_SIGNATURE_INVALID";function E9(I){if(I.reason===RhI)return!0;return I.status===400&&XhI.test(I.message)}var hhI="REQUEST_BODY_INVALID";function HhI(I){return(I.status===void 0||I.status===400)&&(I.reason===hhI||E9(I))}function z9(I,G,C){let N=I.accountManager.countSelectableAccounts?.(C);if(N!==void 0)return N;let Y=Date.now();return G.filter((Z)=>C.has(Z.id)&&HC(Z,Y)).length}function whI(I,G,C,N){let Y=I.filter((Z)=>G.has(Z.id)&&Z.isHealthy&&!nI(Z,N)&&Z.rateLimitResetTime>C).map((Z)=>Z.rateLimitResetTime-C);return Y.length===0?void 0:Math.min(...Y)}function dhI(){return{kind:"response",response:s(503,"Token refresh failed for every usable Kiro account","service_unavailable","upstream_token_refresh_failed")}}function J9(I,G){let C=Date.now()+I.config.quota_recheck_interval_ms;if(I.accountManager.markQuotaExhausted)I.accountManager.markQuotaExhausted(G,C);else I.accountManager.markRateLimited(G,C);y("warn","quota_exhausted_account_persisted",{account_hash:a(G.id),recheck_after:C})}function chI(I){let G=I.modelCapabilities?.isKnownModel(I.model)??!1;return{kind:"response",response:s(G?503:400,G?`Model ${I.model} is not available to any currently usable Kiro account`:`Model ${I.model} is not supported by Kiro`,G?"service_unavailable":"invalid_request_error",G?"model_unavailable_for_accounts":"unsupported_model","model")}}function OhI(I,G){if(I.config.test_upstream_endpoint)return I.config.test_upstream_endpoint;return I.config.runtime_endpoint_mode==="kiro-runtime"?DI.RUNTIME_ENDPOINT.replace("{{region}}",G):void 0}function A9(I,G){let C=new Map(I.tools.map((N)=>[N.wireName,N]));return(N)=>{let Y={text:N.text,toolCalls:N.toolCalls.map((Z)=>{let W=C.get(Z.name);if(!W)return Z;if(W.publicType!=="custom")return{...Z,name:W.name};let b=Z.input;try{let l=JSON.parse(Z.input);if(q2(l)&&Object.keys(l).length===1&&typeof l.input==="string")b=l.input}catch{}return{...Z,name:W.name,input:b}})};return G?Yh(Y,G):jC(Y)}}function g9(I,G){if(!I.clientNormalization)return{};let C=I.body.messages[G];if(!C||C.role!=="assistant")throw new KI("Reasoning replay does not reference assistant output","invalid_reasoning_replay");return{clientNormalization:I.clientNormalization,normalizedOutputFingerprint:Yh({text:CC(C.content),toolCalls:C.toolCalls.map((N)=>({id:N.id,name:N.name,input:JSON.stringify(N.input)}))},I.clientNormalization)}}function $N(I,G,C,N){let Y=new Headers({"Content-Type":"application/json"});if(N!==void 0)Y.set("Retry-After",String(Math.max(1,Math.ceil(N/1000))));return{kind:"response",response:new Response(JSON.stringify({error:{message:G,type:I===429?"rate_limit_error":I===402?"insufficient_quota":I===401||I===403?"authentication_error":"service_unavailable",code:C,...N!==void 0?{retry_after_ms:N}:{}}}),{status:I,headers:Y})}}function Zw(){return $N(503,"The account bound to signed reasoning replay is currently unavailable","reasoning_replay_account_unavailable")}function FhI(I,G,C,N){let Y=C.find((b)=>b.id===G.boundAccountId);if(!Y)return{kind:"result",result:Zw()};let Z=Date.now(),W=I.config.request_timeout_ms-(Z-G.startedAt);if(nI(Y,_0(I))){let b=Y.rateLimitResetTime>Z?Y.rateLimitResetTime-Z:void 0;return{kind:"result",result:$N(402,"The account bound to signed reasoning replay has exhausted its included quota","reasoning_replay_account_quota_exhausted",b)}}if(Y.isHealthy&&Y.rateLimitResetTime>Z){let b=Y.rateLimitResetTime-Z;if(b<=W)return y("info","reasoning_replay_rate_limit_wait",{wait_ms:b,remaining_ms:W}),{kind:"wait",waitMs:b};return{kind:"result",result:$N(429,"The account bound to signed reasoning replay is temporarily rate-limited","reasoning_replay_account_rate_limited",b)}}if(!Y.isHealthy&&xG(Y.unhealthyReason))return{kind:"result",result:$N(403,"The account bound to signed reasoning replay requires re-authentication","reasoning_replay_account_reauthentication_required")};if(!N.has(Y.id))return{kind:"result",result:$N(503,`Model ${I.model} is unavailable on the account bound to signed reasoning replay`,"reasoning_replay_model_unavailable")};return{kind:"result",result:$N(503,"The account bound to signed reasoning replay is unhealthy","reasoning_replay_account_unhealthy")}}function vhI(I,G,C){if(I.config.reasoning_replay_account_failover!=="verified")return;let N=G.provenance;if(G.portable===!0&&N){if(N.protocol!==I.body.protocol||!N.profileArn||N.upstreamOperation!=="GenerateAssistantResponse")return;let l=`${N.protocol}:${I.model}:${N.region}:${N.runtimeProtocol}:profile:${G.replay.content.kind}`,Q=uhI.has(l);return K9.has(l)||Q?{region:N.region,runtimeProtocol:N.runtimeProtocol,profileRequired:!0,...Q?{profileArn:N.profileArn}:{}}:void 0}if(G.legacyPortable!==!0&&G.databaseLegacy!==!0||I.config.reasoning_replay_legacy_account_failover!=="verified-current-cell"||I.body.projectionMode!=="v3-auto"&&I.body.projectionMode!=="native-context-safe"&&I.body.projectionMode!=="legacy-user-prefix")return;let Y=C?.get(G.accountId);if(!Y?.profileArn)return;let Z=W0(Y.profileArn)??Y.region,W=I.body.projectionMode==="legacy-user-prefix"?"codewhisperer":"kiro-runtime",b=`${I.body.protocol}:${I.model}:${Z}:${W}:profile:${G.replay.content.kind}`;return K9.has(b)?{region:Z,runtimeProtocol:W,profileRequired:!0,legacyCurrentCell:!0}:void 0}var K9=new Set(["responses:gpt-5.6-sol:us-east-1:kiro-runtime:profile:reasoning_text","responses:gpt-5.6-sol:us-east-1:codewhisperer:profile:reasoning_text","anthropic-messages:claude-sonnet-5:us-east-1:kiro-runtime:profile:reasoning_text","anthropic-messages:claude-opus-5:us-east-1:kiro-runtime:profile:reasoning_text"]),uhI=new Set(["anthropic-messages:claude-fable-5-1:us-east-1:kiro-runtime:profile:reasoning_text"]);function JhI(I,G){if(I.body.reasoningReplays.length===0)return{replays:[],portableCount:0,legacyPortableCount:0};let C,N,Y=G?.accountId,Z=G?.conversationId,W=0,b=0,l,Q,L,m,V=I.config.reasoning_replay_legacy_account_failover==="verified-current-cell"?new Map(I.accountManager.reconcileFromDb().map((H)=>[H.id,H])):void 0,X=[],R=I.body.reasoningReplays.flatMap((H,d)=>{if(H.lookup.kind!=="responses-token"&&H.lookup.kind!=="anthropic-token")return[];if(!I.tenantId)throw new KI("Reasoning replay requires an authenticated tenant context","reasoning_replay_context_required");let O=H.lookup.kind==="responses-token"?H.lookup.encryptedContent:H.lookup.signature;return[{index:d,token:O,context:{tenantId:I.tenantId,model:I.body.model,outputFingerprint:H.outputFingerprint,...g9(I,H.insertBeforeMessage),...H.compatibleOutputFingerprints!==void 0?{compatibleOutputFingerprints:H.compatibleOutputFingerprints}:{},...C!==void 0?{accountId:C}:{},...N!==void 0?{conversationId:N}:{}},insertBeforeMessage:H.insertBeforeMessage}]}),h=new Map;if(R.length>0){let H=I.reasoningReplayStore;if(!H)throw new KI("Reasoning replay storage is unavailable","reasoning_replay_store_unavailable",!0);let d=H.resolveResponsesBatch?H.resolveResponsesBatch(R):R.map((O)=>H.resolveResponses(O.token,O.context,O.insertBeforeMessage));for(let[O,F]of R.entries()){let c=d[O];if(c)h.set(F.index,c)}}for(let[H,d]of I.body.reasoningReplays.entries()){if(d.lookup.kind==="anthropic-direct"){X.push({insertBeforeMessage:d.insertBeforeMessage,content:d.lookup.content});continue}if(!I.tenantId)throw new KI("Reasoning replay requires an authenticated tenant context","reasoning_replay_context_required");let O=I.reasoningReplayStore;if(!O)throw new KI("Reasoning replay storage is unavailable","reasoning_replay_store_unavailable",!0);let F={tenantId:I.tenantId,model:I.body.model,outputFingerprint:d.outputFingerprint,...g9(I,d.insertBeforeMessage),...d.compatibleOutputFingerprints!==void 0?{compatibleOutputFingerprints:d.compatibleOutputFingerprints}:{},...C!==void 0?{accountId:C}:{},...N!==void 0?{conversationId:N}:{}},c=d.lookup.kind==="chat-hash"?O.resolveChat(d.lookup.reasoningText,F,d.insertBeforeMessage):h.get(H);if(!c)throw new KI("Reasoning replay batch resolution was incomplete","reasoning_replay_not_found");let v=vhI(I,c,V);if(v!==void 0){if(l!==void 0&&l!==v.region||Q!==void 0&&Q!==v.runtimeProtocol||m!==void 0&&v.profileArn!==void 0&&m!==v.profileArn)throw new KI("Portable reasoning replay items resolve to different verified mint cells","reasoning_replay_context_mismatch");if(l=v.region,Q=v.runtimeProtocol,L=v.profileRequired,m??=v.profileArn,W+=1,v.legacyCurrentCell)b+=1;Y??=c.accountId,Z??=c.conversationId}else{if(C!==void 0&&C!==c.accountId||N!==void 0&&N!==c.conversationId)throw new KI("Reasoning replay items resolve to different accounts or conversations","reasoning_replay_context_mismatch");C=c.accountId,N=c.conversationId,Y=c.accountId,Z=c.conversationId}let J=c.replay.instructionProjection===void 0&&c.portable===!0&&c.provenance?.protocol==="anthropic-messages"&&c.provenance.runtimeProtocol==="kiro-runtime"&&I.body.protocol==="anthropic-messages"&&I.model==="claude-fable-5-1"&&I.body.projectionMode==="v3-auto"&&d.insertBeforeMessage>0;X.push(J?{...c.replay,instructionProjection:{version:1,legacyPrefixMessages:d.insertBeforeMessage},legacyProjectionUnversioned:!0}:c.replay)}if(b>0)y("warn","reasoning_replay_legacy_failover_admitted",{protocol:I.body.protocol,model:I.model,region:l,replay_count:b});return{...C!==void 0?{accountId:C}:{},...N!==void 0?{conversationId:N}:{},...Y!==void 0?{preferredAccountId:Y}:{},...Z!==void 0?{preferredConversationId:Z}:{},...l!==void 0?{portableRegion:l}:{},...Q!==void 0?{portableRuntimeProtocol:Q}:{},...L?{portableProfileRequired:L}:{},...m!==void 0?{portableProfileArn:m}:{},portableCount:W,legacyPortableCount:b,replays:X}}function AhI(I,G,C,N){let Y=I.body,Z=Y.includeEncryptedReasoning===!0||Y.protocol==="responses"&&Y.store!==!1||Y.protocol==="anthropic-messages",W=Y.protocol==="anthropic-messages",b=W&&Y.thinking?.enabled===!0&&cC(Y.model),l=W&&Y.thinking?.enabled===!0&&Y.thinking.display!=="summarized"&&nY(Y.model),Q={},L=I.lineage&&I.affinityStore?(m)=>{if(m.text.length===0&&m.toolCalls.length===0)return;let V=Nh(Y,m),X=I.lineage?.outputKeyHash(V);if(X===void 0)return;I.affinityStore?.recordOutputLineage(X,G,C,Date.now(),I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries),y("info","output_lineage_recorded",{protocol:Y.protocol,lineage_source:I.lineage?.source,lineage_hash:a(X),account_hash:a(G),conversation_hash:a(C)})}:void 0;if(!I.reasoningReplayStore||!I.tenantId)return{emitEncryptedReasoning:Z,emitAnthropicReasoningMetadata:W,bufferLateGptReasoning:b,prefetchFableReasoning:l,reasoningReplayDecision:Q,fingerprintOutput:A9(Y,I.clientNormalization),...L?{captureOutput:L}:{}};return{captureReasoning:(m,V)=>I.reasoningReplayStore?.store(m,{tenantId:I.tenantId,model:Y.model,accountId:G,conversationId:C,outputFingerprint:V,...I.clientNormalization?{clientNormalization:I.clientNormalization}:{},protocol:Y.protocol,region:N.region,...N.profileArn!==void 0?{profileArn:N.profileArn}:{},runtimeProtocol:N.runtimeProtocol,upstreamOperation:"GenerateAssistantResponse",instructionProjection:{version:1,...N.legacyPrefixMessages!==void 0?{legacyPrefixMessages:N.legacyPrefixMessages}:{}}}),emitEncryptedReasoning:Z,emitAnthropicReasoningMetadata:W,bufferLateGptReasoning:b,prefetchFableReasoning:l,reasoningReplayDecision:Q,fingerprintOutput:A9(Y,I.clientNormalization),...L?{captureOutput:L}:{}}}var ZZ={kind:"continue"};function vC(I){return{kind:"return",result:I}}function cY(I,G){return I.maxUpstreamDispatches===void 0||G.sdkDispatches<I.maxUpstreamDispatches}function Tb(I,G,C){y("warn","upstream_dispatch_budget_exhausted",{request_id:I.requestId,dispatches:G.sdkDispatches,max_dispatches:I.maxUpstreamDispatches,outcome:C,mode:I.stream?"stream":"non-stream"})}function Ww(I){if(I.affinity)return I.affinity;if(I.lineage?.lookupKeyHash!==void 0)return{keyHash:I.lineage.lookupKeyHash,source:I.lineage.source};return}function ghI(I,G,C){let N=I.config.session_affinity_stall_failover_threshold;if(N<=0||G===void 0||!I.affinityStore)return;let Y=(I.affinityStalls??PL).peek(G.keyHash,C,I.config.session_affinity_stall_window_ms);return Y!==void 0&&Y.count>=N?Y:void 0}function KhI(I){let G=Date.now(),C=I.affinity&&I.affinityStore?I.affinityStore.getSessionAffinity(I.affinity.keyHash):void 0,N=C===void 0&&I.lineage?.lookupKeyHash!==void 0&&I.affinityStore?I.affinityStore.resolveOutputLineage(I.lineage.lookupKeyHash):void 0,Y=JhI(I,C??N),Z=Y.accountId!==void 0,W=Ww(I),b=Z?void 0:ghI(I,W,G),l=b===void 0?C:void 0,Q=b===void 0?N:void 0,L=l??Q,m=Y.accountId??L?.accountId,V=m??(b===void 0?Y.preferredAccountId:void 0);if(b!==void 0&&W!==void 0)y("warn","session_affinity_stall_failover",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,affinity_source:W.source,affinity_hash:a(W.keyHash),stall_count:b.count,stall_span_ms:Math.max(0,b.lastAt-b.firstAt),stall_threshold:I.config.session_affinity_stall_failover_threshold,quarantined_binding:C!==void 0,quarantined_lineage:C===void 0&&N!==void 0});return{pendingMigration:void 0,migrationFallbackSpent:!1,migrationFallback:void 0,forcedRefreshAccountIds:new Set,serverErrors:new Map,requestExcludedAccountIds:new Set,reportedQuotaExhaustedAccountIds:new Set,refreshNetworkRetriedAccountIds:new Set,modelRejectedAccountIds:new Set,lastAuthenticationFailure:void 0,lastQuotaFailure:void 0,lastRefreshFailure:void 0,retryCount:0,iterations:0,startedAt:G,binding:l,lineageBinding:Q,replayState:Y,replayLocked:Z,affinityQuarantined:b!==void 0,quarantinedAccountIds:b===void 0?new Set:b.accountIds.size>0?new Set(b.accountIds):new Set([(C??N)?.accountId].filter((X)=>X!==void 0)),lineageStallRow:I.affinity===void 0?N:void 0,boundAccountId:m,preferredAccountId:V,requestAccountId:V,requestConversationId:Y.conversationId??L?.conversationId??(b===void 0?Y.preferredConversationId:void 0),streamAttempts:0,sdkDispatches:0,streamRetriedAccountIds:new Set,emptyCompletionRetried:!1,lastStreamFailure:void 0}}function j2(I){I.preferredAccountId=void 0,I.requestAccountId=void 0,I.requestConversationId=void 0}function khI(I,G,C,N){let Y=p9(N),Z=N instanceof VG&&GN(Y),W=N instanceof VG&&N.code==="NETWORK_ERROR";if(G.lastRefreshFailure=N,W&&!G.refreshNetworkRetriedAccountIds.has(C.id))return G.refreshNetworkRetriedAccountIds.add(C.id),y("warn","account_token_refresh_retry",{account_hash:a(C.id),error_code:N.code}),"retry";if(G.replayLocked){if(N instanceof VG)if(Z)I.accountManager.markUnhealthy(C,AN(Y));else I.accountManager.markRateLimited(C,Date.now()+I.config.rate_limit_retry_delay_ms);return y("warn","reasoning_replay_account_refresh_failed",{account_hash:a(C.id),error_type:N.name,error_code:N instanceof VG?N.code:void 0,refresh_token_dead:Z}),"switch"}if(G.requestExcludedAccountIds.add(C.id),N instanceof VG)if(Z)I.accountManager.markUnhealthy(C,AN(Y));else I.accountManager.markRateLimited(C,Date.now()+I.config.rate_limit_retry_delay_ms);return y("warn","account_token_refresh_failed",{account_hash:a(C.id),error_type:N.name,error_code:N instanceof VG?N.code:void 0,refresh_token_dead:Z}),j2(G),"switch"}async function k9(I,G,C,N,Y,Z="initial"){let W=khI(I,C,N,Y);if(C.replayLocked){if(Y instanceof VG&&GN(p9(Y)))return vC($N(403,"The account bound to signed reasoning replay requires re-authentication","reasoning_replay_account_reauthentication_required"));if(Y instanceof Rb)return vC(Zw());if(W!=="retry"||Z==="forced")return vC($N(503,"Token refresh failed for the account bound to signed reasoning replay","reasoning_replay_account_refresh_failed"))}if(W==="retry")await MN(I.config.rate_limit_retry_delay_ms,G);return ZZ}async function yhI(I,G,C){let N=I.quotaRechecker;if(!N)return;let Y=I.accountManager.reconcileFromDb(),Z=Date.now(),W=Y.some((l)=>HC(l,Z)),b=C.replayLocked&&Y.some((l)=>l.id===C.boundAccountId&&nI(l,_0(I)));if(W&&!b){N.recheckDueAccounts(Y,new AbortController().signal,C.boundAccountId).catch((l)=>{y("warn","quota_recheck_background_failed",{error_type:l instanceof Error?l.name:typeof l})});return}await N.recheckDueAccounts(Y,G,C.boundAccountId)}function D9(I){return{kind:"response",response:HN(I.status??403,I.message,I.code??"upstream_authentication_failed")}}function _0(I){return I.accountManager.getOveragePolicy?.()??DW(I.config)}function phI(){return{kind:"response",response:HN(402,"All eligible Kiro accounts are blocked by paid overage; set stop_on_overage to false or raise overage_threshold to keep using them","paid_overage_blocked")}}function q9(I){return{kind:"response",response:HN(402,I?.message??"All eligible Kiro accounts have exhausted their quota",I?.code??"quota_exhausted")}}function EhI(I,G){if(G.lastAuthenticationFailure)return D9(G.lastAuthenticationFailure);if(G.lastQuotaFailure)return q9(G.lastQuotaFailure);return{kind:"response",response:s(500,`Exceeded max iterations (${I.config.max_request_iterations})`,"request_error","max_request_iterations")}}function zhI(I,G,C){let N=G.preferredAccountId;if(G.replayState.portableCount===0||N===void 0)return;if(!C.has(N))return;return VY(N)<I.config.account_inference_concurrency?N:void 0}function DhI(I,G){let C=I.accountManager.reconcileFromDb(),N=C.filter((J)=>!G.modelRejectedAccountIds.has(J.id)&&!G.requestExcludedAccountIds.has(J.id)),Y=_0(I),Z=N.filter((J)=>nI(J,Y)),W=Z.filter((J)=>!G.reportedQuotaExhaustedAccountIds.has(J.id));for(let J of W)G.reportedQuotaExhaustedAccountIds.add(J.id);if(W.length>0)y("info","quota_exhausted_accounts_excluded",{account_count:W.length});let b=N.filter((J)=>!nI(J,Y)).map((J)=>J.id),l=I.modelCapabilities?.eligibleAccountIds(I.model,b),Q=new Set([...l??b].filter((J)=>!G.modelRejectedAccountIds.has(J)&&(G.replayState.portableRegion===void 0||(()=>{let u=C.find((A)=>A.id===J);if(!u)return!1;return(W0(u.profileArn)??u.region)===G.replayState.portableRegion&&(!G.replayState.portableProfileRequired||u.profileArn!==void 0)&&(G.replayState.portableProfileArn===void 0||u.profileArn===G.replayState.portableProfileArn)})()))),L=G.migrationFallback?.accountId,m=Date.now(),V=C.filter((J)=>Q.has(J.id)&&HC(J,m,Y)&&(!G.replayLocked||J.id===G.replayState.accountId)&&(L===void 0||J.id===L)),X=V.filter((J)=>!G.quarantinedAccountIds.has(J.id)),R=!G.replayLocked&&X.length>0?X:V,h=new Set(R.map((J)=>J.id)),H=zhI(I,G,h),d=H===void 0?qL(R,h,Y):new Set([H]);if(d.size>0&&[...d].every((J)=>VY(J)>=I.config.account_inference_concurrency))return{kind:"capacity-wait",accountIds:h};let O=I.accountManager.selectHealthyAccount(G.preferredAccountId,d);if(O&&(G.replayState.accountId===void 0||O.id===G.replayState.accountId))return{kind:"selected",selection:{selected:O,accounts:C,eligibleAccountIds:Q}};if(G.migrationFallback!==void 0)return{kind:"result",result:G.migrationFallback.terminal};if(G.replayLocked)return FhI(I,G,C,Q);if(b.length===0&&G.lastAuthenticationFailure)return{kind:"result",result:D9(G.lastAuthenticationFailure)};if(b.length===0&&G.lastQuotaFailure===void 0&&I.accountManager.blockedByOverageOnly?.(new Set(N.map((J)=>J.id)))===!0)return{kind:"result",result:phI()};if(b.length===0&&(Z.length>0||G.lastQuotaFailure))return{kind:"result",result:q9(G.lastQuotaFailure)};if(b.length===0&&G.lastStreamFailure!==void 0)return{kind:"result",result:B2(void 0,G.lastStreamFailure)};if(b.length===0&&G.lastRefreshFailure!==void 0)return{kind:"result",result:dhI()};if(G.modelRejectedAccountIds.size>0||l!==void 0&&Q.size===0)return{kind:"result",result:chI(I)};let F=Date.now(),c=whI(N,new Set(l??b),F,_0(I)),v=I.config.request_timeout_ms-(F-G.startedAt);if(c!==void 0&&c<=v)return y("info","rate_limit_wait_for_reset",{wait_ms:c,remaining_ms:v}),{kind:"wait",waitMs:c};return{kind:"result",result:{kind:"response",response:s(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")}}}function qhI(I,G,C){let N=Date.now();G.pendingMigration=void 0;let Y=G.replayState.portableCount>0&&G.replayState.preferredAccountId!==void 0&&C.id!==G.replayState.preferredAccountId,Z=Y&&G.binding?.accountId!==C.id,W=Z&&I.affinity!==void 0&&I.affinityStore!==void 0,b=G.binding?.accountId??G.replayState.preferredAccountId;if(Y)G.requestAccountId=C.id,G.requestConversationId=t0();if(Z)G.pendingMigration={fromAccountId:b,fromConversationId:G.binding?.conversationId??G.replayState.preferredConversationId,toAccountId:C.id,toConversationId:G.requestConversationId,replayCount:G.replayState.portableCount,legacyReplayCount:G.replayState.legacyPortableCount};else if(I.affinity&&I.affinityStore)if(!G.binding){let l=G.affinityQuarantined?I.affinityStore.rebindSessionAffinity(I.affinity.keyHash,C.id,t0(),N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries):I.affinityStore.claimSessionAffinity(I.affinity.keyHash,C.id,G.requestConversationId??t0(),N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries);if(G.affinityQuarantined=!1,G.binding=l,G.preferredAccountId=l.accountId,G.requestConversationId=l.conversationId,G.replayLocked&&(l.accountId!==G.replayState.accountId||l.conversationId!==G.replayState.conversationId))throw new KI("Session affinity conflicts with signed reasoning replay","reasoning_replay_context_mismatch");if(l.accountId!==C.id)return"reselect"}else if(G.binding.accountId===C.id&&(!G.replayLocked||G.binding.conversationId===G.replayState.conversationId))G.binding=I.affinityStore.claimSessionAffinity(I.affinity.keyHash,C.id,G.binding.conversationId,N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries),G.requestConversationId=G.binding.conversationId;else G.binding=I.affinityStore.rebindSessionAffinity(I.affinity.keyHash,C.id,G.replayLocked?G.replayState.conversationId:t0(),N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries),G.requestConversationId=G.binding.conversationId;else if(!G.replayLocked&&G.requestAccountId!==C.id)G.requestAccountId=C.id,G.requestConversationId=t0();if(Z)y("info","reasoning_replay_account_migrated",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,from_account_hash:a(b),to_account_hash:a(C.id),replay_count:G.replayState.portableCount,legacy_replay_count:G.replayState.legacyPortableCount,binding:W?"deferred":"none"});return G.preferredAccountId=C.id,y("info","upstream_affinity_selected",{request_id:I.requestId,projection_mode:I.config.protocol_projection_mode,session_affinity_mode:I.config.session_affinity_mode,affinity_source:I.affinity?.source??I.lineage?.source,affinity_bound:G.binding!==void 0||G.lineageBinding!==void 0,affinity_kind:G.binding!==void 0?"explicit":G.lineageBinding!==void 0?"history-lineage":void 0,account_hash:a(C.id),conversation_hash:G.requestConversationId===void 0?void 0:a(G.requestConversationId),reasoning_replay_locked:G.replayLocked}),"proceed"}async function UhI(I,G,C,N,Y){let{think:Z,budget:W}=VhI(I.body,I.model),b=N,l=!1;try{I.diagnostics?.phase("token_refresh");let Q=I.accountManager.toAuthDetails(N);b=await wG(I.tokenRefresher.refreshIfNeeded(N,Q,G),G);let L=I.accountManager.toAuthDetails(b);if(I.diagnostics?.phase("request_validation"),I.modelCapabilities){let B=await wG(I.modelCapabilities.ensureAccountModel(b,L,I.model,G),G);if(!B.supported)return y("warn","account_model_unavailable",{request_id:I.requestId,account_hash:a(b.id),model_hash:a(I.model),capability_source:B.source}),{kind:"model-unavailable",account:b}}let m=!1;if((I.body.projectionMode==="v3-auto"||I.body.projectionMode==="native-context-safe"||I.body.protocol==="responses"&&I.body.projectionMode==="legacy-user-prefix")&&LhI(I.body)){let B=I.nativeContextCapabilities?await wG(I.nativeContextCapabilities.ensureAccountNativeContext(b,L,G),G):{status:"unknown",source:"probe-error",featureCount:0,systemFieldInjection:!1,systemPromptMigration:!1};if(y("debug","native_context_capability_selected",{request_id:I.requestId,account_hash:a(b.id),status:B.status,source:B.source,feature_count:B.featureCount,system_field_injection:B.systemFieldInjection,system_prompt_migration:B.systemPromptMigration}),I.body.projectionMode==="native-context-safe"&&B.status!=="available")throw new ZI(B.status==="unknown"?"Kiro Runtime native instruction capability could not be verified; native-context-safe remains fail-closed":"Kiro Runtime did not advertise system_field_injection for this account; native-context-safe remains fail-closed","native_context_capability_unavailable");m=B.status==="available"}let V=O4.safeParse(I.config.effort),X=I.modelCapabilities?.promptCaching?.(b.id,I.model),R=qg(I.body,I.model,L,Z,W,{autoEffortMapping:I.config.auto_effort_mapping,conversationId:C.requestConversationId,nativeSystemPromptEnabled:m,resolvedReasoningReplays:C.replayState.replays,promptCaching:{mode:I.config.kiro_prompt_cache_mode,supported:X?.supportsPromptCaching===!0,...X?.maximumCacheCheckpointsPerRequest!==void 0?{maximumCheckpoints:X.maximumCacheCheckpointsPerRequest}:{},...X?.minimumTokensPerCacheCheckpoint!==void 0?{minimumTokens:X.minimumTokensPerCacheCheckpoint}:{}},...V.success?{effort:V.data}:{}});if(C.replayState.portableRuntimeProtocol!==void 0&&R.runtimeProtocol!==C.replayState.portableRuntimeProtocol)throw new KI("Reasoning replay request does not match the authenticated upstream operation","reasoning_replay_context_mismatch");if(I.onProjection?.(R.diagnostics),R.diagnostics.projection.legacyPrefixMessages!==void 0)y("info","reasoning_replay_projection_compatibility",{protocol:I.body.protocol,model:I.model,prefix_message_count:R.diagnostics.projection.legacyPrefixMessages});if(!cY(I,C))return Tb(I,C,"dispatch-guard"),{kind:"result",leaseTransferred:!1,result:{kind:"response",response:HN(502,"Upstream inference dispatch budget was exhausted","upstream_dispatch_budget_exhausted")}};let h=C.sdkDispatches+1,H=a(R.conversationId),d=a(b.id);y("debug","request_projection_completed",{request_id:I.requestId,attempt:h,model:I.model,conversation_hash:H,projection_mode:R.diagnostics.projection.projectionMode,instruction_channel:R.diagnostics.projection.instructionChannel,input_message_count:R.diagnostics.projection.inputMessageCount,output_message_count:R.diagnostics.projection.outputMessageCount,prefix_instruction_count:R.diagnostics.projection.prefixInstructionCount,trailing_instruction_count:R.diagnostics.projection.trailingInstructionCount,prefix_action:R.diagnostics.projection.prefixAction,suffix_action:R.diagnostics.projection.suffixAction}),y("debug","request_history_built",{request_id:I.requestId,attempt:h,model:I.model,conversation_hash:H,history_message_count:R.diagnostics.history.historyMessageCount,current_role:R.diagnostics.history.currentRole,current_text_chars:R.diagnostics.history.currentTextChars,current_has_text:R.diagnostics.history.currentTextChars>0,current_image_count:R.diagnostics.history.currentImageCount,current_document_count:R.diagnostics.history.currentDocumentCount,current_tool_result_count:R.diagnostics.history.currentToolResultCount,reasoning_replay_count:R.diagnostics.history.reasoningReplayCount});let F=(I.makeClient??yJ)(L,R.region,R.effort,OhI(I,R.region),qC(I.config),b.id,I.config.sdk_http_keep_alive,R.runtimeProtocol),c=R.conversationState.currentMessage.userInputMessage?.modelId??R.effectiveModel,v=R.effort?wL(R.additionalModelRequestFields,Yg(c,R.effort)):R.additionalModelRequestFields,J=Zg(c,I.body.thinking?.enabled===!0,I.body.thinking?.display);if(J!==void 0)v=wL(v,J);let u={conversationState:R.conversationState,...R.profileArn?{profileArn:R.profileArn}:{},...v?{additionalModelRequestFields:v}:{}};if(!mhI(u))throw TypeError("Transformed request is not a valid SDK command input");let g=new qR(u);if(R.runtimeProtocol==="kiro-runtime")KJ(g,{...R.systemPrompt!==void 0?{systemPrompt:R.systemPrompt}:{}});let A=new AbortController,p=(B)=>{if(!A.signal.aborted)A.abort(B)};C.sdkDispatches=h,I.diagnostics?.addSecrets([b.id,b.email,b.accessToken,b.refreshToken,L.access,L.refresh,L.clientSecret,L.profileArn]),I.diagnostics?.dispatch(h),y("info","sdk_dispatch_started",{request_id:I.requestId,attempt:h,model:I.model,effective_model:R.effectiveModel,effort:R.effort,account_hash:d,conversation_hash:H,mode:I.stream?"stream":"non-stream",upstream_operation:R.runtimeProtocol==="kiro-runtime"?"kiro-runtime":"codewhisperer"}),l=!0;let D={abortSignal:AbortSignal.any([G,A.signal]),onResponseHeaders:(B)=>{I.diagnostics?.headers(B.status,B.headers)}},q;try{q=await wG(I.stream?NK(F,g,D):F.send(g,D),G)}catch(B){throw p(B),B}I.diagnostics?.accepted();let k=AhI(I,b.id,R.conversationId,{region:R.region,...R.profileArn!==void 0?{profileArn:R.profileArn}:{},runtimeProtocol:R.runtimeProtocol,...R.diagnostics.projection.legacyPrefixMessages!==void 0?{legacyPrefixMessages:R.diagnostics.projection.legacyPrefixMessages}:{}}),K={options:I,signal:G,state:C,account:b,conversationId:R.conversationId,sdkResponse:q,captureOptions:k,abortUpstream:p,sdkAttempt:h,effort:R.effort,accountHash:d,inputTokenEstimate:()=>aL(R),contextUsageWindow:I.modelCapabilities?.contextUsageWindow?.(b.id,I.model)};return C.streamAttempts+=1,I.stream?await ThI(K,Y):await shI(K)}catch(Q){if(!G.aborted)I.diagnostics?.failure(Q);return{kind:"failed",account:b,caught:Q,upstreamStarted:l}}}function U2(I){return PN(I,Yw(I)?"upstream_protocol_error":"upstream_stream_error")}function B2(I,G){let C=Yw(I)?I.message:G.message;return{kind:"response",response:HN(502,C,G.code)}}function jhI(I,G){let C=I*2**Math.max(0,G-1);return Math.round(C*(1+Math.random()*0.25))}function BhI(I){return I instanceof Error?I:TypeError("SDK stream failed with a non-Error reason",{cause:I})}function ahI(I,G,C,N){if(G.aborted)return Promise.reject(_I(G));return new Promise((Y,Z)=>{let W=()=>{l(),N.onUpstreamReadSettled(),G.removeEventListener("abort",b)},b=()=>{W(),Z(_I(G))},l=N.watchIdle(C,()=>{W(),Z(new tZ(C))});G.addEventListener("abort",b,{once:!0}),I.next().then((Q)=>{W(),Y(Q)},(Q)=>{W(),Z(Q)})})}async function xhI(I,G,C,N){let{iterator:Y,telemetry:Z,prefetched:W}=I,b=async()=>{let Q=_I(G);throw Z.emitTerminal("external_abort"),await fL(I,N,Q),Q},l=async(Q)=>{let L=Q instanceof tZ;return y("warn",L?"sdk_stream_idle_timeout":"sdk_stream_upstream_error",{...Z.auditFields(),...L?Z.stallFields():{},...rY(Q),...L?{idle_timeout_ms:C}:{},phase:"prefetch"}),Z.emitTerminal(L?"idle_timeout":"upstream_error"),await fL(I,N,Q),{kind:"failed",error:Q}};while(!0){let Q;try{Q=await ahI(Y,G,C,Z)}catch(L){if(G.aborted)return b();return l(BhI(L))}if(Q.done){if(G.aborted)return b();return l(new LN)}if(Z.observeCanonicalEvent(Q.value),W.push(Q.value),Q.value.type==="started")return{kind:"accepted"};return l(new kI("Canonical stream omitted its start","upstream_protocol_error"))}}function MhI(I,G,C){return I.config.retry_empty_completion&&!G.emptyCompletionRetried&&G.streamAttempts<I.config.stream_max_attempts&&cY(I,G)&&C.isEmptyCompletion()}function ShI(I,G){let{options:C,state:N,account:Y}=I;return N.emptyCompletionRetried=!0,y("warn","sdk_stream_empty_completion_retry",{...G.auditFields(),attempt:N.streamAttempts,max_attempts:C.config.stream_max_attempts,account_hash:a(Y.id)}),{kind:"empty-completion",account:Y}}function Nw(I,G,C,N){let Y=Ww(I);if(I.config.session_affinity_stall_failover_threshold<=0||Y===void 0)return;let Z=G.lineageStallRow;if(Z!==void 0&&(Z.accountId!==C||Z.conversationId!==N))return;(I.affinityStalls??PL).clear(Y.keyHash)}function nhI(I,G,C,N,Y){let Z=Ww(I);if(I.config.session_affinity_stall_failover_threshold<=0||Z===void 0)return;if(Y.localPersistence){Nw(I,G,C,N);return}let W=I.affinityStalls??PL,b=Z.keyHash,l=Y.provenance;if(l==="normal_complete"){Nw(I,G,C,N);return}if(l==="external_abort"){if(!Y.requestDeadline||!Y.upstreamQuiet)return}else if(l!=="idle_timeout"&&l!=="upstream_error")return;let Q=W.record(b,Date.now(),I.config.session_affinity_stall_window_ms,I.config.session_affinity_max_entries,C);y("warn","session_affinity_stall_recorded",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,affinity_source:Z.source,affinity_hash:a(b),terminal_provenance:l,stall_count:Q.count,stall_span_ms:Math.max(0,Q.lastAt-Q.firstAt),stall_window_ms:I.config.session_affinity_stall_window_ms,stall_threshold:I.config.session_affinity_stall_failover_threshold,failover_armed:Q.count>=I.config.session_affinity_stall_failover_threshold})}function y9(I,G){if(typeof I!=="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(I))return;return G?G.identifier(I):I}function U9(I){let{options:G,state:C,account:N,conversationId:Y}=I,Z=C.pendingMigration;if(Z===void 0)return;C.pendingMigration=void 0;let W={request_id:G.requestId,protocol:G.body.protocol,model:G.model,from_account_hash:a(Z.fromAccountId),to_account_hash:a(N.id),conversation_hash:a(Y),replay_count:Z.replayCount};if(G.affinity&&G.affinityStore){let b;try{b=G.affinityStore.rebindSessionAffinity(G.affinity.keyHash,N.id,Y,Date.now(),G.config.session_affinity_ttl_ms,G.config.session_affinity_max_entries)}catch(l){y("warn","reasoning_replay_migration_commit_failed",{...W,error_type:y9(l instanceof Error?l.name:void 0,G.diagnostics)??(l instanceof Error?"Error":typeof l),error_code:y9(l!==null&&typeof l==="object"&&"code"in l?l.code:void 0,G.diagnostics)});return}C.binding=b,C.affinityQuarantined=!1}y("info","reasoning_replay_migration_committed",W)}async function ThI(I,G){let{options:C,signal:N,account:Y,conversationId:Z,sdkResponse:W,captureOptions:b}=I,l={kind:"stream",sdkResponse:W,maxToolArgumentsBytes:C.config.max_request_body_bytes,validateToolArguments:C.validateToolArguments,model:C.model,conversationId:Z,inputTokenEstimate:I.inputTokenEstimate,contextUsageWindow:I.contextUsageWindow,telemetryContext:{requestId:C.requestId,attempt:I.sdkAttempt,effort:I.effort,accountHash:I.accountHash,diagnostics:C.diagnostics},...b,releaseAccount:G,abortUpstream:I.abortUpstream,onTerminal:(m)=>nhI(C,I.state,Y.id,Z,m)},Q=Mh(l,N),L=await xhI(Q,N,C.config.stream_idle_timeout_ms,I.abortUpstream);if(L.kind==="failed"){if(b.prefetchFableReasoning)return{kind:"result",leaseTransferred:!1,result:B2(L.error,U2(L.error))};return{kind:"stream-failed",account:Y,caught:L.error,failure:U2(L.error)}}return U9(I),{kind:"result",leaseTransferred:!0,result:{...l,prepared:Q}}}async function shI(I){let{options:G,signal:C,state:N,account:Y,conversationId:Z,sdkResponse:W,captureOptions:b}=I,l=xh(G.model,Z,"non-stream",{diagnostics:G.diagnostics,requestId:G.requestId,attempt:I.sdkAttempt,effort:I.effort,accountHash:I.accountHash}),Q,L=Promise.resolve(),m=new AbortController,V=AbortSignal.any([C,m.signal]),X=b.prefetchFableReasoning?l.watchIdle(G.config.stream_idle_timeout_ms,()=>{let R=new tZ(G.config.stream_idle_timeout_ms);m.abort(R),I.abortUpstream(R)}):void 0;try{Q=await rg(W,G.model,Z,V,{...b,inputTokenEstimate:I.inputTokenEstimate,contextUsageWindow:I.contextUsageWindow,maxToolArgumentsBytes:G.config.max_request_body_bytes,textLimit:G.collectedTextLimit,validateToolArguments:G.validateToolArguments,diagnostics:G.diagnostics,onCompletionWitness:(R)=>l.onCompletionWitness(R),onRawEvent:(R)=>l.onRawEvent(R),onToolCallProgress:(R)=>l.onToolCallProgress(R),onCanonicalEvent:(R)=>l.observeCanonicalEvent(R),onIteratorCleanup:(R)=>{L=R}})}catch(R){let h=C.aborted,H=R instanceof tZ;if(!h)y("warn",H?"sdk_stream_idle_timeout":"sdk_stream_upstream_error",{...l.auditFields(),...rY(R,G.diagnostics),error_name:G.diagnostics?.identifier(R instanceof Error?R.name:typeof R)});if(l.emitTerminal(h?"external_abort":H?"idle_timeout":"upstream_error"),I.abortUpstream(R),await FI(()=>L),h)throw _I(C);if(b.prefetchFableReasoning)return{kind:"result",leaseTransferred:!1,result:B2(R,U2(R))};if(!l.collectorSemanticSeen)return{kind:"stream-failed",account:Y,caught:R,failure:U2(R)};throw R}finally{X?.(),l.onUpstreamReadSettled()}if(await FI(()=>L),C.aborted)throw l.emitTerminal("external_abort"),_I(C);if(y("info","sdk_stream_completed",l.auditFields()),l.emitTerminal("normal_complete"),U9(I),b.reasoningReplayDecision.mode===void 0&&MhI(G,N,l))return ShI(I,l);return Nw(G,N,Y.id,Z),{kind:"result",leaseTransferred:!1,result:{kind:"response",response:Response.json(Q,{headers:{"Content-Type":xA,...b.reasoningReplayDecision.mode==="conflict-omitted"?{"x-kiro-reasoning-replay-mode":"conflict-omitted"}:{}}})}}}async function ihI(I,G,C,N,Y){let{account:Z,caught:W,failure:b}=Y;if(G.aborted)throw _I(G);I.diagnostics?.failure(W,"upstream_stream"),C.lastStreamFailure=b;let l=vC(B2(W,b));if(b.disposition==="fatal")return l;if(!cY(I,C))return Tb(I,C,"stream-failed"),l;let Q=I.config.stream_max_attempts;if(C.streamAttempts>=Q)return y("warn","sdk_stream_attempts_exhausted",{attempt:C.streamAttempts,max_attempts:Q,error_code:b.code,account_hash:a(Z.id),mode:I.stream?"stream":"non-stream"}),l;let L=new Set(N.eligibleAccountIds);L.delete(Z.id);let m=C.replayLocked?0:z9(I,N.accounts,L),V=!C.streamRetriedAccountIds.has(Z.id)||m===0;if(C.streamRetriedAccountIds.add(Z.id),!V)C.requestExcludedAccountIds.add(Z.id),j2(C);return y("warn","sdk_stream_attempt_retry",{attempt:C.streamAttempts,max_attempts:Q,error_code:b.code,same_account:V,account_hash:a(Z.id),mode:I.stream?"stream":"non-stream"}),I.diagnostics?.phase("retry_backoff"),await MN(jhI(I.config.rate_limit_retry_delay_ms,C.streamAttempts),G),ZZ}function PhI(I,G,C,N){if(G.migrationFallbackSpent)return"fallback_spent";let Y=C.accounts.find((Z)=>Z.id===N);if(Y===void 0)return"origin_missing";if(!HC(Y,Date.now(),_0(I)))return"origin_unselectable";if(!C.eligibleAccountIds.has(N)||G.requestExcludedAccountIds.has(N)||G.modelRejectedAccountIds.has(N))return"origin_ineligible";if(G.quarantinedAccountIds.has(N))return"origin_quarantined";if(!cY(I,G))return"dispatch_budget";return}function fhI(I,G,C,N,Y){G.pendingMigration=void 0;let Z={kind:"response",response:HN(400,"Kiro rejected the request after its signed reasoning history was migrated to another account, and the original account is unavailable","reasoning_replay_migration_rejected")},W=PhI(I,G,C,N.fromAccountId);if(y("warn","reasoning_replay_migration_rejected",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,from_account_hash:a(N.fromAccountId),to_account_hash:a(N.toAccountId),replay_count:N.replayCount,upstream_status:Y.status,upstream_code:Y.reason,fallback:W===void 0?"origin":"none",fallback_blocked_reason:W}),W!==void 0)return vC(Z);return G.migrationFallbackSpent=!0,G.migrationFallback={accountId:N.fromAccountId,...N.fromConversationId!==void 0?{conversationId:N.fromConversationId}:{},terminal:Z},G.preferredAccountId=N.fromAccountId,G.requestAccountId=N.fromAccountId,G.requestConversationId=N.fromConversationId,ZZ}async function $hI(I,G,C,N,Y){let{account:Z,caught:W,upstreamStarted:b}=Y;if(G.aborted)throw _I(G);if(!b){if(W instanceof ZI||W instanceof KI)throw W;if(u9(W))return k9(I,G,C,Z,W);if(C.replayLocked)return vC(Zw());throw W}if(Yw(W)){let V=PN(W,"upstream_protocol_error");if(V.disposition==="retryable"&&cY(I,C)&&C.retryCount<I.config.rate_limit_max_retries)return C.retryCount+=1,y("warn","non_stream_failure_retry",{account_hash:a(Z.id),error_code:V.code,retry_count:C.retryCount}),I.diagnostics?.phase("retry_backoff"),await MN(I.config.rate_limit_retry_delay_ms*2**(C.retryCount-1),G),ZZ;if(V.disposition==="retryable"&&!cY(I,C))Tb(I,C,"non-stream-failed");return vC({kind:"response",response:HN(502,W.message,W.code)})}let l=Xb(W),Q=iJ(l.status),L=Q?(C.serverErrors.get(Z.id)??0)+1:0;if(Q)C.serverErrors.set(Z.id,L);let m=PJ(l,{accountId:Z.id,accountCount:Math.max(1,z9(I,N.accounts,N.eligibleAccountIds)),retryCount:C.retryCount,maxRetries:I.config.rate_limit_max_retries,serverErrorCount:L,retryDelayMs:I.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:C.forcedRefreshAccountIds});switch(m.action){case"refresh-then-retry":if(!cY(I,C))return Tb(I,C,"refresh-then-retry"),vC({kind:"response",response:HN(m.status,l.message,l.code)});C.forcedRefreshAccountIds.add(m.forcedRefreshAccountId);try{I.diagnostics?.phase("token_refresh"),await wG(I.tokenRefresher.forceRefresh(Z,G),G)}catch(V){if(G.aborted)throw _I(G);if(!u9(V))throw V;return k9(I,G,C,Z,V,"forced")}return ZZ;case"retry":if(!cY(I,C))return Tb(I,C,"retry"),vC({kind:"response",response:HN(m.status??502,l.message,l.code)});return C.retryCount+=1,I.diagnostics?.phase("retry_backoff"),await MN(m.retryAfterMs??0,G),ZZ;case"switch":{let V=l.status===401||l.status===403&&JN(l.message);if(V)C.lastAuthenticationFailure=l;if(OL(m))C.lastQuotaFailure=l;if(V&&C.replayLocked)I.accountManager.markUnhealthy(Z,AN(l.message));else if(l.reason==="TEMPORARILY_SUSPENDED")I.accountManager.markUnhealthy(Z,`InvalidTokenException: Account Suspended: ${l.message}`);else if(OL(m))J9(I,Z);else I.accountManager.markRateLimited(Z,Date.now()+(m.retryAfterMs??I.config.rate_limit_retry_delay_ms));if(!cY(I,C))return Tb(I,C,"switch"),vC({kind:"response",response:HN(m.status??502,l.message,m.code??l.code)});if(C.replayLocked){if(l.status===429){if(C.retryCount+=1,C.retryCount>=I.config.rate_limit_max_retries){let X=m.retryAfterMs??I.config.rate_limit_retry_delay_ms;return vC($N(429,"The account bound to signed reasoning replay remains rate-limited","reasoning_replay_account_rate_limited",X))}}return ZZ}return C.requestExcludedAccountIds.add(Z.id),j2(C),ZZ}case"fail":{let V=C.pendingMigration;if(V!==void 0&&V.toAccountId===Z.id&&HhI(l))return fhI(I,C,N,V,l);if(E9(l))return vC({kind:"response",response:s(400,l.message,"invalid_request_error","invalid_reasoning_signature")});if(OL(m))J9(I,Z);if(l.reason==="TEMPORARILY_SUSPENDED")I.accountManager.markUnhealthy(Z,`InvalidTokenException: Account Suspended: ${l.message}`);return vC({kind:"response",response:HN(m.terminalStatus??m.status??500,l.message,m.code??l.code)})}}}async function thI(I,G){let C=KhI(I);await yhI(I,G,C);while(!0){if(G.aborted)throw _I(G);if(C.iterations+=1,C.iterations>I.config.max_request_iterations)return EhI(I,C);let N=()=>UL(()=>{let m=performance.now(),V=DhI(I,C);return y("info","account_selection_completed",{request_id:I.requestId,duration_ms:Math.max(0,Math.round(performance.now()-m)),outcome:V.kind,replay_locked:C.replayLocked}),V.kind==="capacity-wait"?{kind:"wait",accountIds:V.accountIds}:{kind:"ready",value:V,...V.kind==="selected"?{accountId:V.selection.selected.id}:{}}},G,I.config.account_inference_concurrency),Y=await(I.diagnostics?.waitForQueue("capacity",N,(m)=>m.lease!==void 0)??N()),Z=Y.value;if(Z.kind==="result")return Z.result;if(Z.kind==="wait"){await MN(Z.waitMs+1,G);continue}let{selection:W}=Z,b=Y.lease;if(!b)throw TypeError("Selected account has no capacity reservation");let l=()=>b,Q=await(I.diagnostics?.waitForQueue("account",l)??l()),L=!0;try{if(G.aborted)throw _I(G);if(qhI(I,C,W.selected)==="reselect")continue;let m=await UhI(I,G,C,W.selected,Q);if(m.kind==="result")return L=!m.leaseTransferred,m.result;if(m.kind==="model-unavailable"){if(C.replayLocked)return $N(503,`Model ${I.model} is unavailable on the account bound to signed reasoning replay`,"reasoning_replay_model_unavailable");C.modelRejectedAccountIds.add(m.account.id),j2(C);continue}if(m.kind==="empty-completion")continue;let V=m.kind==="stream-failed"?await ihI(I,G,C,W,m):await $hI(I,G,C,W,m);if(V.kind==="return")return V.result}finally{if(L)Q()}}}async function sb(I){let G=I.requestId??RY(),C=I.diagnostics??new xZ(G,I.config.api_keys),N={...I,requestId:G,diagnostics:C},Y=BJ(N.deadlineSignal,N.config.request_timeout_ms),Z,W,b=!1;try{let l=N.affinity?.keyHash??N.lineage?.lookupKeyHash;if(l!==void 0)Z=await C.waitForQueue("session",()=>cL(l,Y.signal));C.phase("request_validation");let Q=D2(I.body.tools.map((R)=>({name:R.wireName,schema:R.inputSchema,path:R.path,publicType:R.publicType})),I.body.toolChoice!=="none",I.unexpectedToolCallFailure),L=await thI({...N,validateToolArguments:Q},Y.signal);if(L.kind==="response")return await C.response(L.response);W=L.releaseAccount;let m=W,V=Z,X;try{X=(N.createStreamResponse??CK)(L,Y.signal,N.config.stream_idle_timeout_ms,(R)=>{Y.dispose();let h=()=>{m(),V?.(),C.cleanup(),WG(()=>N.onCleanup?.())};if(R)R.then(h,h);else h()})}catch(R){throw L.prepared.telemetry.emitTerminal("external_abort"),await fL(L.prepared,L.abortUpstream,R),R}return W=void 0,Z=void 0,b=!0,await C.response(X)}catch(l){if(l instanceof ZI)return y("warn","request_transform_rejected",{request_id:G,stage:"request_transform",protocol:N.body.protocol,model:N.model,projection_mode:N.body.projectionMode,code:l.code,param:l.param}),s(400,l.message,"invalid_request_error",l.code,l.param);if(l instanceof KI)return s(l.retryable?503:400,l.message,l.retryable?"service_unavailable":"invalid_request_error",l.code);if(Y.signal.aborted){C.cancel(Y.signal.reason instanceof Error&&Y.signal.reason.name==="TimeoutError"?"request_deadline":"external_abort");let L=["client_disconnect","consumer_cancel"].includes(C.snapshot().cancel_source??"");return await C.response(s(L?499:504,L?"Client closed request":"Request deadline exceeded",L?"request_aborted":"timeout_error",L?"client_disconnected":"request_timeout"))}let Q=Xb(l);if(Q.status!==void 0)return C.failure(l),await C.response(s(Q.status>=400?Q.status:502,Q.message,"upstream_error",Q.code));return y("error","pipeline_internal_error",{request_id:G,error_type:C.identifier(l instanceof Error?l.name:typeof l),error_code:C.identifier(Q.code),error_message_hash:a(Q.message)}),MZ(G)}finally{if(!b)W?.(),Z?.(),Y.dispose(),C.cleanup(),WG(()=>N.onCleanup?.())}}function WZ(I,G,C){return{id:I.id,object:"chat.completion.chunk",created:I.created,model:I.model,choices:[{index:0,delta:G,finish_reason:C}]}}function _hI(I,G,C){switch(I.type){case"text_delta":return[JSON.stringify(WZ(G,{content:I.text},null))];case"reasoning_delta":return[JSON.stringify(WZ(G,{reasoning_content:I.text},null))];case"reasoning_signature":return[JSON.stringify(WZ(G,{reasoning_signature:I.signature},null))];case"reasoning_redacted":return[JSON.stringify(WZ(G,{reasoning_redacted_content:I.data},null))];case"reasoning_encrypted":return[JSON.stringify(WZ(G,{reasoning_encrypted_content:I.encryptedContent},null))];case"tool_call_delta":return[JSON.stringify(WZ(G,{tool_calls:[{index:I.index,...I.id!==void 0?{id:I.id,type:"function"}:{},function:{...I.name!==void 0?{name:I.name}:{},arguments:I.arguments}}]},null))];case"completed":{let N=JSON.stringify({...WZ(G,{},I.finishReason),...iY(I.codeReferences)});if(!C)return[N];let Y={id:G.id,object:"chat.completion.chunk",created:G.created,model:G.model,choices:[],usage:{prompt_tokens:I.usage.inputTokens,completion_tokens:I.usage.outputTokens,total_tokens:I.usage.totalTokens}};return[N,JSON.stringify(Y)]}}}function j9(I){let G=I.reasoning;return Response.json({id:I.conversationId,object:"chat.completion",created:I.createdAt,model:I.model,choices:[{index:0,message:{role:"assistant",content:I.text.length===0&&I.toolCalls.length>0?null:I.text,...G?.text?{reasoning_content:G.text}:{},...G?.signature?{reasoning_signature:G.signature}:{},...G?.redactedContent?{reasoning_redacted_content:G.redactedContent}:{},...G?.encryptedContent?{reasoning_encrypted_content:G.encryptedContent}:{},...I.toolCalls.length>0?{tool_calls:I.toolCalls.map((C)=>({id:C.id,type:"function",function:{name:C.name,arguments:C.input}}))}:{}},finish_reason:I.finishReason}],usage:{prompt_tokens:I.usage.inputTokens,completion_tokens:I.usage.outputTokens,total_tokens:I.usage.totalTokens},...iY(I.codeReferences)})}function B9(I,G,C,N){let Y=N.includeUsage===!0,W=(I.body??new ReadableStream({start:(k)=>k.close()})).getReader(),b=new TextDecoder,l=new TextEncoder,Q=[],L=new Map,m="",V,X=!1,R,h,H=!1,d=(k)=>{Q.push(l.encode(`data: ${k}
|
|
375
|
+
`),X,R,h,H,d=()=>{h?.(),h=void 0},O=(J)=>{if(X!==void 0)return!1;return X=J,!0},F=()=>{b.removeEventListener("abort",v)},c=(J,u,g=!1)=>{if(!O(J))return R??Promise.resolve();let A=()=>{},p=new Promise((q)=>{A=q});R=p;let D={provenance:eg[J],requestDeadline:g,upstreamQuiet:l.upstreamWentQuiet(),localPersistence:u instanceof J0};if(WG(()=>l.emitTerminal(eg[J])),WG(()=>I.onTerminal?.(D)),WG(F,d,()=>{if(J==="normal-complete")H?.close();else if(J!=="consumer-cancel")H?.error(u)},()=>{if(J!=="normal-complete")I.abortUpstream?.(u)},()=>N(p)),J!=="normal-complete")WG(()=>{if(!W.signal.aborted)W.abort(u)});return GK(Y).then(A,A),R},v=()=>{let J=b.reason instanceof Error&&b.reason.name==="TimeoutError";I.telemetryContext?.diagnostics?.cancel(J?"request_deadline":"external_abort"),c("external-abort",_I(b),J)};return new Response(new ReadableStream({start(J){if(H=J,b.addEventListener("abort",v,{once:!0}),b.aborted){v();return}for(let u of Q)J.enqueue(V(u))},async pull(J){if(X!==void 0)return;h=l.watchIdle(C,()=>{let u=new tZ(C);I.telemetryContext?.diagnostics?.failure(u,"upstream_stream"),y("warn","sdk_stream_idle_timeout",{...l.auditFields(),...l.stallFields(),...rY(u,I.telemetryContext?.diagnostics),idle_timeout_ms:C}),c("idle-timeout",u)});try{let u=L??Z.next();L=void 0;let g=await u;if(l.onUpstreamReadSettled(),X!==void 0)return;if(d(),g.done){y("info","sdk_stream_completed",l.auditFields()),await c("normal-complete");return}l.observeCanonicalEvent(g.value),J.enqueue(V(g.value))}catch(u){if(l.onUpstreamReadSettled(),X!==void 0)return;let g=u instanceof Error?u:TypeError("SDK stream failed with a non-Error reason",{cause:u});y("warn","sdk_stream_upstream_error",{...l.auditFields(),...rY(g,I.telemetryContext?.diagnostics)}),I.telemetryContext?.diagnostics?.failure(g,"upstream_stream"),await c("upstream-error",g)}},cancel(J){if(H=void 0,l.completedSeen)return c("normal-complete");if(!l.completionWitnessed)I.telemetryContext?.diagnostics?.cancel("consumer_cancel");return c("consumer-cancel",J)}}),{headers:{"Content-Type":MA,...I.reasoningReplayDecision?.mode==="conflict-omitted"?{"x-kiro-reasoning-replay-mode":"conflict-omitted"}:{}}})}async function NK(I,G,C){let N=Promise.withResolvers(),Y=Promise.resolve().then(()=>I.send(G,{...C,onResponseHeaders(W){C.onResponseHeaders?.(W);let b=Object.entries(W.headers).find(([l])=>l.toLowerCase()==="content-type")?.[1];if(W.status>=200&&W.status<300&&b?.split(";")[0]?.trim().toLowerCase()==="application/vnd.amazon.eventstream")N.resolve(W);else if(W.status>=200&&W.status<300)N.reject(new kI("Upstream did not return an AWS EventStream response","invalid_upstream_response"))}}));Y.catch(()=>{return});let Z=await Promise.race([Y.then((W)=>({kind:"decoded",response:W})),N.promise.then((W)=>({kind:"accepted",metadata:W}))]);if(Z.kind==="decoded")return Z.response;return{generateAssistantResponseResponse:{async*[Symbol.asyncIterator](){let b=(await Y).generateAssistantResponseResponse;if(!b)throw new sL;yield*b}}}}var O9=NI(PH(),1),F9=NI(Z9(),1),v9=NI(c9(),1);function D2(I,G=!0,C){let N=new Map,Y=new Map;for(let[b,l]of I.entries())try{if(l.schema.$async===!0||N.has(l.name))throw Error("invalid schema");if(l.publicType==="custom"){N.set(l.name,()=>!0);continue}let Q=typeof l.schema.$schema==="string"?l.schema.$schema:"",L=Q.includes("2020-12")?"2020":Q.includes("2019-09")?"2019":"7",m=Y.get(L);if(!m){let V={strict:!1,allErrors:!1,validateFormats:!1,ownProperties:!0,coerceTypes:!1,useDefaults:!1,removeAdditional:!1,addUsedSchema:!1};m=L==="2020"?new v9.default(V):L==="2019"?new F9.default(V):new O9.default(V),Y.set(L,m)}N.set(l.name,m.compile(l.schema))}catch{throw new ZI("Tool schema cannot be validated; external references and asynchronous schemas are not supported","invalid_tool_schema",l.path??`tools[${b}].parameters`)}let Z=(b)=>{if(C!==void 0)throw new kI(C.message,C.code);if(!G)throw new kI("Upstream called a tool despite tool_choice=none","upstream_tool_choice_violation");if(!N.has(b))throw new kI("Upstream returned an undeclared tool call","unknown_upstream_tool")};return Object.assign((b,l)=>{if(Z(b),!N.get(b)(l))throw new kI("Upstream tool arguments do not match the declared schema","upstream_tool_schema_violation")},{assertName:Z})}function LhI(I){return I.messages.some((G)=>G.role==="system"||G.role==="developer")}function q2(I){return typeof I==="object"&&I!==null&&!Array.isArray(I)}function mhI(I){if(!q2(I))return!1;let G=I.conversationState;return q2(G)&&typeof G.conversationId==="string"&&q2(G.currentMessage)&&typeof G.chatTriggerType==="string"}function VhI(I,G){return{think:G.endsWith("-thinking")||I.thinking?.enabled===!0,budget:I.thinking?.budgetTokens??20000}}function HN(I,G,C){return s(I,G,"upstream_error",C)}function Yw(I){return I instanceof LN||I instanceof kI||I instanceof OC}function u9(I){return I instanceof VG||I instanceof Rb}function p9(I){let G=I instanceof VG?I.code:void 0;return G?`${G}: ${I.message}`:I.message}var XhI=/invalid\s+`?signature`?\s+in\s+`?thinking`?\s+block/i,RhI="THINKING_SIGNATURE_INVALID";function E9(I){if(I.reason===RhI)return!0;return I.status===400&&XhI.test(I.message)}var hhI="REQUEST_BODY_INVALID";function HhI(I){return(I.status===void 0||I.status===400)&&(I.reason===hhI||E9(I))}function z9(I,G,C){let N=I.accountManager.countSelectableAccounts?.(C);if(N!==void 0)return N;let Y=Date.now();return G.filter((Z)=>C.has(Z.id)&&HC(Z,Y)).length}function whI(I,G,C,N){let Y=I.filter((Z)=>G.has(Z.id)&&Z.isHealthy&&!nI(Z,N)&&Z.rateLimitResetTime>C).map((Z)=>Z.rateLimitResetTime-C);return Y.length===0?void 0:Math.min(...Y)}function dhI(){return{kind:"response",response:s(503,"Token refresh failed for every usable Kiro account","service_unavailable","upstream_token_refresh_failed")}}function J9(I,G){let C=Date.now()+I.config.quota_recheck_interval_ms;if(I.accountManager.markQuotaExhausted)I.accountManager.markQuotaExhausted(G,C);else I.accountManager.markRateLimited(G,C);y("warn","quota_exhausted_account_persisted",{account_hash:a(G.id),recheck_after:C})}function chI(I){let G=I.modelCapabilities?.isKnownModel(I.model)??!1;return{kind:"response",response:s(G?503:400,G?`Model ${I.model} is not available to any currently usable Kiro account`:`Model ${I.model} is not supported by Kiro`,G?"service_unavailable":"invalid_request_error",G?"model_unavailable_for_accounts":"unsupported_model","model")}}function OhI(I,G){if(I.config.test_upstream_endpoint)return I.config.test_upstream_endpoint;return I.config.runtime_endpoint_mode==="kiro-runtime"?DI.RUNTIME_ENDPOINT.replace("{{region}}",G):void 0}function A9(I,G){let C=new Map(I.tools.map((N)=>[N.wireName,N]));return(N)=>{let Y={text:N.text,toolCalls:N.toolCalls.map((Z)=>{let W=C.get(Z.name);if(!W)return Z;if(W.publicType!=="custom")return{...Z,name:W.name};let b=Z.input;try{let l=JSON.parse(Z.input);if(q2(l)&&Object.keys(l).length===1&&typeof l.input==="string")b=l.input}catch{}return{...Z,name:W.name,input:b}})};return G?Yh(Y,G):jC(Y)}}function g9(I,G){if(!I.clientNormalization)return{};let C=I.body.messages[G];if(!C||C.role!=="assistant")throw new KI("Reasoning replay does not reference assistant output","invalid_reasoning_replay");return{clientNormalization:I.clientNormalization,normalizedOutputFingerprint:Yh({text:CC(C.content),toolCalls:C.toolCalls.map((N)=>({id:N.id,name:N.name,input:JSON.stringify(N.input)}))},I.clientNormalization)}}function $N(I,G,C,N){let Y=new Headers({"Content-Type":"application/json"});if(N!==void 0)Y.set("Retry-After",String(Math.max(1,Math.ceil(N/1000))));return{kind:"response",response:new Response(JSON.stringify({error:{message:G,type:I===429?"rate_limit_error":I===402?"insufficient_quota":I===401||I===403?"authentication_error":"service_unavailable",code:C,...N!==void 0?{retry_after_ms:N}:{}}}),{status:I,headers:Y})}}function Zw(){return $N(503,"The account bound to signed reasoning replay is currently unavailable","reasoning_replay_account_unavailable")}function FhI(I,G,C,N){let Y=C.find((b)=>b.id===G.boundAccountId);if(!Y)return{kind:"result",result:Zw()};let Z=Date.now(),W=I.config.request_timeout_ms-(Z-G.startedAt);if(nI(Y,_0(I))){let b=Y.rateLimitResetTime>Z?Y.rateLimitResetTime-Z:void 0;return{kind:"result",result:$N(402,"The account bound to signed reasoning replay has exhausted its included quota","reasoning_replay_account_quota_exhausted",b)}}if(Y.isHealthy&&Y.rateLimitResetTime>Z){let b=Y.rateLimitResetTime-Z;if(b<=W)return y("info","reasoning_replay_rate_limit_wait",{wait_ms:b,remaining_ms:W}),{kind:"wait",waitMs:b};return{kind:"result",result:$N(429,"The account bound to signed reasoning replay is temporarily rate-limited","reasoning_replay_account_rate_limited",b)}}if(!Y.isHealthy&&xG(Y.unhealthyReason))return{kind:"result",result:$N(403,"The account bound to signed reasoning replay requires re-authentication","reasoning_replay_account_reauthentication_required")};if(!N.has(Y.id))return{kind:"result",result:$N(503,`Model ${I.model} is unavailable on the account bound to signed reasoning replay`,"reasoning_replay_model_unavailable")};return{kind:"result",result:$N(503,"The account bound to signed reasoning replay is unhealthy","reasoning_replay_account_unhealthy")}}function vhI(I,G,C){if(I.config.reasoning_replay_account_failover!=="verified")return;let N=G.provenance;if(G.portable===!0&&N){if(N.protocol!==I.body.protocol||!N.profileArn||N.upstreamOperation!=="GenerateAssistantResponse")return;let l=`${N.protocol}:${I.model}:${N.region}:${N.runtimeProtocol}:profile:${G.replay.content.kind}`,Q=uhI.has(l);return K9.has(l)||Q?{region:N.region,runtimeProtocol:N.runtimeProtocol,profileRequired:!0,...Q?{profileArn:N.profileArn}:{}}:void 0}if(G.legacyPortable!==!0&&G.databaseLegacy!==!0||I.config.reasoning_replay_legacy_account_failover!=="verified-current-cell"||I.body.projectionMode!=="v3-auto"&&I.body.projectionMode!=="native-context-safe"&&I.body.projectionMode!=="legacy-user-prefix")return;let Y=C?.get(G.accountId);if(!Y?.profileArn)return;let Z=W0(Y.profileArn)??Y.region,W=I.body.projectionMode==="legacy-user-prefix"?"codewhisperer":"kiro-runtime",b=`${I.body.protocol}:${I.model}:${Z}:${W}:profile:${G.replay.content.kind}`;return K9.has(b)?{region:Z,runtimeProtocol:W,profileRequired:!0,legacyCurrentCell:!0}:void 0}var K9=new Set(["responses:gpt-5.6-sol:us-east-1:kiro-runtime:profile:reasoning_text","responses:gpt-5.6-sol:us-east-1:codewhisperer:profile:reasoning_text","anthropic-messages:claude-sonnet-5:us-east-1:kiro-runtime:profile:reasoning_text","anthropic-messages:claude-opus-5:us-east-1:kiro-runtime:profile:reasoning_text","anthropic-messages:claude-opus-5-5:us-east-1:kiro-runtime:profile:reasoning_text"]),uhI=new Set(["anthropic-messages:claude-fable-5-1:us-east-1:kiro-runtime:profile:reasoning_text"]);function JhI(I,G){if(I.body.reasoningReplays.length===0)return{replays:[],portableCount:0,legacyPortableCount:0};let C,N,Y=G?.accountId,Z=G?.conversationId,W=0,b=0,l,Q,L,m,V=I.config.reasoning_replay_legacy_account_failover==="verified-current-cell"?new Map(I.accountManager.reconcileFromDb().map((H)=>[H.id,H])):void 0,X=[],R=I.body.reasoningReplays.flatMap((H,d)=>{if(H.lookup.kind!=="responses-token"&&H.lookup.kind!=="anthropic-token")return[];if(!I.tenantId)throw new KI("Reasoning replay requires an authenticated tenant context","reasoning_replay_context_required");let O=H.lookup.kind==="responses-token"?H.lookup.encryptedContent:H.lookup.signature;return[{index:d,token:O,context:{tenantId:I.tenantId,model:I.body.model,outputFingerprint:H.outputFingerprint,...g9(I,H.insertBeforeMessage),...H.compatibleOutputFingerprints!==void 0?{compatibleOutputFingerprints:H.compatibleOutputFingerprints}:{},...C!==void 0?{accountId:C}:{},...N!==void 0?{conversationId:N}:{}},insertBeforeMessage:H.insertBeforeMessage}]}),h=new Map;if(R.length>0){let H=I.reasoningReplayStore;if(!H)throw new KI("Reasoning replay storage is unavailable","reasoning_replay_store_unavailable",!0);let d=H.resolveResponsesBatch?H.resolveResponsesBatch(R):R.map((O)=>H.resolveResponses(O.token,O.context,O.insertBeforeMessage));for(let[O,F]of R.entries()){let c=d[O];if(c)h.set(F.index,c)}}for(let[H,d]of I.body.reasoningReplays.entries()){if(d.lookup.kind==="anthropic-direct"){X.push({insertBeforeMessage:d.insertBeforeMessage,content:d.lookup.content});continue}if(!I.tenantId)throw new KI("Reasoning replay requires an authenticated tenant context","reasoning_replay_context_required");let O=I.reasoningReplayStore;if(!O)throw new KI("Reasoning replay storage is unavailable","reasoning_replay_store_unavailable",!0);let F={tenantId:I.tenantId,model:I.body.model,outputFingerprint:d.outputFingerprint,...g9(I,d.insertBeforeMessage),...d.compatibleOutputFingerprints!==void 0?{compatibleOutputFingerprints:d.compatibleOutputFingerprints}:{},...C!==void 0?{accountId:C}:{},...N!==void 0?{conversationId:N}:{}},c=d.lookup.kind==="chat-hash"?O.resolveChat(d.lookup.reasoningText,F,d.insertBeforeMessage):h.get(H);if(!c)throw new KI("Reasoning replay batch resolution was incomplete","reasoning_replay_not_found");let v=vhI(I,c,V);if(v!==void 0){if(l!==void 0&&l!==v.region||Q!==void 0&&Q!==v.runtimeProtocol||m!==void 0&&v.profileArn!==void 0&&m!==v.profileArn)throw new KI("Portable reasoning replay items resolve to different verified mint cells","reasoning_replay_context_mismatch");if(l=v.region,Q=v.runtimeProtocol,L=v.profileRequired,m??=v.profileArn,W+=1,v.legacyCurrentCell)b+=1;Y??=c.accountId,Z??=c.conversationId}else{if(C!==void 0&&C!==c.accountId||N!==void 0&&N!==c.conversationId)throw new KI("Reasoning replay items resolve to different accounts or conversations","reasoning_replay_context_mismatch");C=c.accountId,N=c.conversationId,Y=c.accountId,Z=c.conversationId}let J=c.replay.instructionProjection===void 0&&c.portable===!0&&c.provenance?.protocol==="anthropic-messages"&&c.provenance.runtimeProtocol==="kiro-runtime"&&I.body.protocol==="anthropic-messages"&&I.model==="claude-fable-5-1"&&I.body.projectionMode==="v3-auto"&&d.insertBeforeMessage>0;X.push(J?{...c.replay,instructionProjection:{version:1,legacyPrefixMessages:d.insertBeforeMessage},legacyProjectionUnversioned:!0}:c.replay)}if(b>0)y("warn","reasoning_replay_legacy_failover_admitted",{protocol:I.body.protocol,model:I.model,region:l,replay_count:b});return{...C!==void 0?{accountId:C}:{},...N!==void 0?{conversationId:N}:{},...Y!==void 0?{preferredAccountId:Y}:{},...Z!==void 0?{preferredConversationId:Z}:{},...l!==void 0?{portableRegion:l}:{},...Q!==void 0?{portableRuntimeProtocol:Q}:{},...L?{portableProfileRequired:L}:{},...m!==void 0?{portableProfileArn:m}:{},portableCount:W,legacyPortableCount:b,replays:X}}function AhI(I,G,C,N){let Y=I.body,Z=Y.includeEncryptedReasoning===!0||Y.protocol==="responses"&&Y.store!==!1||Y.protocol==="anthropic-messages",W=Y.protocol==="anthropic-messages",b=W&&Y.thinking?.enabled===!0&&cC(Y.model),l=W&&Y.thinking?.enabled===!0&&Y.thinking.display!=="summarized"&&nY(Y.model),Q={},L=I.lineage&&I.affinityStore?(m)=>{if(m.text.length===0&&m.toolCalls.length===0)return;let V=Nh(Y,m),X=I.lineage?.outputKeyHash(V);if(X===void 0)return;I.affinityStore?.recordOutputLineage(X,G,C,Date.now(),I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries),y("info","output_lineage_recorded",{protocol:Y.protocol,lineage_source:I.lineage?.source,lineage_hash:a(X),account_hash:a(G),conversation_hash:a(C)})}:void 0;if(!I.reasoningReplayStore||!I.tenantId)return{emitEncryptedReasoning:Z,emitAnthropicReasoningMetadata:W,bufferLateGptReasoning:b,prefetchFableReasoning:l,reasoningReplayDecision:Q,fingerprintOutput:A9(Y,I.clientNormalization),...L?{captureOutput:L}:{}};return{captureReasoning:(m,V)=>I.reasoningReplayStore?.store(m,{tenantId:I.tenantId,model:Y.model,accountId:G,conversationId:C,outputFingerprint:V,...I.clientNormalization?{clientNormalization:I.clientNormalization}:{},protocol:Y.protocol,region:N.region,...N.profileArn!==void 0?{profileArn:N.profileArn}:{},runtimeProtocol:N.runtimeProtocol,upstreamOperation:"GenerateAssistantResponse",instructionProjection:{version:1,...N.legacyPrefixMessages!==void 0?{legacyPrefixMessages:N.legacyPrefixMessages}:{}}}),emitEncryptedReasoning:Z,emitAnthropicReasoningMetadata:W,bufferLateGptReasoning:b,prefetchFableReasoning:l,reasoningReplayDecision:Q,fingerprintOutput:A9(Y,I.clientNormalization),...L?{captureOutput:L}:{}}}var ZZ={kind:"continue"};function vC(I){return{kind:"return",result:I}}function cY(I,G){return I.maxUpstreamDispatches===void 0||G.sdkDispatches<I.maxUpstreamDispatches}function Tb(I,G,C){y("warn","upstream_dispatch_budget_exhausted",{request_id:I.requestId,dispatches:G.sdkDispatches,max_dispatches:I.maxUpstreamDispatches,outcome:C,mode:I.stream?"stream":"non-stream"})}function Ww(I){if(I.affinity)return I.affinity;if(I.lineage?.lookupKeyHash!==void 0)return{keyHash:I.lineage.lookupKeyHash,source:I.lineage.source};return}function ghI(I,G,C){let N=I.config.session_affinity_stall_failover_threshold;if(N<=0||G===void 0||!I.affinityStore)return;let Y=(I.affinityStalls??PL).peek(G.keyHash,C,I.config.session_affinity_stall_window_ms);return Y!==void 0&&Y.count>=N?Y:void 0}function KhI(I){let G=Date.now(),C=I.affinity&&I.affinityStore?I.affinityStore.getSessionAffinity(I.affinity.keyHash):void 0,N=C===void 0&&I.lineage?.lookupKeyHash!==void 0&&I.affinityStore?I.affinityStore.resolveOutputLineage(I.lineage.lookupKeyHash):void 0,Y=JhI(I,C??N),Z=Y.accountId!==void 0,W=Ww(I),b=Z?void 0:ghI(I,W,G),l=b===void 0?C:void 0,Q=b===void 0?N:void 0,L=l??Q,m=Y.accountId??L?.accountId,V=m??(b===void 0?Y.preferredAccountId:void 0);if(b!==void 0&&W!==void 0)y("warn","session_affinity_stall_failover",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,affinity_source:W.source,affinity_hash:a(W.keyHash),stall_count:b.count,stall_span_ms:Math.max(0,b.lastAt-b.firstAt),stall_threshold:I.config.session_affinity_stall_failover_threshold,quarantined_binding:C!==void 0,quarantined_lineage:C===void 0&&N!==void 0});return{pendingMigration:void 0,migrationFallbackSpent:!1,migrationFallback:void 0,forcedRefreshAccountIds:new Set,serverErrors:new Map,requestExcludedAccountIds:new Set,reportedQuotaExhaustedAccountIds:new Set,refreshNetworkRetriedAccountIds:new Set,modelRejectedAccountIds:new Set,lastAuthenticationFailure:void 0,lastQuotaFailure:void 0,lastRefreshFailure:void 0,retryCount:0,iterations:0,startedAt:G,binding:l,lineageBinding:Q,replayState:Y,replayLocked:Z,affinityQuarantined:b!==void 0,quarantinedAccountIds:b===void 0?new Set:b.accountIds.size>0?new Set(b.accountIds):new Set([(C??N)?.accountId].filter((X)=>X!==void 0)),lineageStallRow:I.affinity===void 0?N:void 0,boundAccountId:m,preferredAccountId:V,requestAccountId:V,requestConversationId:Y.conversationId??L?.conversationId??(b===void 0?Y.preferredConversationId:void 0),streamAttempts:0,sdkDispatches:0,streamRetriedAccountIds:new Set,emptyCompletionRetried:!1,lastStreamFailure:void 0}}function j2(I){I.preferredAccountId=void 0,I.requestAccountId=void 0,I.requestConversationId=void 0}function khI(I,G,C,N){let Y=p9(N),Z=N instanceof VG&&GN(Y),W=N instanceof VG&&N.code==="NETWORK_ERROR";if(G.lastRefreshFailure=N,W&&!G.refreshNetworkRetriedAccountIds.has(C.id))return G.refreshNetworkRetriedAccountIds.add(C.id),y("warn","account_token_refresh_retry",{account_hash:a(C.id),error_code:N.code}),"retry";if(G.replayLocked){if(N instanceof VG)if(Z)I.accountManager.markUnhealthy(C,AN(Y));else I.accountManager.markRateLimited(C,Date.now()+I.config.rate_limit_retry_delay_ms);return y("warn","reasoning_replay_account_refresh_failed",{account_hash:a(C.id),error_type:N.name,error_code:N instanceof VG?N.code:void 0,refresh_token_dead:Z}),"switch"}if(G.requestExcludedAccountIds.add(C.id),N instanceof VG)if(Z)I.accountManager.markUnhealthy(C,AN(Y));else I.accountManager.markRateLimited(C,Date.now()+I.config.rate_limit_retry_delay_ms);return y("warn","account_token_refresh_failed",{account_hash:a(C.id),error_type:N.name,error_code:N instanceof VG?N.code:void 0,refresh_token_dead:Z}),j2(G),"switch"}async function k9(I,G,C,N,Y,Z="initial"){let W=khI(I,C,N,Y);if(C.replayLocked){if(Y instanceof VG&&GN(p9(Y)))return vC($N(403,"The account bound to signed reasoning replay requires re-authentication","reasoning_replay_account_reauthentication_required"));if(Y instanceof Rb)return vC(Zw());if(W!=="retry"||Z==="forced")return vC($N(503,"Token refresh failed for the account bound to signed reasoning replay","reasoning_replay_account_refresh_failed"))}if(W==="retry")await MN(I.config.rate_limit_retry_delay_ms,G);return ZZ}async function yhI(I,G,C){let N=I.quotaRechecker;if(!N)return;let Y=I.accountManager.reconcileFromDb(),Z=Date.now(),W=Y.some((l)=>HC(l,Z)),b=C.replayLocked&&Y.some((l)=>l.id===C.boundAccountId&&nI(l,_0(I)));if(W&&!b){N.recheckDueAccounts(Y,new AbortController().signal,C.boundAccountId).catch((l)=>{y("warn","quota_recheck_background_failed",{error_type:l instanceof Error?l.name:typeof l})});return}await N.recheckDueAccounts(Y,G,C.boundAccountId)}function D9(I){return{kind:"response",response:HN(I.status??403,I.message,I.code??"upstream_authentication_failed")}}function _0(I){return I.accountManager.getOveragePolicy?.()??DW(I.config)}function phI(){return{kind:"response",response:HN(402,"All eligible Kiro accounts are blocked by paid overage; set stop_on_overage to false or raise overage_threshold to keep using them","paid_overage_blocked")}}function q9(I){return{kind:"response",response:HN(402,I?.message??"All eligible Kiro accounts have exhausted their quota",I?.code??"quota_exhausted")}}function EhI(I,G){if(G.lastAuthenticationFailure)return D9(G.lastAuthenticationFailure);if(G.lastQuotaFailure)return q9(G.lastQuotaFailure);return{kind:"response",response:s(500,`Exceeded max iterations (${I.config.max_request_iterations})`,"request_error","max_request_iterations")}}function zhI(I,G,C){let N=G.preferredAccountId;if(G.replayState.portableCount===0||N===void 0)return;if(!C.has(N))return;return VY(N)<I.config.account_inference_concurrency?N:void 0}function DhI(I,G){let C=I.accountManager.reconcileFromDb(),N=C.filter((J)=>!G.modelRejectedAccountIds.has(J.id)&&!G.requestExcludedAccountIds.has(J.id)),Y=_0(I),Z=N.filter((J)=>nI(J,Y)),W=Z.filter((J)=>!G.reportedQuotaExhaustedAccountIds.has(J.id));for(let J of W)G.reportedQuotaExhaustedAccountIds.add(J.id);if(W.length>0)y("info","quota_exhausted_accounts_excluded",{account_count:W.length});let b=N.filter((J)=>!nI(J,Y)).map((J)=>J.id),l=I.modelCapabilities?.eligibleAccountIds(I.model,b),Q=new Set([...l??b].filter((J)=>!G.modelRejectedAccountIds.has(J)&&(G.replayState.portableRegion===void 0||(()=>{let u=C.find((A)=>A.id===J);if(!u)return!1;return(W0(u.profileArn)??u.region)===G.replayState.portableRegion&&(!G.replayState.portableProfileRequired||u.profileArn!==void 0)&&(G.replayState.portableProfileArn===void 0||u.profileArn===G.replayState.portableProfileArn)})()))),L=G.migrationFallback?.accountId,m=Date.now(),V=C.filter((J)=>Q.has(J.id)&&HC(J,m,Y)&&(!G.replayLocked||J.id===G.replayState.accountId)&&(L===void 0||J.id===L)),X=V.filter((J)=>!G.quarantinedAccountIds.has(J.id)),R=!G.replayLocked&&X.length>0?X:V,h=new Set(R.map((J)=>J.id)),H=zhI(I,G,h),d=H===void 0?qL(R,h,Y):new Set([H]);if(d.size>0&&[...d].every((J)=>VY(J)>=I.config.account_inference_concurrency))return{kind:"capacity-wait",accountIds:h};let O=I.accountManager.selectHealthyAccount(G.preferredAccountId,d);if(O&&(G.replayState.accountId===void 0||O.id===G.replayState.accountId))return{kind:"selected",selection:{selected:O,accounts:C,eligibleAccountIds:Q}};if(G.migrationFallback!==void 0)return{kind:"result",result:G.migrationFallback.terminal};if(G.replayLocked)return FhI(I,G,C,Q);if(b.length===0&&G.lastAuthenticationFailure)return{kind:"result",result:D9(G.lastAuthenticationFailure)};if(b.length===0&&G.lastQuotaFailure===void 0&&I.accountManager.blockedByOverageOnly?.(new Set(N.map((J)=>J.id)))===!0)return{kind:"result",result:phI()};if(b.length===0&&(Z.length>0||G.lastQuotaFailure))return{kind:"result",result:q9(G.lastQuotaFailure)};if(b.length===0&&G.lastStreamFailure!==void 0)return{kind:"result",result:B2(void 0,G.lastStreamFailure)};if(b.length===0&&G.lastRefreshFailure!==void 0)return{kind:"result",result:dhI()};if(G.modelRejectedAccountIds.size>0||l!==void 0&&Q.size===0)return{kind:"result",result:chI(I)};let F=Date.now(),c=whI(N,new Set(l??b),F,_0(I)),v=I.config.request_timeout_ms-(F-G.startedAt);if(c!==void 0&&c<=v)return y("info","rate_limit_wait_for_reset",{wait_ms:c,remaining_ms:v}),{kind:"wait",waitMs:c};return{kind:"result",result:{kind:"response",response:s(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")}}}function qhI(I,G,C){let N=Date.now();G.pendingMigration=void 0;let Y=G.replayState.portableCount>0&&G.replayState.preferredAccountId!==void 0&&C.id!==G.replayState.preferredAccountId,Z=Y&&G.binding?.accountId!==C.id,W=Z&&I.affinity!==void 0&&I.affinityStore!==void 0,b=G.binding?.accountId??G.replayState.preferredAccountId;if(Y)G.requestAccountId=C.id,G.requestConversationId=t0();if(Z)G.pendingMigration={fromAccountId:b,fromConversationId:G.binding?.conversationId??G.replayState.preferredConversationId,toAccountId:C.id,toConversationId:G.requestConversationId,replayCount:G.replayState.portableCount,legacyReplayCount:G.replayState.legacyPortableCount};else if(I.affinity&&I.affinityStore)if(!G.binding){let l=G.affinityQuarantined?I.affinityStore.rebindSessionAffinity(I.affinity.keyHash,C.id,t0(),N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries):I.affinityStore.claimSessionAffinity(I.affinity.keyHash,C.id,G.requestConversationId??t0(),N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries);if(G.affinityQuarantined=!1,G.binding=l,G.preferredAccountId=l.accountId,G.requestConversationId=l.conversationId,G.replayLocked&&(l.accountId!==G.replayState.accountId||l.conversationId!==G.replayState.conversationId))throw new KI("Session affinity conflicts with signed reasoning replay","reasoning_replay_context_mismatch");if(l.accountId!==C.id)return"reselect"}else if(G.binding.accountId===C.id&&(!G.replayLocked||G.binding.conversationId===G.replayState.conversationId))G.binding=I.affinityStore.claimSessionAffinity(I.affinity.keyHash,C.id,G.binding.conversationId,N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries),G.requestConversationId=G.binding.conversationId;else G.binding=I.affinityStore.rebindSessionAffinity(I.affinity.keyHash,C.id,G.replayLocked?G.replayState.conversationId:t0(),N,I.config.session_affinity_ttl_ms,I.config.session_affinity_max_entries),G.requestConversationId=G.binding.conversationId;else if(!G.replayLocked&&G.requestAccountId!==C.id)G.requestAccountId=C.id,G.requestConversationId=t0();if(Z)y("info","reasoning_replay_account_migrated",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,from_account_hash:a(b),to_account_hash:a(C.id),replay_count:G.replayState.portableCount,legacy_replay_count:G.replayState.legacyPortableCount,binding:W?"deferred":"none"});return G.preferredAccountId=C.id,y("info","upstream_affinity_selected",{request_id:I.requestId,projection_mode:I.config.protocol_projection_mode,session_affinity_mode:I.config.session_affinity_mode,affinity_source:I.affinity?.source??I.lineage?.source,affinity_bound:G.binding!==void 0||G.lineageBinding!==void 0,affinity_kind:G.binding!==void 0?"explicit":G.lineageBinding!==void 0?"history-lineage":void 0,account_hash:a(C.id),conversation_hash:G.requestConversationId===void 0?void 0:a(G.requestConversationId),reasoning_replay_locked:G.replayLocked}),"proceed"}async function UhI(I,G,C,N,Y){let{think:Z,budget:W}=VhI(I.body,I.model),b=N,l=!1;try{I.diagnostics?.phase("token_refresh");let Q=I.accountManager.toAuthDetails(N);b=await wG(I.tokenRefresher.refreshIfNeeded(N,Q,G),G);let L=I.accountManager.toAuthDetails(b);if(I.diagnostics?.phase("request_validation"),I.modelCapabilities){let B=await wG(I.modelCapabilities.ensureAccountModel(b,L,I.model,G),G);if(!B.supported)return y("warn","account_model_unavailable",{request_id:I.requestId,account_hash:a(b.id),model_hash:a(I.model),capability_source:B.source}),{kind:"model-unavailable",account:b}}let m=!1;if((I.body.projectionMode==="v3-auto"||I.body.projectionMode==="native-context-safe"||I.body.protocol==="responses"&&I.body.projectionMode==="legacy-user-prefix")&&LhI(I.body)){let B=I.nativeContextCapabilities?await wG(I.nativeContextCapabilities.ensureAccountNativeContext(b,L,G),G):{status:"unknown",source:"probe-error",featureCount:0,systemFieldInjection:!1,systemPromptMigration:!1};if(y("debug","native_context_capability_selected",{request_id:I.requestId,account_hash:a(b.id),status:B.status,source:B.source,feature_count:B.featureCount,system_field_injection:B.systemFieldInjection,system_prompt_migration:B.systemPromptMigration}),I.body.projectionMode==="native-context-safe"&&B.status!=="available")throw new ZI(B.status==="unknown"?"Kiro Runtime native instruction capability could not be verified; native-context-safe remains fail-closed":"Kiro Runtime did not advertise system_field_injection for this account; native-context-safe remains fail-closed","native_context_capability_unavailable");m=B.status==="available"}let V=O4.safeParse(I.config.effort),X=I.modelCapabilities?.promptCaching?.(b.id,I.model),R=qg(I.body,I.model,L,Z,W,{autoEffortMapping:I.config.auto_effort_mapping,conversationId:C.requestConversationId,nativeSystemPromptEnabled:m,resolvedReasoningReplays:C.replayState.replays,promptCaching:{mode:I.config.kiro_prompt_cache_mode,supported:X?.supportsPromptCaching===!0,...X?.maximumCacheCheckpointsPerRequest!==void 0?{maximumCheckpoints:X.maximumCacheCheckpointsPerRequest}:{},...X?.minimumTokensPerCacheCheckpoint!==void 0?{minimumTokens:X.minimumTokensPerCacheCheckpoint}:{}},...V.success?{effort:V.data}:{}});if(C.replayState.portableRuntimeProtocol!==void 0&&R.runtimeProtocol!==C.replayState.portableRuntimeProtocol)throw new KI("Reasoning replay request does not match the authenticated upstream operation","reasoning_replay_context_mismatch");if(I.onProjection?.(R.diagnostics),R.diagnostics.projection.legacyPrefixMessages!==void 0)y("info","reasoning_replay_projection_compatibility",{protocol:I.body.protocol,model:I.model,prefix_message_count:R.diagnostics.projection.legacyPrefixMessages});if(!cY(I,C))return Tb(I,C,"dispatch-guard"),{kind:"result",leaseTransferred:!1,result:{kind:"response",response:HN(502,"Upstream inference dispatch budget was exhausted","upstream_dispatch_budget_exhausted")}};let h=C.sdkDispatches+1,H=a(R.conversationId),d=a(b.id);y("debug","request_projection_completed",{request_id:I.requestId,attempt:h,model:I.model,conversation_hash:H,projection_mode:R.diagnostics.projection.projectionMode,instruction_channel:R.diagnostics.projection.instructionChannel,input_message_count:R.diagnostics.projection.inputMessageCount,output_message_count:R.diagnostics.projection.outputMessageCount,prefix_instruction_count:R.diagnostics.projection.prefixInstructionCount,trailing_instruction_count:R.diagnostics.projection.trailingInstructionCount,prefix_action:R.diagnostics.projection.prefixAction,suffix_action:R.diagnostics.projection.suffixAction}),y("debug","request_history_built",{request_id:I.requestId,attempt:h,model:I.model,conversation_hash:H,history_message_count:R.diagnostics.history.historyMessageCount,current_role:R.diagnostics.history.currentRole,current_text_chars:R.diagnostics.history.currentTextChars,current_has_text:R.diagnostics.history.currentTextChars>0,current_image_count:R.diagnostics.history.currentImageCount,current_document_count:R.diagnostics.history.currentDocumentCount,current_tool_result_count:R.diagnostics.history.currentToolResultCount,reasoning_replay_count:R.diagnostics.history.reasoningReplayCount});let F=(I.makeClient??yJ)(L,R.region,R.effort,OhI(I,R.region),qC(I.config),b.id,I.config.sdk_http_keep_alive,R.runtimeProtocol),c=R.conversationState.currentMessage.userInputMessage?.modelId??R.effectiveModel,v=R.effort?wL(R.additionalModelRequestFields,Yg(c,R.effort)):R.additionalModelRequestFields,J=Zg(c,I.body.thinking?.enabled===!0,I.body.thinking?.display);if(J!==void 0)v=wL(v,J);let u={conversationState:R.conversationState,...R.profileArn?{profileArn:R.profileArn}:{},...v?{additionalModelRequestFields:v}:{}};if(!mhI(u))throw TypeError("Transformed request is not a valid SDK command input");let g=new qR(u);if(R.runtimeProtocol==="kiro-runtime")KJ(g,{...R.systemPrompt!==void 0?{systemPrompt:R.systemPrompt}:{}});let A=new AbortController,p=(B)=>{if(!A.signal.aborted)A.abort(B)};C.sdkDispatches=h,I.diagnostics?.addSecrets([b.id,b.email,b.accessToken,b.refreshToken,L.access,L.refresh,L.clientSecret,L.profileArn]),I.diagnostics?.dispatch(h),y("info","sdk_dispatch_started",{request_id:I.requestId,attempt:h,model:I.model,effective_model:R.effectiveModel,effort:R.effort,account_hash:d,conversation_hash:H,mode:I.stream?"stream":"non-stream",upstream_operation:R.runtimeProtocol==="kiro-runtime"?"kiro-runtime":"codewhisperer"}),l=!0;let D={abortSignal:AbortSignal.any([G,A.signal]),onResponseHeaders:(B)=>{I.diagnostics?.headers(B.status,B.headers)}},q;try{q=await wG(I.stream?NK(F,g,D):F.send(g,D),G)}catch(B){throw p(B),B}I.diagnostics?.accepted();let k=AhI(I,b.id,R.conversationId,{region:R.region,...R.profileArn!==void 0?{profileArn:R.profileArn}:{},runtimeProtocol:R.runtimeProtocol,...R.diagnostics.projection.legacyPrefixMessages!==void 0?{legacyPrefixMessages:R.diagnostics.projection.legacyPrefixMessages}:{}}),K={options:I,signal:G,state:C,account:b,conversationId:R.conversationId,sdkResponse:q,captureOptions:k,abortUpstream:p,sdkAttempt:h,effort:R.effort,accountHash:d,inputTokenEstimate:()=>aL(R),contextUsageWindow:I.modelCapabilities?.contextUsageWindow?.(b.id,I.model)};return C.streamAttempts+=1,I.stream?await ThI(K,Y):await shI(K)}catch(Q){if(!G.aborted)I.diagnostics?.failure(Q);return{kind:"failed",account:b,caught:Q,upstreamStarted:l}}}function U2(I){return PN(I,Yw(I)?"upstream_protocol_error":"upstream_stream_error")}function B2(I,G){let C=Yw(I)?I.message:G.message;return{kind:"response",response:HN(502,C,G.code)}}function jhI(I,G){let C=I*2**Math.max(0,G-1);return Math.round(C*(1+Math.random()*0.25))}function BhI(I){return I instanceof Error?I:TypeError("SDK stream failed with a non-Error reason",{cause:I})}function ahI(I,G,C,N){if(G.aborted)return Promise.reject(_I(G));return new Promise((Y,Z)=>{let W=()=>{l(),N.onUpstreamReadSettled(),G.removeEventListener("abort",b)},b=()=>{W(),Z(_I(G))},l=N.watchIdle(C,()=>{W(),Z(new tZ(C))});G.addEventListener("abort",b,{once:!0}),I.next().then((Q)=>{W(),Y(Q)},(Q)=>{W(),Z(Q)})})}async function xhI(I,G,C,N){let{iterator:Y,telemetry:Z,prefetched:W}=I,b=async()=>{let Q=_I(G);throw Z.emitTerminal("external_abort"),await fL(I,N,Q),Q},l=async(Q)=>{let L=Q instanceof tZ;return y("warn",L?"sdk_stream_idle_timeout":"sdk_stream_upstream_error",{...Z.auditFields(),...L?Z.stallFields():{},...rY(Q),...L?{idle_timeout_ms:C}:{},phase:"prefetch"}),Z.emitTerminal(L?"idle_timeout":"upstream_error"),await fL(I,N,Q),{kind:"failed",error:Q}};while(!0){let Q;try{Q=await ahI(Y,G,C,Z)}catch(L){if(G.aborted)return b();return l(BhI(L))}if(Q.done){if(G.aborted)return b();return l(new LN)}if(Z.observeCanonicalEvent(Q.value),W.push(Q.value),Q.value.type==="started")return{kind:"accepted"};return l(new kI("Canonical stream omitted its start","upstream_protocol_error"))}}function MhI(I,G,C){return I.config.retry_empty_completion&&!G.emptyCompletionRetried&&G.streamAttempts<I.config.stream_max_attempts&&cY(I,G)&&C.isEmptyCompletion()}function ShI(I,G){let{options:C,state:N,account:Y}=I;return N.emptyCompletionRetried=!0,y("warn","sdk_stream_empty_completion_retry",{...G.auditFields(),attempt:N.streamAttempts,max_attempts:C.config.stream_max_attempts,account_hash:a(Y.id)}),{kind:"empty-completion",account:Y}}function Nw(I,G,C,N){let Y=Ww(I);if(I.config.session_affinity_stall_failover_threshold<=0||Y===void 0)return;let Z=G.lineageStallRow;if(Z!==void 0&&(Z.accountId!==C||Z.conversationId!==N))return;(I.affinityStalls??PL).clear(Y.keyHash)}function nhI(I,G,C,N,Y){let Z=Ww(I);if(I.config.session_affinity_stall_failover_threshold<=0||Z===void 0)return;if(Y.localPersistence){Nw(I,G,C,N);return}let W=I.affinityStalls??PL,b=Z.keyHash,l=Y.provenance;if(l==="normal_complete"){Nw(I,G,C,N);return}if(l==="external_abort"){if(!Y.requestDeadline||!Y.upstreamQuiet)return}else if(l!=="idle_timeout"&&l!=="upstream_error")return;let Q=W.record(b,Date.now(),I.config.session_affinity_stall_window_ms,I.config.session_affinity_max_entries,C);y("warn","session_affinity_stall_recorded",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,affinity_source:Z.source,affinity_hash:a(b),terminal_provenance:l,stall_count:Q.count,stall_span_ms:Math.max(0,Q.lastAt-Q.firstAt),stall_window_ms:I.config.session_affinity_stall_window_ms,stall_threshold:I.config.session_affinity_stall_failover_threshold,failover_armed:Q.count>=I.config.session_affinity_stall_failover_threshold})}function y9(I,G){if(typeof I!=="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(I))return;return G?G.identifier(I):I}function U9(I){let{options:G,state:C,account:N,conversationId:Y}=I,Z=C.pendingMigration;if(Z===void 0)return;C.pendingMigration=void 0;let W={request_id:G.requestId,protocol:G.body.protocol,model:G.model,from_account_hash:a(Z.fromAccountId),to_account_hash:a(N.id),conversation_hash:a(Y),replay_count:Z.replayCount};if(G.affinity&&G.affinityStore){let b;try{b=G.affinityStore.rebindSessionAffinity(G.affinity.keyHash,N.id,Y,Date.now(),G.config.session_affinity_ttl_ms,G.config.session_affinity_max_entries)}catch(l){y("warn","reasoning_replay_migration_commit_failed",{...W,error_type:y9(l instanceof Error?l.name:void 0,G.diagnostics)??(l instanceof Error?"Error":typeof l),error_code:y9(l!==null&&typeof l==="object"&&"code"in l?l.code:void 0,G.diagnostics)});return}C.binding=b,C.affinityQuarantined=!1}y("info","reasoning_replay_migration_committed",W)}async function ThI(I,G){let{options:C,signal:N,account:Y,conversationId:Z,sdkResponse:W,captureOptions:b}=I,l={kind:"stream",sdkResponse:W,maxToolArgumentsBytes:C.config.max_request_body_bytes,validateToolArguments:C.validateToolArguments,model:C.model,conversationId:Z,inputTokenEstimate:I.inputTokenEstimate,contextUsageWindow:I.contextUsageWindow,telemetryContext:{requestId:C.requestId,attempt:I.sdkAttempt,effort:I.effort,accountHash:I.accountHash,diagnostics:C.diagnostics},...b,releaseAccount:G,abortUpstream:I.abortUpstream,onTerminal:(m)=>nhI(C,I.state,Y.id,Z,m)},Q=Mh(l,N),L=await xhI(Q,N,C.config.stream_idle_timeout_ms,I.abortUpstream);if(L.kind==="failed"){if(b.prefetchFableReasoning)return{kind:"result",leaseTransferred:!1,result:B2(L.error,U2(L.error))};return{kind:"stream-failed",account:Y,caught:L.error,failure:U2(L.error)}}return U9(I),{kind:"result",leaseTransferred:!0,result:{...l,prepared:Q}}}async function shI(I){let{options:G,signal:C,state:N,account:Y,conversationId:Z,sdkResponse:W,captureOptions:b}=I,l=xh(G.model,Z,"non-stream",{diagnostics:G.diagnostics,requestId:G.requestId,attempt:I.sdkAttempt,effort:I.effort,accountHash:I.accountHash}),Q,L=Promise.resolve(),m=new AbortController,V=AbortSignal.any([C,m.signal]),X=b.prefetchFableReasoning?l.watchIdle(G.config.stream_idle_timeout_ms,()=>{let R=new tZ(G.config.stream_idle_timeout_ms);m.abort(R),I.abortUpstream(R)}):void 0;try{Q=await rg(W,G.model,Z,V,{...b,inputTokenEstimate:I.inputTokenEstimate,contextUsageWindow:I.contextUsageWindow,maxToolArgumentsBytes:G.config.max_request_body_bytes,textLimit:G.collectedTextLimit,validateToolArguments:G.validateToolArguments,diagnostics:G.diagnostics,onCompletionWitness:(R)=>l.onCompletionWitness(R),onRawEvent:(R)=>l.onRawEvent(R),onToolCallProgress:(R)=>l.onToolCallProgress(R),onCanonicalEvent:(R)=>l.observeCanonicalEvent(R),onIteratorCleanup:(R)=>{L=R}})}catch(R){let h=C.aborted,H=R instanceof tZ;if(!h)y("warn",H?"sdk_stream_idle_timeout":"sdk_stream_upstream_error",{...l.auditFields(),...rY(R,G.diagnostics),error_name:G.diagnostics?.identifier(R instanceof Error?R.name:typeof R)});if(l.emitTerminal(h?"external_abort":H?"idle_timeout":"upstream_error"),I.abortUpstream(R),await FI(()=>L),h)throw _I(C);if(b.prefetchFableReasoning)return{kind:"result",leaseTransferred:!1,result:B2(R,U2(R))};if(!l.collectorSemanticSeen)return{kind:"stream-failed",account:Y,caught:R,failure:U2(R)};throw R}finally{X?.(),l.onUpstreamReadSettled()}if(await FI(()=>L),C.aborted)throw l.emitTerminal("external_abort"),_I(C);if(y("info","sdk_stream_completed",l.auditFields()),l.emitTerminal("normal_complete"),U9(I),b.reasoningReplayDecision.mode===void 0&&MhI(G,N,l))return ShI(I,l);return Nw(G,N,Y.id,Z),{kind:"result",leaseTransferred:!1,result:{kind:"response",response:Response.json(Q,{headers:{"Content-Type":xA,...b.reasoningReplayDecision.mode==="conflict-omitted"?{"x-kiro-reasoning-replay-mode":"conflict-omitted"}:{}}})}}}async function ihI(I,G,C,N,Y){let{account:Z,caught:W,failure:b}=Y;if(G.aborted)throw _I(G);I.diagnostics?.failure(W,"upstream_stream"),C.lastStreamFailure=b;let l=vC(B2(W,b));if(b.disposition==="fatal")return l;if(!cY(I,C))return Tb(I,C,"stream-failed"),l;let Q=I.config.stream_max_attempts;if(C.streamAttempts>=Q)return y("warn","sdk_stream_attempts_exhausted",{attempt:C.streamAttempts,max_attempts:Q,error_code:b.code,account_hash:a(Z.id),mode:I.stream?"stream":"non-stream"}),l;let L=new Set(N.eligibleAccountIds);L.delete(Z.id);let m=C.replayLocked?0:z9(I,N.accounts,L),V=!C.streamRetriedAccountIds.has(Z.id)||m===0;if(C.streamRetriedAccountIds.add(Z.id),!V)C.requestExcludedAccountIds.add(Z.id),j2(C);return y("warn","sdk_stream_attempt_retry",{attempt:C.streamAttempts,max_attempts:Q,error_code:b.code,same_account:V,account_hash:a(Z.id),mode:I.stream?"stream":"non-stream"}),I.diagnostics?.phase("retry_backoff"),await MN(jhI(I.config.rate_limit_retry_delay_ms,C.streamAttempts),G),ZZ}function PhI(I,G,C,N){if(G.migrationFallbackSpent)return"fallback_spent";let Y=C.accounts.find((Z)=>Z.id===N);if(Y===void 0)return"origin_missing";if(!HC(Y,Date.now(),_0(I)))return"origin_unselectable";if(!C.eligibleAccountIds.has(N)||G.requestExcludedAccountIds.has(N)||G.modelRejectedAccountIds.has(N))return"origin_ineligible";if(G.quarantinedAccountIds.has(N))return"origin_quarantined";if(!cY(I,G))return"dispatch_budget";return}function fhI(I,G,C,N,Y){G.pendingMigration=void 0;let Z={kind:"response",response:HN(400,"Kiro rejected the request after its signed reasoning history was migrated to another account, and the original account is unavailable","reasoning_replay_migration_rejected")},W=PhI(I,G,C,N.fromAccountId);if(y("warn","reasoning_replay_migration_rejected",{request_id:I.requestId,protocol:I.body.protocol,model:I.model,from_account_hash:a(N.fromAccountId),to_account_hash:a(N.toAccountId),replay_count:N.replayCount,upstream_status:Y.status,upstream_code:Y.reason,fallback:W===void 0?"origin":"none",fallback_blocked_reason:W}),W!==void 0)return vC(Z);return G.migrationFallbackSpent=!0,G.migrationFallback={accountId:N.fromAccountId,...N.fromConversationId!==void 0?{conversationId:N.fromConversationId}:{},terminal:Z},G.preferredAccountId=N.fromAccountId,G.requestAccountId=N.fromAccountId,G.requestConversationId=N.fromConversationId,ZZ}async function $hI(I,G,C,N,Y){let{account:Z,caught:W,upstreamStarted:b}=Y;if(G.aborted)throw _I(G);if(!b){if(W instanceof ZI||W instanceof KI)throw W;if(u9(W))return k9(I,G,C,Z,W);if(C.replayLocked)return vC(Zw());throw W}if(Yw(W)){let V=PN(W,"upstream_protocol_error");if(V.disposition==="retryable"&&cY(I,C)&&C.retryCount<I.config.rate_limit_max_retries)return C.retryCount+=1,y("warn","non_stream_failure_retry",{account_hash:a(Z.id),error_code:V.code,retry_count:C.retryCount}),I.diagnostics?.phase("retry_backoff"),await MN(I.config.rate_limit_retry_delay_ms*2**(C.retryCount-1),G),ZZ;if(V.disposition==="retryable"&&!cY(I,C))Tb(I,C,"non-stream-failed");return vC({kind:"response",response:HN(502,W.message,W.code)})}let l=Xb(W),Q=iJ(l.status),L=Q?(C.serverErrors.get(Z.id)??0)+1:0;if(Q)C.serverErrors.set(Z.id,L);let m=PJ(l,{accountId:Z.id,accountCount:Math.max(1,z9(I,N.accounts,N.eligibleAccountIds)),retryCount:C.retryCount,maxRetries:I.config.rate_limit_max_retries,serverErrorCount:L,retryDelayMs:I.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:C.forcedRefreshAccountIds});switch(m.action){case"refresh-then-retry":if(!cY(I,C))return Tb(I,C,"refresh-then-retry"),vC({kind:"response",response:HN(m.status,l.message,l.code)});C.forcedRefreshAccountIds.add(m.forcedRefreshAccountId);try{I.diagnostics?.phase("token_refresh"),await wG(I.tokenRefresher.forceRefresh(Z,G),G)}catch(V){if(G.aborted)throw _I(G);if(!u9(V))throw V;return k9(I,G,C,Z,V,"forced")}return ZZ;case"retry":if(!cY(I,C))return Tb(I,C,"retry"),vC({kind:"response",response:HN(m.status??502,l.message,l.code)});return C.retryCount+=1,I.diagnostics?.phase("retry_backoff"),await MN(m.retryAfterMs??0,G),ZZ;case"switch":{let V=l.status===401||l.status===403&&JN(l.message);if(V)C.lastAuthenticationFailure=l;if(OL(m))C.lastQuotaFailure=l;if(V&&C.replayLocked)I.accountManager.markUnhealthy(Z,AN(l.message));else if(l.reason==="TEMPORARILY_SUSPENDED")I.accountManager.markUnhealthy(Z,`InvalidTokenException: Account Suspended: ${l.message}`);else if(OL(m))J9(I,Z);else I.accountManager.markRateLimited(Z,Date.now()+(m.retryAfterMs??I.config.rate_limit_retry_delay_ms));if(!cY(I,C))return Tb(I,C,"switch"),vC({kind:"response",response:HN(m.status??502,l.message,m.code??l.code)});if(C.replayLocked){if(l.status===429){if(C.retryCount+=1,C.retryCount>=I.config.rate_limit_max_retries){let X=m.retryAfterMs??I.config.rate_limit_retry_delay_ms;return vC($N(429,"The account bound to signed reasoning replay remains rate-limited","reasoning_replay_account_rate_limited",X))}}return ZZ}return C.requestExcludedAccountIds.add(Z.id),j2(C),ZZ}case"fail":{let V=C.pendingMigration;if(V!==void 0&&V.toAccountId===Z.id&&HhI(l))return fhI(I,C,N,V,l);if(E9(l))return vC({kind:"response",response:s(400,l.message,"invalid_request_error","invalid_reasoning_signature")});if(OL(m))J9(I,Z);if(l.reason==="TEMPORARILY_SUSPENDED")I.accountManager.markUnhealthy(Z,`InvalidTokenException: Account Suspended: ${l.message}`);return vC({kind:"response",response:HN(m.terminalStatus??m.status??500,l.message,m.code??l.code)})}}}async function thI(I,G){let C=KhI(I);await yhI(I,G,C);while(!0){if(G.aborted)throw _I(G);if(C.iterations+=1,C.iterations>I.config.max_request_iterations)return EhI(I,C);let N=()=>UL(()=>{let m=performance.now(),V=DhI(I,C);return y("info","account_selection_completed",{request_id:I.requestId,duration_ms:Math.max(0,Math.round(performance.now()-m)),outcome:V.kind,replay_locked:C.replayLocked}),V.kind==="capacity-wait"?{kind:"wait",accountIds:V.accountIds}:{kind:"ready",value:V,...V.kind==="selected"?{accountId:V.selection.selected.id}:{}}},G,I.config.account_inference_concurrency),Y=await(I.diagnostics?.waitForQueue("capacity",N,(m)=>m.lease!==void 0)??N()),Z=Y.value;if(Z.kind==="result")return Z.result;if(Z.kind==="wait"){await MN(Z.waitMs+1,G);continue}let{selection:W}=Z,b=Y.lease;if(!b)throw TypeError("Selected account has no capacity reservation");let l=()=>b,Q=await(I.diagnostics?.waitForQueue("account",l)??l()),L=!0;try{if(G.aborted)throw _I(G);if(qhI(I,C,W.selected)==="reselect")continue;let m=await UhI(I,G,C,W.selected,Q);if(m.kind==="result")return L=!m.leaseTransferred,m.result;if(m.kind==="model-unavailable"){if(C.replayLocked)return $N(503,`Model ${I.model} is unavailable on the account bound to signed reasoning replay`,"reasoning_replay_model_unavailable");C.modelRejectedAccountIds.add(m.account.id),j2(C);continue}if(m.kind==="empty-completion")continue;let V=m.kind==="stream-failed"?await ihI(I,G,C,W,m):await $hI(I,G,C,W,m);if(V.kind==="return")return V.result}finally{if(L)Q()}}}async function sb(I){let G=I.requestId??RY(),C=I.diagnostics??new xZ(G,I.config.api_keys),N={...I,requestId:G,diagnostics:C},Y=BJ(N.deadlineSignal,N.config.request_timeout_ms),Z,W,b=!1;try{let l=N.affinity?.keyHash??N.lineage?.lookupKeyHash;if(l!==void 0)Z=await C.waitForQueue("session",()=>cL(l,Y.signal));C.phase("request_validation");let Q=D2(I.body.tools.map((R)=>({name:R.wireName,schema:R.inputSchema,path:R.path,publicType:R.publicType})),I.body.toolChoice!=="none",I.unexpectedToolCallFailure),L=await thI({...N,validateToolArguments:Q},Y.signal);if(L.kind==="response")return await C.response(L.response);W=L.releaseAccount;let m=W,V=Z,X;try{X=(N.createStreamResponse??CK)(L,Y.signal,N.config.stream_idle_timeout_ms,(R)=>{Y.dispose();let h=()=>{m(),V?.(),C.cleanup(),WG(()=>N.onCleanup?.())};if(R)R.then(h,h);else h()})}catch(R){throw L.prepared.telemetry.emitTerminal("external_abort"),await fL(L.prepared,L.abortUpstream,R),R}return W=void 0,Z=void 0,b=!0,await C.response(X)}catch(l){if(l instanceof ZI)return y("warn","request_transform_rejected",{request_id:G,stage:"request_transform",protocol:N.body.protocol,model:N.model,projection_mode:N.body.projectionMode,code:l.code,param:l.param}),s(400,l.message,"invalid_request_error",l.code,l.param);if(l instanceof KI)return s(l.retryable?503:400,l.message,l.retryable?"service_unavailable":"invalid_request_error",l.code);if(Y.signal.aborted){C.cancel(Y.signal.reason instanceof Error&&Y.signal.reason.name==="TimeoutError"?"request_deadline":"external_abort");let L=["client_disconnect","consumer_cancel"].includes(C.snapshot().cancel_source??"");return await C.response(s(L?499:504,L?"Client closed request":"Request deadline exceeded",L?"request_aborted":"timeout_error",L?"client_disconnected":"request_timeout"))}let Q=Xb(l);if(Q.status!==void 0)return C.failure(l),await C.response(s(Q.status>=400?Q.status:502,Q.message,"upstream_error",Q.code));return y("error","pipeline_internal_error",{request_id:G,error_type:C.identifier(l instanceof Error?l.name:typeof l),error_code:C.identifier(Q.code),error_message_hash:a(Q.message)}),MZ(G)}finally{if(!b)W?.(),Z?.(),Y.dispose(),C.cleanup(),WG(()=>N.onCleanup?.())}}function WZ(I,G,C){return{id:I.id,object:"chat.completion.chunk",created:I.created,model:I.model,choices:[{index:0,delta:G,finish_reason:C}]}}function _hI(I,G,C){switch(I.type){case"text_delta":return[JSON.stringify(WZ(G,{content:I.text},null))];case"reasoning_delta":return[JSON.stringify(WZ(G,{reasoning_content:I.text},null))];case"reasoning_signature":return[JSON.stringify(WZ(G,{reasoning_signature:I.signature},null))];case"reasoning_redacted":return[JSON.stringify(WZ(G,{reasoning_redacted_content:I.data},null))];case"reasoning_encrypted":return[JSON.stringify(WZ(G,{reasoning_encrypted_content:I.encryptedContent},null))];case"tool_call_delta":return[JSON.stringify(WZ(G,{tool_calls:[{index:I.index,...I.id!==void 0?{id:I.id,type:"function"}:{},function:{...I.name!==void 0?{name:I.name}:{},arguments:I.arguments}}]},null))];case"completed":{let N=JSON.stringify({...WZ(G,{},I.finishReason),...iY(I.codeReferences)});if(!C)return[N];let Y={id:G.id,object:"chat.completion.chunk",created:G.created,model:G.model,choices:[],usage:{prompt_tokens:I.usage.inputTokens,completion_tokens:I.usage.outputTokens,total_tokens:I.usage.totalTokens}};return[N,JSON.stringify(Y)]}}}function j9(I){let G=I.reasoning;return Response.json({id:I.conversationId,object:"chat.completion",created:I.createdAt,model:I.model,choices:[{index:0,message:{role:"assistant",content:I.text.length===0&&I.toolCalls.length>0?null:I.text,...G?.text?{reasoning_content:G.text}:{},...G?.signature?{reasoning_signature:G.signature}:{},...G?.redactedContent?{reasoning_redacted_content:G.redactedContent}:{},...G?.encryptedContent?{reasoning_encrypted_content:G.encryptedContent}:{},...I.toolCalls.length>0?{tool_calls:I.toolCalls.map((C)=>({id:C.id,type:"function",function:{name:C.name,arguments:C.input}}))}:{}},finish_reason:I.finishReason}],usage:{prompt_tokens:I.usage.inputTokens,completion_tokens:I.usage.outputTokens,total_tokens:I.usage.totalTokens},...iY(I.codeReferences)})}function B9(I,G,C,N){let Y=N.includeUsage===!0,W=(I.body??new ReadableStream({start:(k)=>k.close()})).getReader(),b=new TextDecoder,l=new TextEncoder,Q=[],L=new Map,m="",V,X=!1,R,h,H=!1,d=(k)=>{Q.push(l.encode(`data: ${k}
|
|
376
376
|
|
|
377
377
|
`))},O=(k)=>{if(H||R===void 0||R==="consumer-cancel"||Q.length>0)return;H=!0,k.close()},F=(k)=>{if(H||Q.length===0)return O(k),!1;let K=k.desiredSize;if(K===null||K<=0)return!1;let B=Q.shift();if(!B)return!1;return k.enqueue(B),O(k),!0},c=(k)=>{if(R!==void 0)return!1;return R=k,!0},v=()=>{G.deadline.removeEventListener("abort",g)},J=()=>{G.client.removeEventListener("abort",A)},u=(k,K,B)=>{if(!c(k))return;if(k==="consumer-cancel")Q.length=0;WG(v,J,()=>{if(k==="normal-complete")d("[DONE]");else if(k==="deadline"||k==="upstream-error"||k==="upstream-protocol-error"){let M=B??(k==="deadline"?FC("request_deadline_exceeded"):k==="upstream-protocol-error"?FC("upstream_protocol_error"):PN(K));d(JSON.stringify({error:{message:M.message,type:M.disposition==="fatal"?"upstream_protocol_error":"upstream_error",code:M.code,...G.diagnostics?G.diagnostics.streamError(M.code,M.message):{}}}))}},C,()=>{if(h)F(h)}),FI(()=>W.cancel(K))},g=()=>{u("deadline",G.deadline.reason instanceof Error?G.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError"))},A=()=>{u("client-abort",G.client.reason instanceof Error?G.client.reason:new DOMException("Client closed request","AbortError"))},p=()=>{u("upstream-protocol-error",void 0,FC("upstream_protocol_error"))},D=()=>{u("upstream-error",void 0,FC("upstream_stream_incomplete"))},q=(k)=>{if(k.type==="started"){if(V!==void 0||X||k.model!==N.expectedModel)return!1;return V={id:k.conversationId,model:k.model,created:k.createdAt},G.diagnostics?.published(),d(JSON.stringify(WZ(V,{role:"assistant"},null))),!0}if(!V||X)return!1;if(k.type==="tool_call_delta"){let K=L.get(k.index)??{id:"",name:"",arguments:""};if(k.id!==void 0&&K.id.length>0&&k.id!==K.id||k.name!==void 0&&K.name.length>0&&k.name!==K.name)return!1;if(k.id!==void 0)K.id=k.id;if(k.name!==void 0)K.name=k.name;K.arguments+=k.arguments,L.set(k.index,K)}if(k.type==="completed"){let K=[...L.entries()].sort(([M],[j])=>M-j),B=K.length>0?"tool_calls":"stop";if(k.finishReason!==B||K.some(([M,j],WI)=>M!==WI||j.id.length===0||j.name.length===0)||new Set(K.map(([,M])=>M.id)).size!==K.length)return!1}for(let K of _hI(k,V,Y))G.diagnostics?.projectedFrame(),d(K);if(k.type==="completed")X=!0;return!0};return new Response(new ReadableStream({start(k){if(h=k,G.deadline.addEventListener("abort",g,{once:!0}),G.client.addEventListener("abort",A,{once:!0}),G.deadline.aborted)g();else if(G.client.aborted)A()},async pull(k){if(F(k))return;if(R!==void 0)return;try{while(R===void 0){let K=m.indexOf(`
|
|
378
378
|
`);if(K>=0){let j=m.slice(0,K).trimEnd();if(m=m.slice(K+1),j.length===0)continue;let WI=hY(j);if(!WI||!q(WI)){p();return}if(F(k))return;continue}let B=await W.read();if(R!==void 0)return;if(!B.done){m+=b.decode(B.value,{stream:!0});continue}m+=b.decode();let M=m.trim();if(m="",M.length>0){let j=hY(M);if(!j||!q(j)){p();return}}if(!X){D();return}u("normal-complete");return}}catch(K){if(R!==void 0)return;u("upstream-error",K)}},cancel(k){u("consumer-cancel",k)}}),{status:I.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}var rhI="request_shape";function bW(I){return Array.isArray(I)?I:[]}function bw(I){return typeof I==="string"?I.length:0}function ohI(I,G){let C=new Set,N=0,Y=(Z)=>{if(typeof Z==="string")C.add(Z);else N+=1};for(let Z of bW(I.toolCalls))Y(Z?.id);for(let Z of bW(I.content))if(Z?.type==="tool_use")Y(Z.id);G.calls+=C.size+N,G.callIds.push(...C)}function ehI(I,G,C){switch(I?.type){case"text":C.textChars+=bw(I.text);return;case"image":C.images+=1;return;case"document":C.documents+=1;return;case"tool_result":if(C.results+=1,typeof I.toolCallId!=="string"||!G.has(I.toolCallId))C.orphanResults+=1;for(let N of bW(I.content))C.textChars+=bw(N?.text);return;default:return}}function IHI(I){let G=bW(I.messages),C=bW(I.tools),N=bW(I.reasoningReplays),Y={user:0,assistant:0,tool:0,instruction:0},Z={textChars:bw(I.instructions?.text),images:0,documents:0,results:0,orphanResults:0,calls:0,callIds:[]},W=new Set;for(let l of G){switch(l?.role){case"user":Y.user+=1;break;case"assistant":Y.assistant+=1;break;case"tool":Y.tool+=1;break;case"system":case"developer":Y.instruction+=1;break;default:break}if(l===void 0||l===null)continue;for(let Q of bW(l.content))ehI(Q,W,Z);ohI(l,Z);for(let Q of Z.callIds.splice(0))W.add(Q)}let b=C.map((l)=>typeof l?.name==="string"?l.name:"").sort((l,Q)=>l<Q?-1:l>Q?1:0);return{protocol:I.protocol,projection_mode:I.projectionMode,model:I.model,message_count:G.length,user_message_count:Y.user,assistant_message_count:Y.assistant,tool_message_count:Y.tool,instruction_message_count:Y.instruction,tool_declaration_count:C.length,tool_call_count:Z.calls,tool_result_count:Z.results,orphan_tool_result_count:Z.orphanResults,image_count:Z.images,document_count:Z.documents,has_reasoning_replay:N.length>0,reasoning_replay_count:N.length,system_instruction_present:I.instructions!==void 0||Y.instruction>0,input_text_chars:Z.textChars,tool_set_hash:a(b.join(`
|