@arcforge/axon 2.0.164 → 2.0.166

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/agent-main.js CHANGED
@@ -499,9 +499,9 @@ Project '${L.projectName}' (${aC[L.projectKind]}) ${B}
499
499
  `,B++};this.projectService.externalProjects.forEach(V),this.projectService.configuredProjects.forEach(V),this.projectService.inferredProjects.forEach(V)}}this.logger.msg(U,"Err")}send(X){if(X.type==="event"&&!this.canUseEvents){if(this.logger.hasLevel(3))this.logger.info(`Session does not support events: ignored event: ${S3(X)}`);return}this.writeMessage(X)}writeMessage(X){let K=YM$(X,this.logger,this.byteLength,this.host.newLine);this.host.write(K)}event(X,K){this.send(QM$(K,X))}doOutput(X,K,G,U,B,V){let L={seq:0,type:"response",command:K,request_seq:G,success:U,performanceData:B&&W86(B)};if(U){let A;if(I9(X))L.body=X,A=X.metadata,delete X.metadata;else if(typeof X==="object")if(X.metadata){let{metadata:_,...N}=X;L.body=N,A=_}else L.body=X;else L.body=X;if(A)L.metadata=A}else m.assert(X===void 0);if(V)L.message=V;this.send(L)}semanticCheck(X,K){var G,U;let B=DY();(G=H8)==null||G.push(H8.Phase.Session,"semanticCheck",{file:X,configFilePath:K.canonicalConfigFilePath});let V=o16(K,X)?r7:K.getLanguageService().getSemanticDiagnostics(X).filter((L)=>!!L.file);this.sendDiagnosticsEvent(X,K,V,"semanticDiag",B),(U=H8)==null||U.pop()}syntacticCheck(X,K){var G,U;let B=DY();(G=H8)==null||G.push(H8.Phase.Session,"syntacticCheck",{file:X,configFilePath:K.canonicalConfigFilePath}),this.sendDiagnosticsEvent(X,K,K.getLanguageService().getSyntacticDiagnostics(X),"syntaxDiag",B),(U=H8)==null||U.pop()}suggestionCheck(X,K){var G,U;let B=DY();(G=H8)==null||G.push(H8.Phase.Session,"suggestionCheck",{file:X,configFilePath:K.canonicalConfigFilePath}),this.sendDiagnosticsEvent(X,K,K.getLanguageService().getSuggestionDiagnostics(X),"suggestionDiag",B),(U=H8)==null||U.pop()}regionSemanticCheck(X,K,G){var U,B,V;let L=DY();(U=H8)==null||U.push(H8.Phase.Session,"regionSemanticCheck",{file:X,configFilePath:K.canonicalConfigFilePath});let A;if(!this.shouldDoRegionCheck(X)||!(A=K.getLanguageService().getRegionSemanticDiagnostics(X,G))){(B=H8)==null||B.pop();return}this.sendDiagnosticsEvent(X,K,A.diagnostics,"regionSemanticDiag",L,A.spans),(V=H8)==null||V.pop();return}shouldDoRegionCheck(X){var K;let G=(K=this.projectService.getScriptInfoForNormalizedPath(X))==null?void 0:K.textStorage.getLineInfo().getLineCount();return!!(G&&G>=this.regionDiagLineCountThreshold)}sendDiagnosticsEvent(X,K,G,U,B,V){try{let L=m.checkDefined(K.getScriptInfo(X)),A=DY()-B,_={file:X,diagnostics:G.map((N)=>t16(X,K,N)),spans:V==null?void 0:V.map((N)=>AU(N,L))};this.event(_,U),this.addDiagnosticsPerformanceData(X,U,A)}catch(L){this.logError(L,U)}}updateErrorCheck(X,K,G,U=!0){if(K.length===0)return;m.assert(!this.suppressDiagnosticEvents);let B=this.changeSeq,V=Math.min(G,200),L=0,A=()=>{if(L++,K.length>L)return X.delay("checkOne",V,N)},_=(T,k)=>{if(this.semanticCheck(T,k),this.changeSeq!==B)return;if(this.getPreferences(T).disableSuggestions)return A();X.immediate("suggestionCheck",()=>{this.suggestionCheck(T,k),A()})},N=()=>{if(this.changeSeq!==B)return;let T,k=K[L];if(h9(k))k=this.toPendingErrorCheck(k);else if("ranges"in k)T=k.ranges,k=this.toPendingErrorCheck(k.file);if(!k)return A();let{fileName:y,project:h}=k;if(qW(h),!h.containsFile(y,U))return;if(this.syntacticCheck(y,h),this.changeSeq!==B)return;if(h.projectService.serverMode!==0)return A();if(T)return X.immediate("regionSemanticCheck",()=>{let u=this.projectService.getScriptInfoForNormalizedPath(y);if(u)this.regionSemanticCheck(y,h,T.map((l)=>this.getRange({file:y,...l},u)));if(this.changeSeq!==B)return;X.immediate("semanticCheck",()=>_(y,h))});X.immediate("semanticCheck",()=>_(y,h))};if(K.length>L&&this.changeSeq===B)X.delay("checkOne",G,N)}cleanProjects(X,K){if(!K)return;this.logger.info(`cleaning ${X}`);for(let G of K)G.getLanguageService(!1).cleanupSemanticCache(),G.cleanupProgram()}cleanup(){if(this.cleanProjects("inferred projects",this.projectService.inferredProjects),this.cleanProjects("configured projects",F9(this.projectService.configuredProjects.values())),this.cleanProjects("external projects",this.projectService.externalProjects),this.host.gc)this.logger.info("host.gc()"),this.host.gc()}getEncodedSyntacticClassifications(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X);return G.getEncodedSyntacticClassifications(K,X)}getEncodedSemanticClassifications(X){let{file:K,project:G}=this.getFileAndProject(X),U=X.format==="2020"?"2020":"original";return G.getLanguageService().getEncodedSemanticClassifications(K,X,U)}getProject(X){return X===void 0?void 0:this.projectService.findProject(X)}getConfigFileAndProject(X){let K=this.getProject(X.projectFileName),G=WY(X.file);return{configFile:K&&K.hasConfigFile(G)?G:void 0,project:K}}getConfigFileDiagnostics(X,K,G){let U=K.getAllProjectErrors(),B=K.getLanguageService().getCompilerOptionsDiagnostics(),V=x$(u6(U,B),(L)=>!!L.file&&L.file.fileName===X);return G?this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(V):b6(V,(L)=>Mh(L,!1))}convertToDiagnosticsWithLinePositionFromDiagnosticFile(X){return X.map((K)=>({message:BU(K.messageText,this.host.newLine),start:K.start,length:K.length,category:cL(K),code:K.code,source:K.source,startLocation:K.file&&RT(w4(K.file,K.start)),endLocation:K.file&&RT(w4(K.file,K.start+K.length)),reportsUnnecessary:K.reportsUnnecessary,reportsDeprecated:K.reportsDeprecated,relatedInformation:b6(K.relatedInformation,UX$)}))}getCompilerOptionsDiagnostics(X){let K=this.getProject(X.projectFileName);return this.convertToDiagnosticsWithLinePosition(x$(K.getLanguageService().getCompilerOptionsDiagnostics(),(G)=>!G.file),void 0)}convertToDiagnosticsWithLinePosition(X,K){return X.map((G)=>({message:BU(G.messageText,this.host.newLine),start:G.start,length:G.length,category:cL(G),code:G.code,source:G.source,startLocation:K&&K.positionToLineOffset(G.start),endLocation:K&&K.positionToLineOffset(G.start+G.length),reportsUnnecessary:G.reportsUnnecessary,reportsDeprecated:G.reportsDeprecated,relatedInformation:b6(G.relatedInformation,UX$)}))}getDiagnosticsWorker(X,K,G,U){let{project:B,file:V}=this.getFileAndProject(X);if(K&&o16(B,V))return r7;let L=B.getScriptInfoForNormalizedPath(V),A=G(B,V);return U?this.convertToDiagnosticsWithLinePosition(A,L):A.map((_)=>t16(V,B,_))}getDefinition(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.getPositionInFile(X,G),V=this.mapDefinitionInfoLocations(U.getLanguageService().getDefinitionAtPosition(G,B)||r7,U);return K?this.mapDefinitionInfo(V,U):V.map($.mapToOriginalLocation)}mapDefinitionInfoLocations(X,K){return X.map((G)=>{let U=K86(G,K);return!U?G:{...U,containerKind:G.containerKind,containerName:G.containerName,kind:G.kind,name:G.name,failedAliasResolution:G.failedAliasResolution,...G.unverified&&{unverified:G.unverified}}})}getDefinitionAndBoundSpan(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.getPositionInFile(X,G),V=m.checkDefined(U.getScriptInfo(G)),L=U.getLanguageService().getDefinitionAndBoundSpan(G,B);if(!L||!L.definitions)return{definitions:r7,textSpan:void 0};let A=this.mapDefinitionInfoLocations(L.definitions,U),{textSpan:_}=L;if(K)return{definitions:this.mapDefinitionInfo(A,U),textSpan:AU(_,V)};return{definitions:A.map($.mapToOriginalLocation),textSpan:_}}findSourceDefinition(X){var K;let{file:G,project:U}=this.getFileAndProject(X),B=this.getPositionInFile(X,G),V=U.getLanguageService().getDefinitionAtPosition(G,B),L=this.mapDefinitionInfoLocations(V||r7,U).slice();if(this.projectService.serverMode===0&&(!L6(L,(y)=>WY(y.fileName)!==G&&!y.isAmbient)||L6(L,(y)=>!!y.failedAliasResolution))){let y=Ux((i)=>i.textSpan.start,IJ$(this.host.useCaseSensitiveFileNames));L==null||L.forEach((i)=>y.add(i));let h=U.getNoDtsResolutionProject(G),u=h.getLanguageService(),l=(K=u.getDefinitionAtPosition(G,B,!0,!1))==null?void 0:K.filter((i)=>WY(i.fileName)!==G);if(L6(l))for(let i of l){if(i.unverified){let t=T(i,U.getLanguageService().getProgram(),u.getProgram());if(L6(t)){for(let o of t)y.add(o);continue}}y.add(i)}else{let i=L.filter((t)=>WY(t.fileName)!==G&&t.isAmbient);for(let t of L6(i)?i:N()){let o=_(t.fileName,G,h);if(!o)continue;let J$=this.projectService.getOrCreateScriptInfoNotOpenedByClient(o,h.currentDirectory,h.directoryStructureHost,!1);if(!J$)continue;if(!h.containsScriptInfo(J$))h.addRoot(J$),h.updateGraph();let Y$=u.getProgram(),z$=m.checkDefined(Y$.getSourceFile(o));for(let V$ of k(t.name,z$,Y$))y.add(V$)}}L=F9(y.values())}return L=L.filter((y)=>!y.isAmbient&&!y.failedAliasResolution),this.mapDefinitionInfo(L,U);function _(y,h,u){var l,i,t;let o=xd(y);if(o&&y.lastIndexOf(nj)===o.topLevelNodeModulesIndex){let J$=y.substring(0,o.packageRootIndex),Y$=(l=U.getModuleResolutionCache())==null?void 0:l.getPackageJsonInfoCache(),z$=U.getCompilationSettings(),V$=JC(O9(J$,U.getCurrentDirectory()),$C(Y$,U,z$));if(!V$)return;let Z$=i0$(V$,{moduleResolution:2},U,U.getModuleResolutionCache()),f$=y.substring(o.topLevelPackageNameIndex+1,o.packageRootIndex),O$=XC(lf(f$)),G$=U.toPath(y);if(Z$&&L6(Z$,(R$)=>U.toPath(R$)===G$))return(i=u.resolutionCache.resolveSingleModuleNameWithoutWatching(O$,h).resolvedModule)==null?void 0:i.resolvedFileName;else{let R$=y.substring(o.packageRootIndex+1),T$=`${O$}/${h2(R$)}`;return(t=u.resolutionCache.resolveSingleModuleNameWithoutWatching(T$,h).resolvedModule)==null?void 0:t.resolvedFileName}}return}function N(){let y=U.getLanguageService(),h=y.getProgram(),u=IK(h.getSourceFile(G),B);if((fX(u)||z6(u))&&CY(u.parent))return Wj$(u,(l)=>{var i;if(l===u)return;let t=(i=y.getDefinitionAtPosition(G,l.getStart(),!0,!1))==null?void 0:i.filter((o)=>WY(o.fileName)!==G&&o.isAmbient).map((o)=>({fileName:o.fileName,name:_G(u)}));if(L6(t))return t})||r7;return r7}function T(y,h,u){var l;let i=u.getSourceFile(y.fileName);if(!i)return;let t=IK(h.getSourceFile(G),B),o=h.getTypeChecker().getSymbolAtLocation(t),J$=o&&uY(o,277);if(!J$)return;let Y$=((l=J$.propertyName)==null?void 0:l.text)||J$.name.text;return k(Y$,i,u)}function k(y,h,u){let l=kY.Core.getTopMostDeclarationNamesInFile(y,h);return f1(l,(i)=>{let t=u.getTypeChecker().getSymbolAtLocation(i),o=tw(i);if(t&&o)return NT.createDefinitionInfo(o,u.getTypeChecker(),t,o,!0)})}}getEmitOutput(X){let{file:K,project:G}=this.getFileAndProject(X);if(!G.shouldEmitFile(G.getScriptInfo(K)))return{emitSkipped:!0,outputFiles:[],diagnostics:[]};let U=G.getLanguageService().getEmitOutput(K);return X.richResponse?{...U,diagnostics:X.includeLinePosition?this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(U.diagnostics):U.diagnostics.map((B)=>Mh(B,!0))}:U}mapJSDocTagInfo(X,K,G){return X?X.map((U)=>{var B;return{...U,text:G?this.mapDisplayParts(U.text,K):(B=U.text)==null?void 0:B.map((V)=>V.text).join("")}}):[]}mapDisplayParts(X,K){if(!X)return[];return X.map((G)=>G.kind!=="linkName"?G:{...G,target:this.toFileSpan(G.target.fileName,G.target.textSpan,K)})}mapSignatureHelpItems(X,K,G){return X.map((U)=>({...U,documentation:this.mapDisplayParts(U.documentation,K),parameters:U.parameters.map((B)=>({...B,documentation:this.mapDisplayParts(B.documentation,K)})),tags:this.mapJSDocTagInfo(U.tags,K,G)}))}mapDefinitionInfo(X,K){return X.map((G)=>({...this.toFileSpanWithContext(G.fileName,G.textSpan,G.contextSpan,K),...G.unverified&&{unverified:G.unverified}}))}static mapToOriginalLocation(X){if(X.originalFileName)return m.assert(X.originalTextSpan!==void 0,"originalTextSpan should be present if originalFileName is"),{...X,fileName:X.originalFileName,textSpan:X.originalTextSpan,targetFileName:X.fileName,targetTextSpan:X.textSpan,contextSpan:X.originalContextSpan,targetContextSpan:X.contextSpan};return X}toFileSpan(X,K,G){let U=G.getLanguageService(),B=U.toLineColumnOffset(X,K.start),V=U.toLineColumnOffset(X,HQ(K));return{file:X,start:{line:B.line+1,offset:B.character+1},end:{line:V.line+1,offset:V.character+1}}}toFileSpanWithContext(X,K,G,U){let B=this.toFileSpan(X,K,U),V=G&&this.toFileSpan(X,G,U);return V?{...B,contextStart:V.start,contextEnd:V.end}:B}getTypeDefinition(X){let{file:K,project:G}=this.getFileAndProject(X),U=this.getPositionInFile(X,K),B=this.mapDefinitionInfoLocations(G.getLanguageService().getTypeDefinitionAtPosition(K,U)||r7,G);return this.mapDefinitionInfo(B,G)}mapImplementationLocations(X,K){return X.map((G)=>{let U=K86(G,K);return!U?G:{...U,kind:G.kind,displayParts:G.displayParts}})}getImplementation(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.getPositionInFile(X,G),V=this.mapImplementationLocations(U.getLanguageService().getImplementationAtPosition(G,B)||r7,U);return K?V.map(({fileName:L,textSpan:A,contextSpan:_})=>this.toFileSpanWithContext(L,A,_,U)):V.map($.mapToOriginalLocation)}getSyntacticDiagnosticsSync(X){let{configFile:K}=this.getConfigFileAndProject(X);if(K)return r7;return this.getDiagnosticsWorker(X,!1,(G,U)=>G.getLanguageService().getSyntacticDiagnostics(U),!!X.includeLinePosition)}getSemanticDiagnosticsSync(X){let{configFile:K,project:G}=this.getConfigFileAndProject(X);if(K)return this.getConfigFileDiagnostics(K,G,!!X.includeLinePosition);return this.getDiagnosticsWorker(X,!0,(U,B)=>U.getLanguageService().getSemanticDiagnostics(B).filter((V)=>!!V.file),!!X.includeLinePosition)}getSuggestionDiagnosticsSync(X){let{configFile:K}=this.getConfigFileAndProject(X);if(K)return r7;return this.getDiagnosticsWorker(X,!0,(G,U)=>G.getLanguageService().getSuggestionDiagnostics(U),!!X.includeLinePosition)}getJsxClosingTag(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K),B=G.getJsxClosingTagAtPosition(K,U);return B===void 0?void 0:{newText:B.newText,caretOffset:0}}getLinkedEditingRange(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K),B=G.getLinkedEditingRangeAtPosition(K,U),V=this.projectService.getScriptInfoForNormalizedPath(K);if(V===void 0||B===void 0)return;return Rs6(B,V)}getDocumentHighlights(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.getPositionInFile(X,G),V=U.getLanguageService().getDocumentHighlights(G,B,X.filesToSearch);if(!V)return r7;if(!K)return V;return V.map(({fileName:L,highlightSpans:A})=>{let _=U.getScriptInfo(L);return{file:L,highlightSpans:A.map(({textSpan:N,kind:T,contextSpan:k})=>({...ZM$(N,k,_),kind:T}))}})}provideInlayHints(X){let{file:K,project:G}=this.getFileAndProject(X),U=this.projectService.getScriptInfoForNormalizedPath(K);return G.getLanguageService().provideInlayHints(K,X,this.getPreferences(K)).map((V)=>{let{position:L,displayParts:A}=V;return{...V,position:U.positionToLineOffset(L),displayParts:A==null?void 0:A.map(({text:_,span:N,file:T})=>{if(N){m.assertIsDefined(T,"Target file should be defined together with its span.");let k=this.projectService.getScriptInfo(T);return{text:_,span:{start:k.positionToLineOffset(N.start),end:k.positionToLineOffset(N.start+N.length),file:T}}}else return{text:_}})}})}mapCode(X){var K;let G=this.getHostFormatOptions(),U=this.getHostPreferences(),{file:B,languageService:V}=this.getFileAndLanguageServiceForSyntacticOperation(X),L=this.projectService.getScriptInfoForNormalizedPath(B),A=(K=X.mapping.focusLocations)==null?void 0:K.map((N)=>{return N.map((T)=>{let k=L.lineOffsetToPosition(T.start.line,T.start.offset),y=L.lineOffsetToPosition(T.end.line,T.end.offset);return{start:k,length:y-k}})}),_=V.mapCode(B,X.mapping.contents,A,G,U);return this.mapTextChangesToCodeEdits(_)}getCopilotRelatedInfo(){return{relatedFiles:[]}}setCompilerOptionsForInferredProjects(X){this.projectService.setCompilerOptionsForInferredProjects(X.options,X.projectRootPath)}getProjectInfo(X){return this.getProjectInfoWorker(X.file,X.projectFileName,X.needFileNameList,X.needDefaultConfiguredProjectInfo,!1)}getProjectInfoWorker(X,K,G,U,B){let{project:V}=this.getFileAndProjectWorker(X,K);return qW(V),{configFileName:V.getProjectName(),languageServiceDisabled:!V.languageServiceEnabled,fileNames:G?V.getFileNames(!1,B):void 0,configuredProjectInfo:U?this.getDefaultConfiguredProjectInfo(X):void 0}}getDefaultConfiguredProjectInfo(X){var K;let G=this.projectService.getScriptInfo(X);if(!G)return;let U=this.projectService.findDefaultConfiguredProjectWorker(G,3);if(!U)return;let B,V;return U.seenProjects.forEach((L,A)=>{if(A!==U.defaultProject)if(L!==3)(B??(B=[])).push(WY(A.getConfigFilePath()));else(V??(V=[])).push(WY(A.getConfigFilePath()))}),(K=U.seenConfigs)==null||K.forEach((L)=>(B??(B=[])).push(L)),{notMatchedByConfig:B,notInProject:V,defaultProject:U.defaultProject&&WY(U.defaultProject.getConfigFilePath())}}getRenameInfo(X){let{file:K,project:G}=this.getFileAndProject(X),U=this.getPositionInFile(X,K),B=this.getPreferences(K);return G.getLanguageService().getRenameInfo(K,U,B)}getProjects(X,K,G){let U,B;if(X.projectFileName){let V=this.getProject(X.projectFileName);if(V)U=[V]}else{let V=K?this.projectService.getScriptInfoEnsuringProjectsUptoDate(X.file):this.projectService.getScriptInfo(X.file);if(!V){if(G)return r7;return this.projectService.logErrorForScriptInfoNotFound(X.file),XH.ThrowNoProject()}else if(!K)this.projectService.ensureDefaultProjectForFile(V);U=V.containingProjects,B=this.projectService.getSymlinkedProjects(V)}if(U=x$(U,(V)=>V.languageServiceEnabled&&!V.isOrphan()),!G&&(!U||!U.length)&&!B)return this.projectService.logErrorForScriptInfoNotFound(X.file??X.projectFileName),XH.ThrowNoProject();return B?{projects:U,symLinkedProjects:B}:U}getDefaultProject(X){if(X.projectFileName){let G=this.getProject(X.projectFileName);if(G)return G;if(!X.file)return XH.ThrowNoProject()}return this.projectService.getScriptInfo(X.file).getDefaultProject()}getRenameLocations(X,K){let G=WY(X.file),U=this.getPositionInFile(X,G),B=this.getProjects(X),V=this.getDefaultProject(X),L=this.getPreferences(G),A=this.mapRenameInfo(V.getLanguageService().getRenameInfo(G,U,L),m.checkDefined(this.projectService.getScriptInfo(G)));if(!A.canRename)return K?{info:A,locs:[]}:[];let _=Ms6(B,V,{fileName:X.file,pos:U},!!X.findInStrings,!!X.findInComments,L,this.host.useCaseSensitiveFileNames);if(!K)return _;return{info:A,locs:this.toSpanGroups(_)}}mapRenameInfo(X,K){if(X.canRename){let{canRename:G,fileToRename:U,displayName:B,fullDisplayName:V,kind:L,kindModifiers:A,triggerSpan:_}=X;return _X({canRename:G,fileToRename:U,displayName:B,fullDisplayName:V,kind:L,kindModifiers:A,triggerSpan:AU(_,K)})}else return X}toSpanGroups(X){let K=new Map;for(let{fileName:G,textSpan:U,contextSpan:B,originalContextSpan:V,originalTextSpan:L,originalFileName:A,..._}of X){let N=K.get(G);if(!N)K.set(G,N={file:G,locs:[]});let T=m.checkDefined(this.projectService.getScriptInfo(G));N.locs.push({...ZM$(U,B,T),..._})}return F9(K.values())}getReferences(X,K){let G=WY(X.file),U=this.getProjects(X),B=this.getPositionInFile(X,G),V=Ns6(U,this.getDefaultProject(X),{fileName:X.file,pos:B},this.host.useCaseSensitiveFileNames,this.logger);if(!K)return V;let L=this.getPreferences(G),A=this.getDefaultProject(X),_=A.getScriptInfoForNormalizedPath(G),N=A.getLanguageService().getQuickInfoAtPosition(G,B),T=N?iv(N.displayParts):"",k=N&&N.textSpan,y=k?_.positionToLineOffset(k.start).offset:0,h=k?_.getSnapshot().getText(k.start,HQ(k)):"";return{refs:Z0(V,(l)=>{return l.references.map((i)=>U86(this.projectService,i,L))}),symbolName:h,symbolStartOffset:y,symbolDisplayString:T}}getFileReferences(X,K){let G=this.getProjects(X),U=WY(X.file),B=this.getPreferences(U),V={fileName:U,pos:0},L=KM$(G,this.getDefaultProject(X),V,V,X86,(N)=>{return this.logger.info(`Finding references to file ${U} in project ${N.getProjectName()}`),N.getLanguageService().getFileReferences(U)}),A;if(I9(L))A=L;else{A=[];let N=jX$(this.host.useCaseSensitiveFileNames);L.forEach((T)=>{for(let k of T)if(!N.has(k))A.push(k),N.add(k)})}if(!K)return A;return{refs:A.map((N)=>U86(this.projectService,N,B)),symbolName:`"${X.file}"`}}openClientFile(X,K,G,U){this.projectService.openClientFileWithNormalizedPath(X,K,G,!1,U)}getPosition(X,K){return X.position!==void 0?X.position:K.lineOffsetToPosition(X.line,X.offset)}getPositionInFile(X,K){let G=this.projectService.getScriptInfoForNormalizedPath(K);return this.getPosition(X,G)}getFileAndProject(X){return this.getFileAndProjectWorker(X.file,X.projectFileName)}getFileAndLanguageServiceForSyntacticOperation(X){let{file:K,project:G}=this.getFileAndProject(X);return{file:K,languageService:G.getLanguageService(!1)}}getFileAndProjectWorker(X,K){let G=WY(X),U=this.getProject(K)||this.projectService.ensureDefaultProjectForFile(G);return{file:G,project:U}}getOutliningSpans(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=U.getOutliningSpans(G);if(K){let V=this.projectService.getScriptInfoForNormalizedPath(G);return B.map((L)=>({textSpan:AU(L.textSpan,V),hintSpan:AU(L.hintSpan,V),bannerText:L.bannerText,autoCollapse:L.autoCollapse,kind:L.kind}))}else return B}getTodoComments(X){let{file:K,project:G}=this.getFileAndProject(X);return G.getLanguageService().getTodoComments(K,X.descriptors)}getDocCommentTemplate(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K);return G.getDocCommentTemplateAtPosition(K,U,this.getPreferences(K),this.getFormatOptions(K))}getSpanOfEnclosingComment(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=X.onlyMultiLine,B=this.getPositionInFile(X,K);return G.getSpanOfEnclosingComment(K,B,U)}getIndentation(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K),B=X.options?TT(X.options):this.getFormatOptions(K),V=G.getIndentationAtPosition(K,U,B);return{position:U,indentation:V}}getBreakpointStatement(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K);return G.getBreakpointStatementAtPosition(K,U)}getNameOrDottedNameSpan(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K);return G.getNameOrDottedNameSpan(K,U,U)}isValidBraceCompletion(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.getPositionInFile(X,K);return G.isValidBraceCompletionAtPosition(K,U,X.openingBrace.charCodeAt(0))}getQuickInfoWorker(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getPreferences(G),L=U.getLanguageService().getQuickInfoAtPosition(G,this.getPosition(X,B),V.maximumHoverLength,X.verbosityLevel);if(!L)return;let A=!!V.displayPartsForJSDoc;if(K){let _=iv(L.displayParts);return{kind:L.kind,kindModifiers:L.kindModifiers,start:B.positionToLineOffset(L.textSpan.start),end:B.positionToLineOffset(HQ(L.textSpan)),displayString:_,documentation:A?this.mapDisplayParts(L.documentation,U):iv(L.documentation),tags:this.mapJSDocTagInfo(L.tags,U,A),canIncreaseVerbosityLevel:L.canIncreaseVerbosityLevel}}else return A?L:{...L,tags:this.mapJSDocTagInfo(L.tags,U,!1)}}getFormattingEditsForRange(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.projectService.getScriptInfoForNormalizedPath(K),B=U.lineOffsetToPosition(X.line,X.offset),V=U.lineOffsetToPosition(X.endLine,X.endOffset),L=G.getFormattingEditsForRange(K,B,V,this.getFormatOptions(K));if(!L)return;return L.map((A)=>this.convertTextChangeToCodeEdit(A,U))}getFormattingEditsForRangeFull(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=X.options?TT(X.options):this.getFormatOptions(K);return G.getFormattingEditsForRange(K,X.position,X.endPosition,U)}getFormattingEditsForDocumentFull(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=X.options?TT(X.options):this.getFormatOptions(K);return G.getFormattingEditsForDocument(K,U)}getFormattingEditsAfterKeystrokeFull(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=X.options?TT(X.options):this.getFormatOptions(K);return G.getFormattingEditsAfterKeystroke(K,X.position,X.key,U)}getFormattingEditsAfterKeystroke(X){let{file:K,languageService:G}=this.getFileAndLanguageServiceForSyntacticOperation(X),U=this.projectService.getScriptInfoForNormalizedPath(K),B=U.lineOffsetToPosition(X.line,X.offset),V=this.getFormatOptions(K),L=G.getFormattingEditsAfterKeystroke(K,B,X.key,V);if(X.key===`
500
500
  `&&(!L||L.length===0||Ls6(L,B))){let{lineText:A,absolutePosition:_}=U.textStorage.getAbsolutePositionAndLineText(X.line);if(A&&A.search("\\S")<0){let N=G.getIndentationAtPosition(K,B,V),T=0,k,y;for(k=0,y=A.length;k<y;k++)if(A.charAt(k)===" ")T++;else if(A.charAt(k)==="\t")T+=V.tabSize;else break;if(N!==T){let h=_+k;L.push({span:sQ(_,h),newText:_7.getIndentationString(N,V)})}}}if(!L)return;return L.map((A)=>{return{start:U.positionToLineOffset(A.span.start),end:U.positionToLineOffset(HQ(A.span)),newText:A.newText?A.newText:""}})}getCompletions(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getPosition(X,B),L=U.getLanguageService().getCompletionsAtPosition(G,V,{...uP$(this.getPreferences(G)),triggerCharacter:X.triggerCharacter,triggerKind:X.triggerKind,includeExternalModuleExports:X.includeExternalModuleExports,includeInsertTextCompletions:X.includeInsertTextCompletions},U.projectService.getFormatCodeOptions(G));if(L===void 0)return;if(K==="completions-full")return L;let A=X.prefix||"",_=f1(L.entries,(T)=>{if(L.isMemberCompletion||z9(T.name.toLowerCase(),A.toLowerCase())){let k=T.replacementSpan?AU(T.replacementSpan,B):void 0;return{...T,replacementSpan:k,hasAction:T.hasAction||void 0,symbol:void 0}}});if(K==="completions"){if(L.metadata)_.metadata=L.metadata;return _}return{...L,optionalReplacementSpan:L.optionalReplacementSpan&&AU(L.optionalReplacementSpan,B),entries:_}}getCompletionEntryDetails(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getPosition(X,B),L=U.projectService.getFormatCodeOptions(G),A=!!this.getPreferences(G).displayPartsForJSDoc,_=f1(X.entryNames,(N)=>{let{name:T,source:k,data:y}=typeof N==="string"?{name:N,source:void 0,data:void 0}:N;return U.getLanguageService().getCompletionEntryDetails(G,V,T,L,k,this.getPreferences(G),y?Q4(y,ks6):void 0)});return K?A?_:_.map((N)=>({...N,tags:this.mapJSDocTagInfo(N.tags,U,!1)})):_.map((N)=>({...N,codeActions:b6(N.codeActions,(T)=>this.mapCodeAction(T)),documentation:this.mapDisplayParts(N.documentation,U),tags:this.mapJSDocTagInfo(N.tags,U,A)}))}getCompileOnSaveAffectedFileList(X){let K=this.getProjects(X,!0,!0),G=this.projectService.getScriptInfo(X.file);if(!G)return r7;return Ps6(G,(U)=>this.projectService.getScriptInfoForPath(U),K,(U,B)=>{if(!U.compileOnSaveEnabled||!U.languageServiceEnabled||U.isOrphan())return;let V=U.getCompilationSettings();if(!!V.noEmit||j5(B.fileName)&&!As6(V))return;return{projectFileName:U.getProjectName(),fileNames:U.getCompileOnSaveAffectedFileList(B),projectUsesOutFile:!!V.outFile}})}emitFile(X){let{file:K,project:G}=this.getFileAndProject(X);if(!G)XH.ThrowNoProject();if(!G.languageServiceEnabled)return X.richResponse?{emitSkipped:!0,diagnostics:[]}:!1;let U=G.getScriptInfo(K),{emitSkipped:B,diagnostics:V}=G.emitFile(U,(L,A,_)=>this.host.writeFile(L,A,_));return X.richResponse?{emitSkipped:B,diagnostics:X.includeLinePosition?this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(V):V.map((L)=>Mh(L,!0))}:!B}getSignatureHelpItems(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getPosition(X,B),L=U.getLanguageService().getSignatureHelpItems(G,V,X),A=!!this.getPreferences(G).displayPartsForJSDoc;if(L&&K){let _=L.applicableSpan;return{...L,applicableSpan:{start:B.positionToLineOffset(_.start),end:B.positionToLineOffset(_.start+_.length)},items:this.mapSignatureHelpItems(L.items,U,A)}}else if(A||!L)return L;else return{...L,items:L.items.map((_)=>({..._,tags:this.mapJSDocTagInfo(_.tags,U,!1)}))}}toPendingErrorCheck(X){let K=WY(X),G=this.projectService.tryGetDefaultProjectForFile(K);return G&&{fileName:K,project:G}}getDiagnostics(X,K,G){if(this.suppressDiagnosticEvents)return;if(G.length>0)this.updateErrorCheck(X,G,K)}change(X){let K=this.projectService.getScriptInfo(X.file);m.assert(!!K),K.textStorage.switchToScriptVersionCache();let G=K.lineOffsetToPosition(X.line,X.offset),U=K.lineOffsetToPosition(X.endLine,X.endOffset);if(G>=0)this.changeSeq++,this.projectService.applyChangesToFile(K,L1({span:{start:G,length:U-G},newText:X.insertString}))}reload(X){let K=WY(X.file),G=X.tmpfile===void 0?void 0:WY(X.tmpfile),U=this.projectService.getScriptInfoForNormalizedPath(K);if(U)this.changeSeq++,U.reloadFromFile(G)}saveToTmp(X,K){let G=this.projectService.getScriptInfo(X);if(G)G.saveTo(K)}closeClientFile(X){if(!X)return;let K=y4(X);this.projectService.closeClientFile(K)}mapLocationNavigationBarItems(X,K){return b6(X,(G)=>({text:G.text,kind:G.kind,kindModifiers:G.kindModifiers,spans:G.spans.map((U)=>AU(U,K)),childItems:this.mapLocationNavigationBarItems(G.childItems,K),indent:G.indent}))}getNavigationBarItems(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=U.getNavigationBarItems(G);return!B?void 0:K?this.mapLocationNavigationBarItems(B,this.projectService.getScriptInfoForNormalizedPath(G)):B}toLocationNavigationTree(X,K){return{text:X.text,kind:X.kind,kindModifiers:X.kindModifiers,spans:X.spans.map((G)=>AU(G,K)),nameSpan:X.nameSpan&&AU(X.nameSpan,K),childItems:b6(X.childItems,(G)=>this.toLocationNavigationTree(G,K))}}getNavigationTree(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=U.getNavigationTree(G);return!B?void 0:K?this.toLocationNavigationTree(B,this.projectService.getScriptInfoForNormalizedPath(G)):B}getNavigateToItems(X,K){let G=this.getFullNavigateToItems(X);return!K?Z0(G,({navigateToItems:U})=>U):Z0(G,({project:U,navigateToItems:B})=>B.map((V)=>{let L=U.getScriptInfo(V.fileName),A={name:V.name,kind:V.kind,kindModifiers:V.kindModifiers,isCaseSensitive:V.isCaseSensitive,matchKind:V.matchKind,file:V.fileName,start:L.positionToLineOffset(V.textSpan.start),end:L.positionToLineOffset(HQ(V.textSpan))};if(V.kindModifiers&&V.kindModifiers!=="")A.kindModifiers=V.kindModifiers;if(V.containerName&&V.containerName.length>0)A.containerName=V.containerName;if(V.containerKind&&V.containerKind.length>0)A.containerKind=V.containerKind;return A}))}getFullNavigateToItems(X){let{currentFileOnly:K,searchValue:G,maxResultCount:U,projectFileName:B}=X;if(K){m.assertIsDefined(X.file);let{file:k,project:y}=this.getFileAndProject(X);return[{project:y,navigateToItems:y.getLanguageService().getNavigateToItems(G,U,k)}]}let V=this.getHostPreferences(),L=[],A=new Map;if(!X.file&&!B)this.projectService.loadAncestorProjectTree(),this.projectService.forEachEnabledProject((k)=>_(k));else{let k=this.getProjects(X);J86(k,void 0,(y)=>_(y))}return L;function _(k){let y=k.getLanguageService().getNavigateToItems(G,U,void 0,k.isNonTsProject(),V.excludeLibrarySymbolsInNavTo),h=x$(y,(u)=>N(u)&&!BX$(nC(u),k));if(h.length)L.push({project:k,navigateToItems:h})}function N(k){let y=k.name;if(!A.has(y))return A.set(y,[k]),!0;let h=A.get(y);for(let u of h)if(T(u,k))return!1;return h.push(k),!0}function T(k,y){if(k===y)return!0;if(!k||!y)return!1;return k.containerKind===y.containerKind&&k.containerName===y.containerName&&k.fileName===y.fileName&&k.isCaseSensitive===y.isCaseSensitive&&k.kind===y.kind&&k.kindModifiers===y.kindModifiers&&k.matchKind===y.matchKind&&k.name===y.name&&k.textSpan.start===y.textSpan.start&&k.textSpan.length===y.textSpan.length}}getSupportedCodeFixes(X){if(!X)return w9$();if(X.file){let{file:G,project:U}=this.getFileAndProject(X);return U.getLanguageService().getSupportedCodeFixes(G)}let K=this.getProject(X.projectFileName);if(!K)XH.ThrowNoProject();return K.getLanguageService().getSupportedCodeFixes()}isLocation(X){return X.line!==void 0}extractPositionOrRange(X,K){let G,U;if(this.isLocation(X))G=B(X);else U=this.getRange(X,K);return m.checkDefined(G===void 0?U:G);function B(V){return V.position!==void 0?V.position:K.lineOffsetToPosition(V.line,V.offset)}}getRange(X,K){let{startPosition:G,endPosition:U}=this.getStartAndEndPosition(X,K);return{pos:G,end:U}}getApplicableRefactors(X){let{file:K,project:G}=this.getFileAndProject(X),U=G.getScriptInfoForNormalizedPath(K);return G.getLanguageService().getApplicableRefactors(K,this.extractPositionOrRange(X,U),this.getPreferences(K),X.triggerReason,X.kind,X.includeInteractiveActions).map((V)=>({...V,actions:V.actions.map((L)=>({...L,range:L.range?{start:RT({line:L.range.start.line,character:L.range.start.offset}),end:RT({line:L.range.end.line,character:L.range.end.offset})}:void 0}))}))}getEditsForRefactor(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=U.getScriptInfoForNormalizedPath(G),V=U.getLanguageService().getEditsForRefactor(G,this.getFormatOptions(G),this.extractPositionOrRange(X,B),X.refactor,X.action,this.getPreferences(G),X.interactiveRefactorArguments);if(V===void 0)return{edits:[]};if(K){let{renameFilename:L,renameLocation:A,edits:_}=V,N;if(L!==void 0&&A!==void 0){let T=U.getScriptInfoForNormalizedPath(WY(L));N=GM$(bN(T.getSnapshot()),L,A,_)}return{renameLocation:N,renameFilename:L,edits:this.mapTextChangesToCodeEdits(_),notApplicableReason:V.notApplicableReason}}return V}getMoveToRefactoringFileSuggestions(X){let{file:K,project:G}=this.getFileAndProject(X),U=G.getScriptInfoForNormalizedPath(K);return G.getLanguageService().getMoveToRefactoringFileSuggestions(K,this.extractPositionOrRange(X,U),this.getPreferences(K))}preparePasteEdits(X){let{file:K,project:G}=this.getFileAndProject(X);return G.getLanguageService().preparePasteEditsForFile(K,X.copiedTextSpan.map((U)=>this.getRange({file:K,startLine:U.start.line,startOffset:U.start.offset,endLine:U.end.line,endOffset:U.end.offset},this.projectService.getScriptInfoForNormalizedPath(K))))}getPasteEdits(X){let{file:K,project:G}=this.getFileAndProject(X);if(sC(K))return;let U=X.copiedFrom?{file:X.copiedFrom.file,range:X.copiedFrom.spans.map((V)=>this.getRange({file:X.copiedFrom.file,startLine:V.start.line,startOffset:V.start.offset,endLine:V.end.line,endOffset:V.end.offset},G.getScriptInfoForNormalizedPath(WY(X.copiedFrom.file))))}:void 0,B=G.getLanguageService().getPasteEdits({targetFile:K,pastedText:X.pastedText,pasteLocations:X.pasteLocations.map((V)=>this.getRange({file:K,startLine:V.start.line,startOffset:V.start.offset,endLine:V.end.line,endOffset:V.end.offset},G.getScriptInfoForNormalizedPath(K))),copiedFrom:U,preferences:this.getPreferences(K)},this.getFormatOptions(K));return B&&this.mapPasteEditsAction(B)}organizeImports(X,K){m.assert(X.scope.type==="file");let{file:G,project:U}=this.getFileAndProject(X.scope.args),B=U.getLanguageService().organizeImports({fileName:G,mode:X.mode??(X.skipDestructiveCodeActions?"SortAndCombine":void 0),type:"file"},this.getFormatOptions(G),this.getPreferences(G));if(K)return this.mapTextChangesToCodeEdits(B);else return B}getEditsForFileRename(X,K){let G=WY(X.oldFilePath),U=WY(X.newFilePath),B=this.getHostFormatOptions(),V=this.getHostPreferences(),L=new Set,A=[];return this.projectService.loadAncestorProjectTree(),this.projectService.forEachEnabledProject((_)=>{let N=_.getLanguageService().getEditsForFileRename(G,U,B,V),T=[];for(let k of N)if(!L.has(k.fileName))A.push(k),T.push(k.fileName);for(let k of T)L.add(k)}),K?A.map((_)=>this.mapTextChangeToCodeEdit(_)):A}getCodeFixes(X,K){let{file:G,project:U}=this.getFileAndProject(X),B=U.getScriptInfoForNormalizedPath(G),{startPosition:V,endPosition:L}=this.getStartAndEndPosition(X,B),A;try{A=U.getLanguageService().getCodeFixesAtPosition(G,V,L,X.errorCodes,this.getFormatOptions(G),this.getPreferences(G))}catch(_){let N=_ instanceof Error?_:Error(_),T=U.getLanguageService(),k=[...T.getSyntacticDiagnostics(G),...T.getSemanticDiagnostics(G),...T.getSuggestionDiagnostics(G)].filter((h)=>xx(V,L-V,h.start,h.length)).map((h)=>h.code),y=X.errorCodes.find((h)=>!k.includes(h));if(y!==void 0)N.message+=`
501
501
  Additional information: BADCLIENT: Bad error code, ${y} not found in range ${V}..${L} (found: ${k.join(", ")})`;throw N}return K?A.map((_)=>this.mapCodeFixAction(_)):A}getCombinedCodeFix({scope:X,fixId:K},G){m.assert(X.type==="file");let{file:U,project:B}=this.getFileAndProject(X.args),V=B.getLanguageService().getCombinedCodeFix({type:"file",fileName:U},K,this.getFormatOptions(U),this.getPreferences(U));if(G)return{changes:this.mapTextChangesToCodeEdits(V.changes),commands:V.commands};else return V}applyCodeActionCommand(X){let K=X.command;for(let G of Xq(K)){let{file:U,project:B}=this.getFileAndProject(G);B.getLanguageService().applyCodeActionCommand(G,this.getFormatOptions(U)).then((V)=>{},(V)=>{})}return{}}getStartAndEndPosition(X,K){let G,U;if(X.startPosition!==void 0)G=X.startPosition;else G=K.lineOffsetToPosition(X.startLine,X.startOffset),X.startPosition=G;if(X.endPosition!==void 0)U=X.endPosition;else U=K.lineOffsetToPosition(X.endLine,X.endOffset),X.endPosition=U;return{startPosition:G,endPosition:U}}mapCodeAction({description:X,changes:K,commands:G}){return{description:X,changes:this.mapTextChangesToCodeEdits(K),commands:G}}mapCodeFixAction({fixName:X,description:K,changes:G,commands:U,fixId:B,fixAllDescription:V}){return{fixName:X,description:K,changes:this.mapTextChangesToCodeEdits(G),commands:U,fixId:B,fixAllDescription:V}}mapPasteEditsAction({edits:X,fixId:K}){return{edits:this.mapTextChangesToCodeEdits(X),fixId:K}}mapTextChangesToCodeEdits(X){return X.map((K)=>this.mapTextChangeToCodeEdit(K))}mapTextChangeToCodeEdit(X){let K=this.projectService.getScriptInfoOrConfig(X.fileName);if(!!X.isNewFile===!!K){if(!K)this.projectService.logErrorForScriptInfoNotFound(X.fileName);m.fail("Expected isNewFile for (only) new files. "+JSON.stringify({isNewFile:!!X.isNewFile,hasScriptInfo:!!K}))}return K?{fileName:X.fileName,textChanges:X.textChanges.map((G)=>Ts6(G,K))}:Ss6(X)}convertTextChangeToCodeEdit(X,K){return{start:K.positionToLineOffset(X.span.start),end:K.positionToLineOffset(X.span.start+X.span.length),newText:X.newText?X.newText:""}}getBraceMatching(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getPosition(X,B),L=U.getBraceMatchingAtPosition(G,V);return!L?void 0:K?L.map((A)=>AU(A,B)):L}getDiagnosticsForProject(X,K,G){if(this.suppressDiagnosticEvents)return;let{fileNames:U,languageServiceDisabled:B}=this.getProjectInfoWorker(G,void 0,!0,void 0,!0);if(B)return;let V=U.filter((u)=>!u.includes("lib.d.ts"));if(V.length===0)return;let L=[],A=[],_=[],N=[],T=WY(G),k=this.projectService.ensureDefaultProjectForFile(T);for(let u of V)if(this.getCanonicalFileName(u)===this.getCanonicalFileName(G))L.push(u);else if(!this.projectService.getScriptInfo(u).isScriptOpen())if(j5(u))N.push(u);else _.push(u);else A.push(u);let h=[...L,...A,..._,...N].map((u)=>({fileName:u,project:k}));this.updateErrorCheck(X,h,K,!1)}configurePlugin(X){this.projectService.configurePlugin(X)}getSmartSelectionRange(X,K){let{locations:G}=X,{file:U,languageService:B}=this.getFileAndLanguageServiceForSyntacticOperation(X),V=m.checkDefined(this.projectService.getScriptInfo(U));return b6(G,(L)=>{let A=this.getPosition(L,V),_=B.getSmartSelectionRange(U,A);return K?this.mapSelectionRange(_,V):_})}toggleLineComment(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=this.projectService.getScriptInfo(G),V=this.getRange(X,B),L=U.toggleLineComment(G,V);if(K){let A=this.projectService.getScriptInfoForNormalizedPath(G);return L.map((_)=>this.convertTextChangeToCodeEdit(_,A))}return L}toggleMultilineComment(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getRange(X,B),L=U.toggleMultilineComment(G,V);if(K){let A=this.projectService.getScriptInfoForNormalizedPath(G);return L.map((_)=>this.convertTextChangeToCodeEdit(_,A))}return L}commentSelection(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getRange(X,B),L=U.commentSelection(G,V);if(K){let A=this.projectService.getScriptInfoForNormalizedPath(G);return L.map((_)=>this.convertTextChangeToCodeEdit(_,A))}return L}uncommentSelection(X,K){let{file:G,languageService:U}=this.getFileAndLanguageServiceForSyntacticOperation(X),B=this.projectService.getScriptInfoForNormalizedPath(G),V=this.getRange(X,B),L=U.uncommentSelection(G,V);if(K){let A=this.projectService.getScriptInfoForNormalizedPath(G);return L.map((_)=>this.convertTextChangeToCodeEdit(_,A))}return L}mapSelectionRange(X,K){let G={textSpan:AU(X.textSpan,K)};if(X.parent)G.parent=this.mapSelectionRange(X.parent,K);return G}getScriptInfoFromProjectService(X){let K=WY(X),G=this.projectService.getScriptInfoForNormalizedPath(K);if(!G)return this.projectService.logErrorForScriptInfoNotFound(K),XH.ThrowNoProject();return G}toProtocolCallHierarchyItem(X){let K=this.getScriptInfoFromProjectService(X.file);return{name:X.name,kind:X.kind,kindModifiers:X.kindModifiers,file:X.file,containerName:X.containerName,span:AU(X.span,K),selectionSpan:AU(X.selectionSpan,K)}}toProtocolCallHierarchyIncomingCall(X){let K=this.getScriptInfoFromProjectService(X.from.file);return{from:this.toProtocolCallHierarchyItem(X.from),fromSpans:X.fromSpans.map((G)=>AU(G,K))}}toProtocolCallHierarchyOutgoingCall(X,K){return{to:this.toProtocolCallHierarchyItem(X.to),fromSpans:X.fromSpans.map((G)=>AU(G,K))}}prepareCallHierarchy(X){let{file:K,project:G}=this.getFileAndProject(X),U=this.projectService.getScriptInfoForNormalizedPath(K);if(U){let B=this.getPosition(X,U),V=G.getLanguageService().prepareCallHierarchy(K,B);return V&&gJ$(V,(L)=>this.toProtocolCallHierarchyItem(L))}return}provideCallHierarchyIncomingCalls(X){let{file:K,project:G}=this.getFileAndProject(X),U=this.getScriptInfoFromProjectService(K);return G.getLanguageService().provideCallHierarchyIncomingCalls(K,this.getPosition(X,U)).map((V)=>this.toProtocolCallHierarchyIncomingCall(V))}provideCallHierarchyOutgoingCalls(X){let{file:K,project:G}=this.getFileAndProject(X),U=this.getScriptInfoFromProjectService(K);return G.getLanguageService().provideCallHierarchyOutgoingCalls(K,this.getPosition(X,U)).map((V)=>this.toProtocolCallHierarchyOutgoingCall(V,U))}getCanonicalFileName(X){let K=this.host.useCaseSensitiveFileNames?X:Tj(X);return y4(K)}exit(){}notRequired(X){if(X)this.doOutput(void 0,X.command,X.seq,!0,this.performanceData);return{responseRequired:!1,performanceData:this.performanceData}}requiredResponse(X){return{response:X,responseRequired:!0,performanceData:this.performanceData}}addProtocolHandler(X,K){if(this.handlers.has(X))throw Error(`Protocol handler already exists for command "${X}"`);this.handlers.set(X,K)}setCurrentRequest(X){m.assert(this.currentRequestId===void 0),this.currentRequestId=X,this.cancellationToken.setRequest(X)}resetCurrentRequest(X){m.assert(this.currentRequestId===X),this.currentRequestId=void 0,this.cancellationToken.resetRequest(X)}executeWithRequestId(X,K,G){let U=this.performanceData;try{return this.performanceData=G,this.setCurrentRequest(X),K()}finally{this.resetCurrentRequest(X),this.performanceData=U}}executeCommand(X){let K=this.handlers.get(X.command);if(K){let G=this.executeWithRequestId(X.seq,()=>K(X),void 0);return this.projectService.enableRequestedPlugins(),G}else return this.logger.msg(`Unrecognized JSON command:${S3(X)}`,"Err"),this.doOutput(void 0,"unknown",X.seq,!1,void 0,`Unrecognized JSON command: ${X.command}`),{responseRequired:!1}}onMessage(X){var K,G,U,B,V,L,A;this.gcTimer.scheduleCollect();let _,N=this.performanceData;if(this.logger.hasLevel(2)){if(_=this.hrtime(),this.logger.hasLevel(3))this.logger.info(`request:${OC(this.toStringMessage(X))}`)}let T,k;try{T=this.parseMessage(X),k=T.arguments&&T.arguments.file?T.arguments:void 0,(K=H8)==null||K.instant(H8.Phase.Session,"request",{seq:T.seq,command:T.command}),(G=H8)==null||G.push(H8.Phase.Session,"executeCommand",{seq:T.seq,command:T.command},!0);let{response:y,responseRequired:h,performanceData:u}=this.executeCommand(T);if((U=H8)==null||U.pop(),this.logger.hasLevel(2)){let l=Fs6(this.hrtime(_)).toFixed(4);if(h)this.logger.perftrc(`${T.seq}::${T.command}: elapsed time (in milliseconds) ${l}`);else this.logger.perftrc(`${T.seq}::${T.command}: async elapsed time (in milliseconds) ${l}`)}if((B=H8)==null||B.instant(H8.Phase.Session,"response",{seq:T.seq,command:T.command,success:!!y}),y)this.doOutput(y,T.command,T.seq,!0,u);else if(h)this.doOutput(void 0,T.command,T.seq,!1,u,"No content available.")}catch(y){if((V=H8)==null||V.popAll(),y instanceof Dw){(L=H8)==null||L.instant(H8.Phase.Session,"commandCanceled",{seq:T==null?void 0:T.seq,command:T==null?void 0:T.command}),this.doOutput({canceled:!0},T.command,T.seq,!0,this.performanceData);return}this.logErrorWorker(y,this.toStringMessage(X),k),(A=H8)==null||A.instant(H8.Phase.Session,"commandError",{seq:T==null?void 0:T.seq,command:T==null?void 0:T.command,message:y.message}),this.doOutput(void 0,T?T.command:"unknown",T?T.seq:0,!1,this.performanceData,"Error processing request. "+y.message+`
502
- `+y.stack)}finally{this.performanceData=N}}parseMessage(X){return JSON.parse(X)}toStringMessage(X){return X}getFormatOptions(X){return this.projectService.getFormatCodeOptions(X)}getPreferences(X){return this.projectService.getPreferences(X)}getHostFormatOptions(){return this.projectService.getHostFormatCodeOptions()}getHostPreferences(){return this.projectService.getHostPreferences()}};function W86($){let X=$.diagnosticsDuration&&F9($.diagnosticsDuration,([K,G])=>({...G,file:K}));return{...$,diagnosticsDuration:X}}function AU($,X){return{start:X.positionToLineOffset($.start),end:X.positionToLineOffset(HQ($))}}function ZM$($,X,K){let G=AU($,K),U=X&&AU(X,K);return U?{...G,contextStart:U.start,contextEnd:U.end}:G}function Ts6($,X){return{start:z86(X,$.span.start),end:z86(X,HQ($.span)),newText:$.newText}}function z86($,X){return eP$($)?ws6($.getLineAndCharacterOfPosition(X)):$.positionToLineOffset(X)}function Rs6($,X){let K=$.ranges.map((G)=>{return{start:X.positionToLineOffset(G.start),end:X.positionToLineOffset(G.start+G.length)}});if(!$.wordPattern)return{ranges:K};return{ranges:K,wordPattern:$.wordPattern}}function ws6($){return{line:$.line+1,offset:$.character+1}}function Ss6($){m.assert($.textChanges.length===1);let X=_4($.textChanges);return m.assert(X.span.start===0&&X.span.length===0),{fileName:$.fileName,textChanges:[{start:{line:0,offset:0},end:{line:0,offset:0},newText:X.newText}]}}function GM$($,X,K,G){let U=Cs6($,X,G),{line:B,character:V}=dE(NM(U),K);return{line:B+1,offset:V+1}}function Cs6($,X,K){for(let{fileName:G,textChanges:U}of K){if(G!==X)continue;for(let B=U.length-1;B>=0;B--){let{newText:V,span:{start:L,length:A}}=U[B];$=$.slice(0,L)+V+$.slice(L+A)}}return $}function U86($,{fileName:X,textSpan:K,contextSpan:G,isWriteAccess:U,isDefinition:B},{disableLineTextInReferences:V}){let L=m.checkDefined($.getScriptInfo(X)),A=ZM$(K,G,L),_=V?void 0:bs6(L,A);return{file:X,...A,lineText:_,isWriteAccess:U,isDefinition:B}}function bs6($,X){let K=$.lineToTextSpan(X.start.line-1);return $.getSnapshot().getText(K.start,HQ(K)).replace(/\r|\n/g,"")}function ks6($){return $===void 0||$&&typeof $==="object"&&typeof $.exportName==="string"&&($.fileName===void 0||typeof $.fileName==="string")&&($.ambientModuleName===void 0||typeof $.ambientModuleName==="string"&&($.isPackageJsonImport===void 0||typeof $.isPackageJsonImport==="boolean"))}var wT=4,WM$=(($)=>{return $[$.PreStart=0]="PreStart",$[$.Start=1]="Start",$[$.Entire=2]="Entire",$[$.Mid=3]="Mid",$[$.End=4]="End",$[$.PostEnd=5]="PostEnd",$})(WM$||{}),xs6=class{constructor(){this.goSubtree=!0,this.lineIndex=new Nh,this.endBranch=[],this.state=2,this.initialText="",this.trailingText="",this.lineIndex.root=new ST,this.startPath=[this.lineIndex.root],this.stack=[this.lineIndex.root]}get done(){return!1}insertLines($,X){if(X)this.trailingText="";if($)$=this.initialText+$+this.trailingText;else $=this.initialText+this.trailingText;let G=Nh.linesFromText($).lines;if(G.length>1&&G[G.length-1]==="")G.pop();let U,B;for(let L=this.endBranch.length-1;L>=0;L--)if(this.endBranch[L].updateCounts(),this.endBranch[L].charCount()===0)if(B=this.endBranch[L],L>0)U=this.endBranch[L-1];else U=this.branchNode;if(B)U.remove(B);let V=this.startPath[this.startPath.length-1];if(G.length>0)if(V.text=G[0],G.length>1){let L=Array(G.length-1),A=V;for(let T=1;T<G.length;T++)L[T-1]=new Dr(G[T]);let _=this.startPath.length-2;while(_>=0){let T=this.startPath[_];L=T.insertAt(A,L),_--,A=T}let N=L.length;while(N>0){let T=new ST;T.add(this.lineIndex.root),L=T.insertAt(this.lineIndex.root,L),N=L.length,this.lineIndex.root=T}this.lineIndex.root.updateCounts()}else for(let L=this.startPath.length-2;L>=0;L--)this.startPath[L].updateCounts();else{this.startPath[this.startPath.length-2].remove(V);for(let A=this.startPath.length-2;A>=0;A--)this.startPath[A].updateCounts()}return this.lineIndex}post($,X,K){if(K===this.lineCollectionAtBranch)this.state=4;this.stack.pop()}pre($,X,K,G,U){let B=this.stack[this.stack.length-1];if(this.state===2&&U===1)this.state=1,this.branchNode=B,this.lineCollectionAtBranch=K;let V;function L(A){if(A.isLeaf())return new Dr("");else return new ST}switch(U){case 0:if(this.goSubtree=!1,this.state!==4)B.add(K);break;case 1:if(this.state===4)this.goSubtree=!1;else V=L(K),B.add(V),this.startPath.push(V);break;case 2:if(this.state!==4)V=L(K),B.add(V),this.startPath.push(V);else if(!K.isLeaf())V=L(K),B.add(V),this.endBranch.push(V);break;case 3:this.goSubtree=!1;break;case 4:if(this.state!==4)this.goSubtree=!1;else if(!K.isLeaf())V=L(K),B.add(V),this.endBranch.push(V);break;case 5:if(this.goSubtree=!1,this.state!==1)B.add(K);break}if(this.goSubtree)this.stack.push(V)}leaf($,X,K){if(this.state===1)this.initialText=K.text.substring(0,$);else if(this.state===2)this.initialText=K.text.substring(0,$),this.trailingText=K.text.substring($+X);else this.trailingText=K.text.substring($+X)}},ys6=class{constructor($,X,K){this.pos=$,this.deleteLen=X,this.insertedText=K}getTextChangeRange(){return yx(k5(this.pos,this.deleteLen),this.insertedText?this.insertedText.length:0)}},HX$=class ${constructor(){this.changes=[],this.versions=Array($.maxVersions),this.minVersion=0,this.currentVersion=0}versionToIndex(X){if(X<this.minVersion||X>this.currentVersion)return;return X%$.maxVersions}currentVersionToIndex(){return this.currentVersion%$.maxVersions}edit(X,K,G){if(this.changes.push(new ys6(X,K,G)),this.changes.length>$.changeNumberThreshold||K>$.changeLengthThreshold||G&&G.length>$.changeLengthThreshold)this.getSnapshot()}getSnapshot(){return this._getSnapshot()}_getSnapshot(){let X=this.versions[this.currentVersionToIndex()];if(this.changes.length>0){let K=X.index;for(let G of this.changes)K=K.edit(G.pos,G.deleteLen,G.insertedText);if(X=new j86(this.currentVersion+1,this,K,this.changes),this.currentVersion=X.version,this.versions[this.currentVersionToIndex()]=X,this.changes=[],this.currentVersion-this.minVersion>=$.maxVersions)this.minVersion=this.currentVersion-$.maxVersions+1}return X}getSnapshotVersion(){return this._getSnapshot().version}getAbsolutePositionAndLineText(X){return this._getSnapshot().index.lineNumberToInfo(X)}lineOffsetToPosition(X,K){return this._getSnapshot().index.absolutePositionOfStartOfLine(X)+(K-1)}positionToLineOffset(X){return this._getSnapshot().index.positionToLineOffset(X)}lineToTextSpan(X){let K=this._getSnapshot().index,{lineText:G,absolutePosition:U}=K.lineNumberToInfo(X+1),B=G!==void 0?G.length:K.absolutePositionOfStartOfLine(X+2)-U;return k5(U,B)}getTextChangesBetweenVersions(X,K){if(X<K)if(X>=this.minVersion){let G=[];for(let U=X+1;U<=K;U++){let B=this.versions[this.versionToIndex(U)];for(let V of B.changesSincePreviousVersion)G.push(V.getTextChangeRange())}return pW$(G)}else return;else return du}getLineCount(){return this._getSnapshot().index.getLineCount()}static fromString(X){let K=new $,G=new j86(0,K,new Nh);K.versions[K.currentVersion]=G;let U=Nh.linesFromText(X);return G.index.load(U.lines),K}};HX$.changeNumberThreshold=8,HX$.changeLengthThreshold=256,HX$.maxVersions=8;var VX$=HX$,j86=class ${constructor(X,K,G,U=r7){this.version=X,this.cache=K,this.index=G,this.changesSincePreviousVersion=U}getText(X,K){return this.index.getText(X,K-X)}getLength(){return this.index.getLength()}getChangeRange(X){if(X instanceof $&&this.cache===X.cache)if(this.version<=X.version)return du;else return this.cache.getTextChangesBetweenVersions(X.version,this.version)}},Nh=class ${constructor(){this.checkEdits=!1}absolutePositionOfStartOfLine(X){return this.lineNumberToInfo(X).absolutePosition}positionToLineOffset(X){let{oneBasedLine:K,zeroBasedColumn:G}=this.root.charOffsetToLineInfo(1,X);return{line:K,offset:G+1}}positionToColumnAndLineText(X){return this.root.charOffsetToLineInfo(1,X)}getLineCount(){return this.root.lineCount()}lineNumberToInfo(X){let K=this.getLineCount();if(X<=K){let{position:G,leaf:U}=this.root.lineNumberToInfo(X,0);return{absolutePosition:G,lineText:U&&U.text}}else return{absolutePosition:this.root.charCount(),lineText:void 0}}load(X){if(X.length>0){let K=[];for(let G=0;G<X.length;G++)K[G]=new Dr(X[G]);this.root=$.buildTreeFromBottom(K)}else this.root=new ST}walk(X,K,G){this.root.walk(X,K,G)}getText(X,K){let G="";if(K>0&&X<this.root.charCount())this.walk(X,K,{goSubtree:!0,done:!1,leaf:(U,B,V)=>{G=G.concat(V.text.substring(U,U+B))}});return G}getLength(){return this.root.charCount()}every(X,K,G){if(!G)G=this.root.charCount();let U={goSubtree:!0,done:!1,leaf(B,V,L){if(!X(L,B,V))this.done=!0}};return this.walk(K,G-K,U),!U.done}edit(X,K,G){if(this.root.charCount()===0){if(m.assert(K===0),G!==void 0)return this.load($.linesFromText(G).lines),this;return}else{let U;if(this.checkEdits){let L=this.getText(0,this.root.charCount());U=L.slice(0,X)+G+L.slice(X+K)}let B=new xs6,V=!1;if(X>=this.root.charCount()){X=this.root.charCount()-1;let L=this.getText(X,1);if(G)G=L+G;else G=L;K=0,V=!0}else if(K>0){let L=X+K,{zeroBasedColumn:A,lineText:_}=this.positionToColumnAndLineText(L);if(A===0)K+=_.length,G=G?G+_:_}if(this.root.walk(X,K,B),B.insertLines(G,V),this.checkEdits){let L=B.lineIndex.getText(0,B.lineIndex.getLength());m.assert(U===L,"buffer edit mismatch")}return B.lineIndex}}static buildTreeFromBottom(X){if(X.length<wT)return new ST(X);let K=Array(Math.ceil(X.length/wT)),G=0;for(let U=0;U<K.length;U++){let B=Math.min(G+wT,X.length);K[U]=new ST(X.slice(G,B)),G=B}return this.buildTreeFromBottom(K)}static linesFromText(X){let K=NM(X);if(K.length===0)return{lines:[],lineMap:K};let G=Array(K.length),U=K.length-1;for(let V=0;V<U;V++)G[V]=X.substring(K[V],K[V+1]);let B=X.substring(K[U]);if(B.length>0)G[U]=B;else G.pop();return{lines:G,lineMap:K}}},ST=class ${constructor(X=[]){if(this.children=X,this.totalChars=0,this.totalLines=0,X.length)this.updateCounts()}isLeaf(){return!1}updateCounts(){this.totalChars=0,this.totalLines=0;for(let X of this.children)this.totalChars+=X.charCount(),this.totalLines+=X.lineCount()}execWalk(X,K,G,U,B){if(G.pre)G.pre(X,K,this.children[U],this,B);if(G.goSubtree){if(this.children[U].walk(X,K,G),G.post)G.post(X,K,this.children[U],this,B)}else G.goSubtree=!0;return G.done}skipChild(X,K,G,U,B){if(U.pre&&!U.done)U.pre(X,K,this.children[G],this,B),U.goSubtree=!0}walk(X,K,G){if(this.children.length===0)return;let U=0,B=this.children[U].charCount(),V=X;while(V>=B)this.skipChild(V,K,U,G,0),V-=B,U++,B=this.children[U].charCount();if(V+K<=B){if(this.execWalk(V,K,G,U,2))return}else{if(this.execWalk(V,B-V,G,U,1))return;let L=K-(B-V);U++,B=this.children[U].charCount();while(L>B){if(this.execWalk(0,B,G,U,3))return;L-=B,U++,B=this.children[U].charCount()}if(L>0){if(this.execWalk(0,L,G,U,4))return}}if(G.pre){let L=this.children.length;if(U<L-1)for(let A=U+1;A<L;A++)this.skipChild(0,0,A,G,5)}}charOffsetToLineInfo(X,K){if(this.children.length===0)return{oneBasedLine:X,zeroBasedColumn:K,lineText:void 0};for(let B of this.children)if(B.charCount()>K)if(B.isLeaf())return{oneBasedLine:X,zeroBasedColumn:K,lineText:B.text};else return B.charOffsetToLineInfo(X,K);else K-=B.charCount(),X+=B.lineCount();let G=this.lineCount();if(G===0)return{oneBasedLine:1,zeroBasedColumn:0,lineText:void 0};let U=m.checkDefined(this.lineNumberToInfo(G,0).leaf);return{oneBasedLine:G,zeroBasedColumn:U.charCount(),lineText:void 0}}lineNumberToInfo(X,K){for(let G of this.children){let U=G.lineCount();if(U>=X)return G.isLeaf()?{position:K,leaf:G}:G.lineNumberToInfo(X,K);else X-=U,K+=G.charCount()}return{position:K,leaf:void 0}}splitAfter(X){let K,G=this.children.length;X++;let U=X;if(X<G){K=new $;while(X<G)K.add(this.children[X]),X++;K.updateCounts()}return this.children.length=U,K}remove(X){let K=this.findChildIndex(X),G=this.children.length;if(K<G-1)for(let U=K;U<G-1;U++)this.children[U]=this.children[U+1];this.children.pop()}findChildIndex(X){let K=this.children.indexOf(X);return m.assert(K!==-1),K}insertAt(X,K){let G=this.findChildIndex(X),U=this.children.length,B=K.length;if(U<wT&&G===U-1&&B===1)return this.add(K[0]),this.updateCounts(),[];else{let V=this.splitAfter(G),L=0;G++;while(G<wT&&L<B)this.children[G]=K[L],G++,L++;let A=[],_=0;if(L<B){_=Math.ceil((B-L)/wT),A=Array(_);let N=0;for(let k=0;k<_;k++)A[k]=new $;let T=A[0];while(L<B)if(T.add(K[L]),L++,T.children.length===wT)N++,T=A[N];for(let k=A.length-1;k>=0;k--)if(A[k].children.length===0)A.pop()}if(V)A.push(V);this.updateCounts();for(let N=0;N<_;N++)A[N].updateCounts();return A}}add(X){this.children.push(X),m.assert(this.children.length<=wT)}charCount(){return this.totalChars}lineCount(){return this.totalLines}},Dr=class{constructor($){this.text=$}isLeaf(){return!0}walk($,X,K){K.leaf($,X,this)}charCount(){return this.text.length}lineCount(){return 1}},B86=class ${constructor(X,K,G,U,B,V){this.telemetryEnabled=X,this.logger=K,this.host=G,this.globalTypingsCacheLocation=U,this.event=B,this.maxActiveRequestCount=V,this.activeRequestCount=0,this.requestQueue=fU(),this.requestMap=new Map,this.requestedRegistry=!1,this.packageInstallId=0}isKnownTypesPackageName(X){var K;if(lq.validatePackageName(X)!==lq.NameValidationResult.Ok)return!1;if(!this.requestedRegistry)this.requestedRegistry=!0,this.installer.send({kind:"typesRegistry"});return!!((K=this.typesRegistryCache)==null?void 0:K.has(X))}installPackage(X){this.packageInstallId++;let K={kind:"installPackage",...X,id:this.packageInstallId},G=new Promise((U,B)=>{(this.packageInstalledPromise??(this.packageInstalledPromise=new Map)).set(this.packageInstallId,{resolve:U,reject:B})});return this.installer.send(K),G}attach(X){this.projectService=X,this.installer=this.createInstallerProcess()}onProjectClosed(X){this.installer.send({projectName:X.getProjectName(),kind:"closeProject"})}enqueueInstallTypingsRequest(X,K,G){let U=qP$(X,K,G);if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Scheduling throttled operation:${S3(U)}`);if(this.activeRequestCount<this.maxActiveRequestCount)this.scheduleRequest(U);else{if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Deferring request for: ${U.projectName}`);this.requestQueue.enqueue(U),this.requestMap.set(U.projectName,U)}}handleMessage(X){var K,G;if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Received response:${S3(X)}`);switch(X.kind){case h8$:this.typesRegistryCache=new Map(Object.entries(X.typesRegistry));break;case yp:{let U=(K=this.packageInstalledPromise)==null?void 0:K.get(X.id);if(m.assertIsDefined(U,"Should find the promise for package install"),(G=this.packageInstalledPromise)==null||G.delete(X.id),X.success)U.resolve({successMessage:X.message});else U.reject(X.message);this.projectService.updateTypingsForProject(X),this.event(X,"setTypings");break}case PD$:{let U={message:X.message},B="typesInstallerInitializationFailed";this.event(U,"typesInstallerInitializationFailed");break}case g8$:{let U={eventId:X.eventId,packages:X.packagesToInstall},B="beginInstallTypes";this.event(U,"beginInstallTypes");break}case m8$:{if(this.telemetryEnabled){let V={telemetryEventName:"typingsInstalled",payload:{installedPackages:X.packagesToInstall.join(","),installSuccess:X.installSuccess,typingsInstallerVersion:X.typingsInstallerVersion}},L="telemetry";this.event(V,"telemetry")}let U={eventId:X.eventId,packages:X.packagesToInstall,success:X.installSuccess},B="endInstallTypes";this.event(U,B);break}case xp:{this.projectService.updateTypingsForProject(X);break}case kp:{if(this.activeRequestCount>0)this.activeRequestCount--;else m.fail("TIAdapter:: Received too many responses");while(!this.requestQueue.isEmpty()){let U=this.requestQueue.dequeue();if(this.requestMap.get(U.projectName)===U){this.requestMap.delete(U.projectName),this.scheduleRequest(U);break}if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Skipping defunct request for: ${U.projectName}`)}this.projectService.updateTypingsForProject(X),this.event(X,"setTypings");break}case Av:this.projectService.watchTypingLocations(X);break;default:xB(X)}}scheduleRequest(X){if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Scheduling request for: ${X.projectName}`);this.activeRequestCount++,this.host.setTimeout(()=>{if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Sending request:${S3(X)}`);this.installer.send(X)},$.requestDelayMillis,`${X.projectName}::${X.kind}`)}};B86.requestDelayMillis=100;var H86=B86,V86={};if(H(V86,{ActionInvalidate:()=>xp,ActionPackageInstalled:()=>yp,ActionSet:()=>kp,ActionWatchTypingLocations:()=>Av,Arguments:()=>u8$,AutoImportProviderProject:()=>fP$,AuxiliaryProject:()=>xP$,CharRangeSection:()=>WM$,CloseFileWatcherEvent:()=>XX$,CommandNames:()=>e16,ConfigFileDiagEvent:()=>o4$,ConfiguredProject:()=>vP$,ConfiguredProjectLoadKind:()=>dP$,CreateDirectoryWatcherEvent:()=>JX$,CreateFileWatcherEvent:()=>$X$,Errors:()=>XH,EventBeginInstallTypes:()=>g8$,EventEndInstallTypes:()=>m8$,EventInitializationFailed:()=>PD$,EventTypesRegistry:()=>h8$,ExternalProject:()=>p4$,GcTimer:()=>MP$,InferredProject:()=>kP$,LargeFileReferencedEvent:()=>n4$,LineIndex:()=>Nh,LineLeaf:()=>Dr,LineNode:()=>ST,LogLevel:()=>HP$,Msg:()=>VP$,OpenFileInfoTelemetryEvent:()=>hP$,Project:()=>iN,ProjectInfoTelemetryEvent:()=>e4$,ProjectKind:()=>aC,ProjectLanguageServiceStateEvent:()=>t4$,ProjectLoadingFinishEvent:()=>a4$,ProjectLoadingStartEvent:()=>s4$,ProjectService:()=>tP$,ProjectsUpdatedInBackgroundEvent:()=>Hr,ScriptInfo:()=>_P$,ScriptVersionCache:()=>VX$,Session:()=>G86,TextStorage:()=>EP$,ThrottledOperations:()=>PP$,TypingsInstallerAdapter:()=>H86,allFilesAreJsOrDts:()=>SP$,allRootFilesAreJsOrDts:()=>wP$,asNormalizedPath:()=>FU,convertCompilerOptions:()=>Vr,convertFormatOptions:()=>TT,convertScriptKindName:()=>QX$,convertTypeAcquisition:()=>mP$,convertUserPreferences:()=>uP$,convertWatchOptions:()=>Ph,countEachFileTypes:()=>Fh,createInstallTypingsRequest:()=>qP$,createModuleSpecifierCache:()=>JM$,createNormalizedPathMap:()=>_16,createPackageJsonCache:()=>XM$,createSortedArray:()=>OP$,emptyArray:()=>r7,findArgument:()=>Ti$,formatDiagnosticToProtocol:()=>Mh,formatMessage:()=>YM$,getBaseConfigFileName:()=>l4$,getDetailWatchInfo:()=>WX$,getLocationInNewDocument:()=>GM$,hasArgument:()=>_i$,hasNoTypeScriptSource:()=>CP$,indent:()=>OC,isBackgroundProject:()=>Lh,isConfigFile:()=>eP$,isConfiguredProject:()=>qV,isDynamicFileName:()=>sC,isExternalProject:()=>Ah,isInferredProject:()=>_T,isInferredProjectName:()=>DP$,isProjectDeferredClose:()=>Oh,makeAutoImportProviderProjectName:()=>AP$,makeAuxiliaryProjectName:()=>LP$,makeInferredProjectName:()=>FP$,maxFileSize:()=>r4$,maxProgramSizeForNonTsFiles:()=>i4$,normalizedPathToPath:()=>ET,nowString:()=>Ri$,nullCancellationToken:()=>n16,nullTypingsInstaller:()=>qr,protocol:()=>NP$,scriptInfoIsContainedByBackgroundProject:()=>TP$,scriptInfoIsContainedByDeferredClosedProject:()=>RP$,stringifyIndented:()=>S3,toEvent:()=>QM$,toNormalizedPath:()=>WY,tryConvertScriptKindName:()=>YX$,typingsInstaller:()=>BP$,updateProjectIfDirty:()=>qW}),typeof console<"u")m.loggingHost={log($,X){switch($){case 1:return console.error(X);case 2:return console.warn(X);case 3:return console.log(X);case 4:return console.log(X)}}}})({get exports(){return lj6},set exports(J){if(lj6=J,typeof s5$<"u"&&s5$.exports)s5$.exports=J}})});import{readFileSync as eP0}from"fs";import{resolve as $M0,dirname as JM0}from"path";import{parse as XM0,compileScript as YM0,compileTemplate as QM0}from"@vue/compiler-sfc";function aj6(){o5$.clear()}async function t5$(J,Y,Z,W={}){let z=Y?`${J}::${WM0(Z)}`:null;if(z&&o5$.has(z))return o5$.get(z);let H=eP0(J,"utf-8"),F=await FS$(H,J,Y,Z,W);if(z)o5$.set(z,F);return F}async function FS$(J,Y,Z,W,z={}){let{descriptor:H,errors:F}=XM0(J,{filename:Y});if(F.length)throw Error(`@axon/vstr: parse errors in ${Y}:
502
+ `+y.stack)}finally{this.performanceData=N}}parseMessage(X){return JSON.parse(X)}toStringMessage(X){return X}getFormatOptions(X){return this.projectService.getFormatCodeOptions(X)}getPreferences(X){return this.projectService.getPreferences(X)}getHostFormatOptions(){return this.projectService.getHostFormatCodeOptions()}getHostPreferences(){return this.projectService.getHostPreferences()}};function W86($){let X=$.diagnosticsDuration&&F9($.diagnosticsDuration,([K,G])=>({...G,file:K}));return{...$,diagnosticsDuration:X}}function AU($,X){return{start:X.positionToLineOffset($.start),end:X.positionToLineOffset(HQ($))}}function ZM$($,X,K){let G=AU($,K),U=X&&AU(X,K);return U?{...G,contextStart:U.start,contextEnd:U.end}:G}function Ts6($,X){return{start:z86(X,$.span.start),end:z86(X,HQ($.span)),newText:$.newText}}function z86($,X){return eP$($)?ws6($.getLineAndCharacterOfPosition(X)):$.positionToLineOffset(X)}function Rs6($,X){let K=$.ranges.map((G)=>{return{start:X.positionToLineOffset(G.start),end:X.positionToLineOffset(G.start+G.length)}});if(!$.wordPattern)return{ranges:K};return{ranges:K,wordPattern:$.wordPattern}}function ws6($){return{line:$.line+1,offset:$.character+1}}function Ss6($){m.assert($.textChanges.length===1);let X=_4($.textChanges);return m.assert(X.span.start===0&&X.span.length===0),{fileName:$.fileName,textChanges:[{start:{line:0,offset:0},end:{line:0,offset:0},newText:X.newText}]}}function GM$($,X,K,G){let U=Cs6($,X,G),{line:B,character:V}=dE(NM(U),K);return{line:B+1,offset:V+1}}function Cs6($,X,K){for(let{fileName:G,textChanges:U}of K){if(G!==X)continue;for(let B=U.length-1;B>=0;B--){let{newText:V,span:{start:L,length:A}}=U[B];$=$.slice(0,L)+V+$.slice(L+A)}}return $}function U86($,{fileName:X,textSpan:K,contextSpan:G,isWriteAccess:U,isDefinition:B},{disableLineTextInReferences:V}){let L=m.checkDefined($.getScriptInfo(X)),A=ZM$(K,G,L),_=V?void 0:bs6(L,A);return{file:X,...A,lineText:_,isWriteAccess:U,isDefinition:B}}function bs6($,X){let K=$.lineToTextSpan(X.start.line-1);return $.getSnapshot().getText(K.start,HQ(K)).replace(/\r|\n/g,"")}function ks6($){return $===void 0||$&&typeof $==="object"&&typeof $.exportName==="string"&&($.fileName===void 0||typeof $.fileName==="string")&&($.ambientModuleName===void 0||typeof $.ambientModuleName==="string"&&($.isPackageJsonImport===void 0||typeof $.isPackageJsonImport==="boolean"))}var wT=4,WM$=(($)=>{return $[$.PreStart=0]="PreStart",$[$.Start=1]="Start",$[$.Entire=2]="Entire",$[$.Mid=3]="Mid",$[$.End=4]="End",$[$.PostEnd=5]="PostEnd",$})(WM$||{}),xs6=class{constructor(){this.goSubtree=!0,this.lineIndex=new Nh,this.endBranch=[],this.state=2,this.initialText="",this.trailingText="",this.lineIndex.root=new ST,this.startPath=[this.lineIndex.root],this.stack=[this.lineIndex.root]}get done(){return!1}insertLines($,X){if(X)this.trailingText="";if($)$=this.initialText+$+this.trailingText;else $=this.initialText+this.trailingText;let G=Nh.linesFromText($).lines;if(G.length>1&&G[G.length-1]==="")G.pop();let U,B;for(let L=this.endBranch.length-1;L>=0;L--)if(this.endBranch[L].updateCounts(),this.endBranch[L].charCount()===0)if(B=this.endBranch[L],L>0)U=this.endBranch[L-1];else U=this.branchNode;if(B)U.remove(B);let V=this.startPath[this.startPath.length-1];if(G.length>0)if(V.text=G[0],G.length>1){let L=Array(G.length-1),A=V;for(let T=1;T<G.length;T++)L[T-1]=new Dr(G[T]);let _=this.startPath.length-2;while(_>=0){let T=this.startPath[_];L=T.insertAt(A,L),_--,A=T}let N=L.length;while(N>0){let T=new ST;T.add(this.lineIndex.root),L=T.insertAt(this.lineIndex.root,L),N=L.length,this.lineIndex.root=T}this.lineIndex.root.updateCounts()}else for(let L=this.startPath.length-2;L>=0;L--)this.startPath[L].updateCounts();else{this.startPath[this.startPath.length-2].remove(V);for(let A=this.startPath.length-2;A>=0;A--)this.startPath[A].updateCounts()}return this.lineIndex}post($,X,K){if(K===this.lineCollectionAtBranch)this.state=4;this.stack.pop()}pre($,X,K,G,U){let B=this.stack[this.stack.length-1];if(this.state===2&&U===1)this.state=1,this.branchNode=B,this.lineCollectionAtBranch=K;let V;function L(A){if(A.isLeaf())return new Dr("");else return new ST}switch(U){case 0:if(this.goSubtree=!1,this.state!==4)B.add(K);break;case 1:if(this.state===4)this.goSubtree=!1;else V=L(K),B.add(V),this.startPath.push(V);break;case 2:if(this.state!==4)V=L(K),B.add(V),this.startPath.push(V);else if(!K.isLeaf())V=L(K),B.add(V),this.endBranch.push(V);break;case 3:this.goSubtree=!1;break;case 4:if(this.state!==4)this.goSubtree=!1;else if(!K.isLeaf())V=L(K),B.add(V),this.endBranch.push(V);break;case 5:if(this.goSubtree=!1,this.state!==1)B.add(K);break}if(this.goSubtree)this.stack.push(V)}leaf($,X,K){if(this.state===1)this.initialText=K.text.substring(0,$);else if(this.state===2)this.initialText=K.text.substring(0,$),this.trailingText=K.text.substring($+X);else this.trailingText=K.text.substring($+X)}},ys6=class{constructor($,X,K){this.pos=$,this.deleteLen=X,this.insertedText=K}getTextChangeRange(){return yx(k5(this.pos,this.deleteLen),this.insertedText?this.insertedText.length:0)}},HX$=class ${constructor(){this.changes=[],this.versions=Array($.maxVersions),this.minVersion=0,this.currentVersion=0}versionToIndex(X){if(X<this.minVersion||X>this.currentVersion)return;return X%$.maxVersions}currentVersionToIndex(){return this.currentVersion%$.maxVersions}edit(X,K,G){if(this.changes.push(new ys6(X,K,G)),this.changes.length>$.changeNumberThreshold||K>$.changeLengthThreshold||G&&G.length>$.changeLengthThreshold)this.getSnapshot()}getSnapshot(){return this._getSnapshot()}_getSnapshot(){let X=this.versions[this.currentVersionToIndex()];if(this.changes.length>0){let K=X.index;for(let G of this.changes)K=K.edit(G.pos,G.deleteLen,G.insertedText);if(X=new j86(this.currentVersion+1,this,K,this.changes),this.currentVersion=X.version,this.versions[this.currentVersionToIndex()]=X,this.changes=[],this.currentVersion-this.minVersion>=$.maxVersions)this.minVersion=this.currentVersion-$.maxVersions+1}return X}getSnapshotVersion(){return this._getSnapshot().version}getAbsolutePositionAndLineText(X){return this._getSnapshot().index.lineNumberToInfo(X)}lineOffsetToPosition(X,K){return this._getSnapshot().index.absolutePositionOfStartOfLine(X)+(K-1)}positionToLineOffset(X){return this._getSnapshot().index.positionToLineOffset(X)}lineToTextSpan(X){let K=this._getSnapshot().index,{lineText:G,absolutePosition:U}=K.lineNumberToInfo(X+1),B=G!==void 0?G.length:K.absolutePositionOfStartOfLine(X+2)-U;return k5(U,B)}getTextChangesBetweenVersions(X,K){if(X<K)if(X>=this.minVersion){let G=[];for(let U=X+1;U<=K;U++){let B=this.versions[this.versionToIndex(U)];for(let V of B.changesSincePreviousVersion)G.push(V.getTextChangeRange())}return pW$(G)}else return;else return du}getLineCount(){return this._getSnapshot().index.getLineCount()}static fromString(X){let K=new $,G=new j86(0,K,new Nh);K.versions[K.currentVersion]=G;let U=Nh.linesFromText(X);return G.index.load(U.lines),K}};HX$.changeNumberThreshold=8,HX$.changeLengthThreshold=256,HX$.maxVersions=8;var VX$=HX$,j86=class ${constructor(X,K,G,U=r7){this.version=X,this.cache=K,this.index=G,this.changesSincePreviousVersion=U}getText(X,K){return this.index.getText(X,K-X)}getLength(){return this.index.getLength()}getChangeRange(X){if(X instanceof $&&this.cache===X.cache)if(this.version<=X.version)return du;else return this.cache.getTextChangesBetweenVersions(X.version,this.version)}},Nh=class ${constructor(){this.checkEdits=!1}absolutePositionOfStartOfLine(X){return this.lineNumberToInfo(X).absolutePosition}positionToLineOffset(X){let{oneBasedLine:K,zeroBasedColumn:G}=this.root.charOffsetToLineInfo(1,X);return{line:K,offset:G+1}}positionToColumnAndLineText(X){return this.root.charOffsetToLineInfo(1,X)}getLineCount(){return this.root.lineCount()}lineNumberToInfo(X){let K=this.getLineCount();if(X<=K){let{position:G,leaf:U}=this.root.lineNumberToInfo(X,0);return{absolutePosition:G,lineText:U&&U.text}}else return{absolutePosition:this.root.charCount(),lineText:void 0}}load(X){if(X.length>0){let K=[];for(let G=0;G<X.length;G++)K[G]=new Dr(X[G]);this.root=$.buildTreeFromBottom(K)}else this.root=new ST}walk(X,K,G){this.root.walk(X,K,G)}getText(X,K){let G="";if(K>0&&X<this.root.charCount())this.walk(X,K,{goSubtree:!0,done:!1,leaf:(U,B,V)=>{G=G.concat(V.text.substring(U,U+B))}});return G}getLength(){return this.root.charCount()}every(X,K,G){if(!G)G=this.root.charCount();let U={goSubtree:!0,done:!1,leaf(B,V,L){if(!X(L,B,V))this.done=!0}};return this.walk(K,G-K,U),!U.done}edit(X,K,G){if(this.root.charCount()===0){if(m.assert(K===0),G!==void 0)return this.load($.linesFromText(G).lines),this;return}else{let U;if(this.checkEdits){let L=this.getText(0,this.root.charCount());U=L.slice(0,X)+G+L.slice(X+K)}let B=new xs6,V=!1;if(X>=this.root.charCount()){X=this.root.charCount()-1;let L=this.getText(X,1);if(G)G=L+G;else G=L;K=0,V=!0}else if(K>0){let L=X+K,{zeroBasedColumn:A,lineText:_}=this.positionToColumnAndLineText(L);if(A===0)K+=_.length,G=G?G+_:_}if(this.root.walk(X,K,B),B.insertLines(G,V),this.checkEdits){let L=B.lineIndex.getText(0,B.lineIndex.getLength());m.assert(U===L,"buffer edit mismatch")}return B.lineIndex}}static buildTreeFromBottom(X){if(X.length<wT)return new ST(X);let K=Array(Math.ceil(X.length/wT)),G=0;for(let U=0;U<K.length;U++){let B=Math.min(G+wT,X.length);K[U]=new ST(X.slice(G,B)),G=B}return this.buildTreeFromBottom(K)}static linesFromText(X){let K=NM(X);if(K.length===0)return{lines:[],lineMap:K};let G=Array(K.length),U=K.length-1;for(let V=0;V<U;V++)G[V]=X.substring(K[V],K[V+1]);let B=X.substring(K[U]);if(B.length>0)G[U]=B;else G.pop();return{lines:G,lineMap:K}}},ST=class ${constructor(X=[]){if(this.children=X,this.totalChars=0,this.totalLines=0,X.length)this.updateCounts()}isLeaf(){return!1}updateCounts(){this.totalChars=0,this.totalLines=0;for(let X of this.children)this.totalChars+=X.charCount(),this.totalLines+=X.lineCount()}execWalk(X,K,G,U,B){if(G.pre)G.pre(X,K,this.children[U],this,B);if(G.goSubtree){if(this.children[U].walk(X,K,G),G.post)G.post(X,K,this.children[U],this,B)}else G.goSubtree=!0;return G.done}skipChild(X,K,G,U,B){if(U.pre&&!U.done)U.pre(X,K,this.children[G],this,B),U.goSubtree=!0}walk(X,K,G){if(this.children.length===0)return;let U=0,B=this.children[U].charCount(),V=X;while(V>=B)this.skipChild(V,K,U,G,0),V-=B,U++,B=this.children[U].charCount();if(V+K<=B){if(this.execWalk(V,K,G,U,2))return}else{if(this.execWalk(V,B-V,G,U,1))return;let L=K-(B-V);U++,B=this.children[U].charCount();while(L>B){if(this.execWalk(0,B,G,U,3))return;L-=B,U++,B=this.children[U].charCount()}if(L>0){if(this.execWalk(0,L,G,U,4))return}}if(G.pre){let L=this.children.length;if(U<L-1)for(let A=U+1;A<L;A++)this.skipChild(0,0,A,G,5)}}charOffsetToLineInfo(X,K){if(this.children.length===0)return{oneBasedLine:X,zeroBasedColumn:K,lineText:void 0};for(let B of this.children)if(B.charCount()>K)if(B.isLeaf())return{oneBasedLine:X,zeroBasedColumn:K,lineText:B.text};else return B.charOffsetToLineInfo(X,K);else K-=B.charCount(),X+=B.lineCount();let G=this.lineCount();if(G===0)return{oneBasedLine:1,zeroBasedColumn:0,lineText:void 0};let U=m.checkDefined(this.lineNumberToInfo(G,0).leaf);return{oneBasedLine:G,zeroBasedColumn:U.charCount(),lineText:void 0}}lineNumberToInfo(X,K){for(let G of this.children){let U=G.lineCount();if(U>=X)return G.isLeaf()?{position:K,leaf:G}:G.lineNumberToInfo(X,K);else X-=U,K+=G.charCount()}return{position:K,leaf:void 0}}splitAfter(X){let K,G=this.children.length;X++;let U=X;if(X<G){K=new $;while(X<G)K.add(this.children[X]),X++;K.updateCounts()}return this.children.length=U,K}remove(X){let K=this.findChildIndex(X),G=this.children.length;if(K<G-1)for(let U=K;U<G-1;U++)this.children[U]=this.children[U+1];this.children.pop()}findChildIndex(X){let K=this.children.indexOf(X);return m.assert(K!==-1),K}insertAt(X,K){let G=this.findChildIndex(X),U=this.children.length,B=K.length;if(U<wT&&G===U-1&&B===1)return this.add(K[0]),this.updateCounts(),[];else{let V=this.splitAfter(G),L=0;G++;while(G<wT&&L<B)this.children[G]=K[L],G++,L++;let A=[],_=0;if(L<B){_=Math.ceil((B-L)/wT),A=Array(_);let N=0;for(let k=0;k<_;k++)A[k]=new $;let T=A[0];while(L<B)if(T.add(K[L]),L++,T.children.length===wT)N++,T=A[N];for(let k=A.length-1;k>=0;k--)if(A[k].children.length===0)A.pop()}if(V)A.push(V);this.updateCounts();for(let N=0;N<_;N++)A[N].updateCounts();return A}}add(X){this.children.push(X),m.assert(this.children.length<=wT)}charCount(){return this.totalChars}lineCount(){return this.totalLines}},Dr=class{constructor($){this.text=$}isLeaf(){return!0}walk($,X,K){K.leaf($,X,this)}charCount(){return this.text.length}lineCount(){return 1}},B86=class ${constructor(X,K,G,U,B,V){this.telemetryEnabled=X,this.logger=K,this.host=G,this.globalTypingsCacheLocation=U,this.event=B,this.maxActiveRequestCount=V,this.activeRequestCount=0,this.requestQueue=fU(),this.requestMap=new Map,this.requestedRegistry=!1,this.packageInstallId=0}isKnownTypesPackageName(X){var K;if(lq.validatePackageName(X)!==lq.NameValidationResult.Ok)return!1;if(!this.requestedRegistry)this.requestedRegistry=!0,this.installer.send({kind:"typesRegistry"});return!!((K=this.typesRegistryCache)==null?void 0:K.has(X))}installPackage(X){this.packageInstallId++;let K={kind:"installPackage",...X,id:this.packageInstallId},G=new Promise((U,B)=>{(this.packageInstalledPromise??(this.packageInstalledPromise=new Map)).set(this.packageInstallId,{resolve:U,reject:B})});return this.installer.send(K),G}attach(X){this.projectService=X,this.installer=this.createInstallerProcess()}onProjectClosed(X){this.installer.send({projectName:X.getProjectName(),kind:"closeProject"})}enqueueInstallTypingsRequest(X,K,G){let U=qP$(X,K,G);if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Scheduling throttled operation:${S3(U)}`);if(this.activeRequestCount<this.maxActiveRequestCount)this.scheduleRequest(U);else{if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Deferring request for: ${U.projectName}`);this.requestQueue.enqueue(U),this.requestMap.set(U.projectName,U)}}handleMessage(X){var K,G;if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Received response:${S3(X)}`);switch(X.kind){case h8$:this.typesRegistryCache=new Map(Object.entries(X.typesRegistry));break;case yp:{let U=(K=this.packageInstalledPromise)==null?void 0:K.get(X.id);if(m.assertIsDefined(U,"Should find the promise for package install"),(G=this.packageInstalledPromise)==null||G.delete(X.id),X.success)U.resolve({successMessage:X.message});else U.reject(X.message);this.projectService.updateTypingsForProject(X),this.event(X,"setTypings");break}case PD$:{let U={message:X.message},B="typesInstallerInitializationFailed";this.event(U,"typesInstallerInitializationFailed");break}case g8$:{let U={eventId:X.eventId,packages:X.packagesToInstall},B="beginInstallTypes";this.event(U,"beginInstallTypes");break}case m8$:{if(this.telemetryEnabled){let V={telemetryEventName:"typingsInstalled",payload:{installedPackages:X.packagesToInstall.join(","),installSuccess:X.installSuccess,typingsInstallerVersion:X.typingsInstallerVersion}},L="telemetry";this.event(V,"telemetry")}let U={eventId:X.eventId,packages:X.packagesToInstall,success:X.installSuccess},B="endInstallTypes";this.event(U,B);break}case xp:{this.projectService.updateTypingsForProject(X);break}case kp:{if(this.activeRequestCount>0)this.activeRequestCount--;else m.fail("TIAdapter:: Received too many responses");while(!this.requestQueue.isEmpty()){let U=this.requestQueue.dequeue();if(this.requestMap.get(U.projectName)===U){this.requestMap.delete(U.projectName),this.scheduleRequest(U);break}if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Skipping defunct request for: ${U.projectName}`)}this.projectService.updateTypingsForProject(X),this.event(X,"setTypings");break}case Av:this.projectService.watchTypingLocations(X);break;default:xB(X)}}scheduleRequest(X){if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Scheduling request for: ${X.projectName}`);this.activeRequestCount++,this.host.setTimeout(()=>{if(this.logger.hasLevel(3))this.logger.info(`TIAdapter:: Sending request:${S3(X)}`);this.installer.send(X)},$.requestDelayMillis,`${X.projectName}::${X.kind}`)}};B86.requestDelayMillis=100;var H86=B86,V86={};if(H(V86,{ActionInvalidate:()=>xp,ActionPackageInstalled:()=>yp,ActionSet:()=>kp,ActionWatchTypingLocations:()=>Av,Arguments:()=>u8$,AutoImportProviderProject:()=>fP$,AuxiliaryProject:()=>xP$,CharRangeSection:()=>WM$,CloseFileWatcherEvent:()=>XX$,CommandNames:()=>e16,ConfigFileDiagEvent:()=>o4$,ConfiguredProject:()=>vP$,ConfiguredProjectLoadKind:()=>dP$,CreateDirectoryWatcherEvent:()=>JX$,CreateFileWatcherEvent:()=>$X$,Errors:()=>XH,EventBeginInstallTypes:()=>g8$,EventEndInstallTypes:()=>m8$,EventInitializationFailed:()=>PD$,EventTypesRegistry:()=>h8$,ExternalProject:()=>p4$,GcTimer:()=>MP$,InferredProject:()=>kP$,LargeFileReferencedEvent:()=>n4$,LineIndex:()=>Nh,LineLeaf:()=>Dr,LineNode:()=>ST,LogLevel:()=>HP$,Msg:()=>VP$,OpenFileInfoTelemetryEvent:()=>hP$,Project:()=>iN,ProjectInfoTelemetryEvent:()=>e4$,ProjectKind:()=>aC,ProjectLanguageServiceStateEvent:()=>t4$,ProjectLoadingFinishEvent:()=>a4$,ProjectLoadingStartEvent:()=>s4$,ProjectService:()=>tP$,ProjectsUpdatedInBackgroundEvent:()=>Hr,ScriptInfo:()=>_P$,ScriptVersionCache:()=>VX$,Session:()=>G86,TextStorage:()=>EP$,ThrottledOperations:()=>PP$,TypingsInstallerAdapter:()=>H86,allFilesAreJsOrDts:()=>SP$,allRootFilesAreJsOrDts:()=>wP$,asNormalizedPath:()=>FU,convertCompilerOptions:()=>Vr,convertFormatOptions:()=>TT,convertScriptKindName:()=>QX$,convertTypeAcquisition:()=>mP$,convertUserPreferences:()=>uP$,convertWatchOptions:()=>Ph,countEachFileTypes:()=>Fh,createInstallTypingsRequest:()=>qP$,createModuleSpecifierCache:()=>JM$,createNormalizedPathMap:()=>_16,createPackageJsonCache:()=>XM$,createSortedArray:()=>OP$,emptyArray:()=>r7,findArgument:()=>Ti$,formatDiagnosticToProtocol:()=>Mh,formatMessage:()=>YM$,getBaseConfigFileName:()=>l4$,getDetailWatchInfo:()=>WX$,getLocationInNewDocument:()=>GM$,hasArgument:()=>_i$,hasNoTypeScriptSource:()=>CP$,indent:()=>OC,isBackgroundProject:()=>Lh,isConfigFile:()=>eP$,isConfiguredProject:()=>qV,isDynamicFileName:()=>sC,isExternalProject:()=>Ah,isInferredProject:()=>_T,isInferredProjectName:()=>DP$,isProjectDeferredClose:()=>Oh,makeAutoImportProviderProjectName:()=>AP$,makeAuxiliaryProjectName:()=>LP$,makeInferredProjectName:()=>FP$,maxFileSize:()=>r4$,maxProgramSizeForNonTsFiles:()=>i4$,normalizedPathToPath:()=>ET,nowString:()=>Ri$,nullCancellationToken:()=>n16,nullTypingsInstaller:()=>qr,protocol:()=>NP$,scriptInfoIsContainedByBackgroundProject:()=>TP$,scriptInfoIsContainedByDeferredClosedProject:()=>RP$,stringifyIndented:()=>S3,toEvent:()=>QM$,toNormalizedPath:()=>WY,tryConvertScriptKindName:()=>YX$,typingsInstaller:()=>BP$,updateProjectIfDirty:()=>qW}),typeof console<"u")m.loggingHost={log($,X){switch($){case 1:return console.error(X);case 2:return console.warn(X);case 3:return console.log(X);case 4:return console.log(X)}}}})({get exports(){return lj6},set exports(J){if(lj6=J,typeof s5$<"u"&&s5$.exports)s5$.exports=J}})});import{readFileSync as eP0}from"fs";import{resolve as $M0,dirname as JM0}from"path";import{parse as XM0,compileScript as YM0,compileTemplate as QM0}from"@vue/compiler-sfc";function aj6(){o5$.clear()}async function t5$(J,Y,Z,W={}){let z=Y?`${J}::${WM0(Z)}`:null;if(z&&o5$.has(z))return o5$.get(z);let H=eP0(J,"utf-8"),F=await FS$(H,J,Y,Z,W);if(z)o5$.set(z,F);return F}async function FS$(J,Y,Z,W,z={}){let{descriptor:H,errors:F}=XM0(J,{filename:Y});if(F.length)throw Error(`@arcforge/vstr: parse errors in ${Y}:
503
503
  ${F.map((y$)=>y$.message).join(`
504
- `)}`);if(!H.template)throw Error(`@axon/vstr: ${Y} has no <template> block`);KM0(J,H,Y);let P=Y.replace(/[^a-zA-Z0-9]/g,"_"),E=H.scriptSetup?.content??H.script?.content??"",w=await ZM0(E,Y,Z,W,z),S=Object.keys(w),v=Object.values(w),x;if(H.scriptSetup||H.script)x=YM0(H,{id:P,inlineTemplate:!0,templateOptions:{ssr:!0,compilerOptions:{runtimeModuleName:"@vue/runtime-core"}}}).content;else{let y$=QM0({source:H.template.content,filename:Y,id:P,scoped:!1,ssr:!0,ssrCssVars:[],compilerOptions:{runtimeModuleName:"@vue/runtime-core"}});if(y$.errors.length)throw Error(`@axon/vstr: template compile errors in ${Y}:
504
+ `)}`);if(!H.template)throw Error(`@arcforge/vstr: ${Y} has no <template> block`);KM0(J,H,Y);let P=Y.replace(/[^a-zA-Z0-9]/g,"_"),E=H.scriptSetup?.content??H.script?.content??"",w=await ZM0(E,Y,Z,W,z),S=Object.keys(w),v=Object.values(w),x;if(H.scriptSetup||H.script)x=YM0(H,{id:P,inlineTemplate:!0,templateOptions:{ssr:!0,compilerOptions:{runtimeModuleName:"@vue/runtime-core"}}}).content;else{let y$=QM0({source:H.template.content,filename:Y,id:P,scoped:!1,ssr:!0,ssrCssVars:[],compilerOptions:{runtimeModuleName:"@vue/runtime-core"}});if(y$.errors.length)throw Error(`@arcforge/vstr: template compile errors in ${Y}:
505
505
  ${y$.errors.map((k6)=>typeof k6==="string"?k6:k6.message).join(`
506
506
  `)}`);x=`export default { ssrRender }
507
507
  ${rj6(await sj6(y$.code)).replace(/^export\s+function\s+ssrRender/,"function ssrRender").replace(/^export\s+/gm,"")}`}let c=await sj6(x),r=new Set(["default","__esModule"]),n=Object.keys(pj6).filter((y$)=>!r.has(y$)),B$=Object.keys(IL).filter((y$)=>!r.has(y$)&&y$!=="render"&&y$!=="ssrRender"&&!n.includes(y$)),_$=Object.keys(ij6).filter((y$)=>!r.has(y$)),A$=Object.keys(W),H$=Object.values(W),M$=Object.keys(z),b$=Object.values(z),p$=new Set;for(let y$ of M$)p$.add(y$.toLowerCase()),p$.add(y$.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase());let o$=rj6(GM0(c)).replace(/const\s+(_component_\w+)\s*=\s*_resolveComponent\([^)]+\);?/g,(y$,_6)=>{let k6=_6.replace(/^_component_/,"").toLowerCase();return p$.has(k6)?"":`const ${_6} = _resolveComponent;`}).replace(/export\s+default\s+/,"const __scriptDef = ").replace(/export\s*\{([^}]+)\}/g,""),T6=`
@@ -557,7 +557,7 @@ const __component = {
557
557
  }
558
558
 
559
559
  return __component;
560
- `,Y6=Function("__vueRuntimeCore","__vue","__serverRenderer","__subComponents","__globals","__context",T6)(pj6,IL,ij6,v,b$,H$);if(!Y6)throw Error(`@axon/vstr: compiled component is null for ${Y}`);return Y6}function KM0(J,Y,Z){let W=[Y.template,Y.script,Y.scriptSetup,...Y.styles,...Y.customBlocks].filter((H)=>H!==null),z=J;for(let H of W){let F=J.lastIndexOf(`<${H.type}`,H.loc.start.offset),P=`</${H.type}>`,E=J.indexOf(P,H.loc.end.offset)+P.length;if(F===-1||E===P.length-1)continue;z=z.slice(0,F)+" ".repeat(E-F)+z.slice(E)}if(z=z.replace(/<(template|script|style)(\s[^>]*)?>\s*<\/\1>/g,""),z.trim().length>0)throw Error(`@axon/vstr: ${Z} has content outside its <template>/<script>/<style> blocks \u2014 this is likely a typo`)}async function ZM0(J,Y,Z,W,z){let H=JM0(Y),F={},P=/import\s+(\w+)\s+from\s+["'](\.{1,2}\/[^"']+\.(vd|vue|prompt))["']/g,E;while((E=P.exec(J))!==null){let[,w,S]=E;if(w===void 0||S===void 0)continue;F[w]=await t5$($M0(H,S),Z,W,z)}return F}function rj6(J){return J.replace(/^import\s[\s\S]*?from\s+["'][^"']+["'];?/gm,(Y)=>{let Z=Y.replace(/\s+/g," ").trim();if(/^import\s+\*\s+as\s+/.test(Z))return"";let W=Z.match(/^import\s*\{([^}]+)\}\s*from/);if(W?.[1]!==void 0)return W[1].split(",").map((z)=>{let[H,F]=z.split(" as ").map((P)=>P.trim());if(!H)return"";if(F&&F!==H)return`const ${F} = ${H};`;return""}).filter(Boolean).join(`
560
+ `,Y6=Function("__vueRuntimeCore","__vue","__serverRenderer","__subComponents","__globals","__context",T6)(pj6,IL,ij6,v,b$,H$);if(!Y6)throw Error(`@arcforge/vstr: compiled component is null for ${Y}`);return Y6}function KM0(J,Y,Z){let W=[Y.template,Y.script,Y.scriptSetup,...Y.styles,...Y.customBlocks].filter((H)=>H!==null),z=J;for(let H of W){let F=J.lastIndexOf(`<${H.type}`,H.loc.start.offset),P=`</${H.type}>`,E=J.indexOf(P,H.loc.end.offset)+P.length;if(F===-1||E===P.length-1)continue;z=z.slice(0,F)+" ".repeat(E-F)+z.slice(E)}if(z=z.replace(/<(template|script|style)(\s[^>]*)?>\s*<\/\1>/g,""),z.trim().length>0)throw Error(`@arcforge/vstr: ${Z} has content outside its <template>/<script>/<style> blocks \u2014 this is likely a typo`)}async function ZM0(J,Y,Z,W,z){let H=JM0(Y),F={},P=/import\s+(\w+)\s+from\s+["'](\.{1,2}\/[^"']+\.(vd|vue|prompt))["']/g,E;while((E=P.exec(J))!==null){let[,w,S]=E;if(w===void 0||S===void 0)continue;F[w]=await t5$($M0(H,S),Z,W,z)}return F}function rj6(J){return J.replace(/^import\s[\s\S]*?from\s+["'][^"']+["'];?/gm,(Y)=>{let Z=Y.replace(/\s+/g," ").trim();if(/^import\s+\*\s+as\s+/.test(Z))return"";let W=Z.match(/^import\s*\{([^}]+)\}\s*from/);if(W?.[1]!==void 0)return W[1].split(",").map((z)=>{let[H,F]=z.split(" as ").map((P)=>P.trim());if(!H)return"";if(F&&F!==H)return`const ${F} = ${H};`;return""}).filter(Boolean).join(`
561
561
  `);return""})}function GM0(J){return J.replace(/^import\s+\w+\s+from\s+["']\.{1,2}\/[^"']+\.(vd|vue|prompt)["'];?\n?/gm,"")}async function sj6(J){if(typeof Bun<"u")return new Bun.Transpiler({loader:"ts"}).transformSync(J);return n5$.default.transpileModule(J,{compilerOptions:{module:n5$.default.ModuleKind.ESNext,target:n5$.default.ScriptTarget.ESNext}}).outputText}function WM0(J){return Object.keys(J).sort().map((Y)=>`${Y}:${typeof J[Y]}`).join(",")}var pj6,ij6,n5$,o5$;var nj6=n9(()=>{Sw$();pj6=db(Lw$(),1),ij6=db(aw$(),1),n5$=db(a5$(),1),o5$=new Map});import{readFileSync as zM0}from"fs";import{resolve as UM0}from"path";import{parse as jM0}from"@vue/compiler-sfc";function oj6(J){let Y=UM0(J),Z=zM0(Y,"utf-8");return AS$(Z,Y)}function AS$(J,Y="<source>"){let{descriptor:Z,errors:W}=jM0(J,{filename:Y});if(W.length||!Z.scriptSetup)return[];let z=Z.scriptSetup.content,H=HM0(z),F=BM0(z);for(let P of F)if(P.name in H)P.default=H[P.name];else if(!P.required)P.default=null;return F}function BM0(J){let Y=_L.default.createSourceFile("props.ts",J,_L.default.ScriptTarget.Latest,!0,_L.default.ScriptKind.TS),Z=[];function W(z){if(_L.default.isCallExpression(z)&&_L.default.isIdentifier(z.expression)&&z.expression.text==="defineProps"&&z.typeArguments&&z.typeArguments.length>0){let H=z.typeArguments[0];if(_L.default.isTypeLiteralNode(H)){for(let F of H.members)if(_L.default.isPropertySignature(F)&&_L.default.isIdentifier(F.name))Z.push({name:F.name.text,type:F.type?F.type.getText(Y):"unknown",required:!F.questionToken,default:void 0})}}_L.default.forEachChild(z,W)}return _L.default.forEachChild(Y,W),Z}function HM0(J){let Y={},Z=J.match(/const\s*\{([^}]+)\}\s*=\s*defineProps/);if(Z?.[1]===void 0)return Y;for(let W of Z[1].split(",")){let z=W.indexOf("=");if(z===-1)continue;let H=W.slice(0,z).trim(),F=W.slice(z+1).trim();try{Y[H]=JSON.parse(F)}catch{Y[H]=F}}return Y}var _L;var tj6=n9(()=>{_L=db(a5$(),1)});var Om=N9((M01,ej6)=>{ej6.exports=wk;wk.CAPTURING_PHASE=1;wk.AT_TARGET=2;wk.BUBBLING_PHASE=3;function wk(J,Y){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=wk.AT_TARGET,this.bubbles=!1,this.cancelable=!1,this.isTrusted=!1,this.defaultPrevented=!1,this.timeStamp=Date.now(),this._propagationStopped=!1,this._immediatePropagationStopped=!1,this._initialized=!0,this._dispatching=!1,J)this.type=J;if(Y)for(var Z in Y)this[Z]=Y[Z]}wk.prototype=Object.create(Object.prototype,{constructor:{value:wk},stopPropagation:{value:function(){this._propagationStopped=!0}},stopImmediatePropagation:{value:function(){this._propagationStopped=!0,this._immediatePropagationStopped=!0}},preventDefault:{value:function(){if(this.cancelable)this.defaultPrevented=!0}},initEvent:{value:function(Y,Z,W){if(this._initialized=!0,this._dispatching)return;this._propagationStopped=!1,this._immediatePropagationStopped=!1,this.defaultPrevented=!1,this.isTrusted=!1,this.target=null,this.type=Y,this.bubbles=Z,this.cancelable=W}}})});var OS$=N9((N01,JB6)=>{var $B6=Om();JB6.exports=LS$;function LS$(){$B6.call(this),this.view=null,this.detail=0}LS$.prototype=Object.create($B6.prototype,{constructor:{value:LS$},initUIEvent:{value:function(J,Y,Z,W,z){this.initEvent(J,Y,Z),this.view=W,this.detail=z}}})});var MS$=N9((I01,YB6)=>{var XB6=OS$();YB6.exports=PS$;function PS$(){XB6.call(this),this.screenX=this.screenY=this.clientX=this.clientY=0,this.ctrlKey=this.altKey=this.shiftKey=this.metaKey=!1,this.button=0,this.buttons=1,this.relatedTarget=null}PS$.prototype=Object.create(XB6.prototype,{constructor:{value:PS$},initMouseEvent:{value:function(J,Y,Z,W,z,H,F,P,E,w,S,v,x,c,r){switch(this.initEvent(J,Y,Z,W,z),this.screenX=H,this.screenY=F,this.clientX=P,this.clientY=E,this.ctrlKey=w,this.altKey=S,this.shiftKey=v,this.metaKey=x,this.button=c,c){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2;break;default:this.buttons=0;break}this.relatedTarget=r}},getModifierState:{value:function(J){switch(J){case"Alt":return this.altKey;case"Control":return this.ctrlKey;case"Shift":return this.shiftKey;case"Meta":return this.metaKey;default:return!1}}}})});var J2$=N9((E01,KB6)=>{KB6.exports=$2$;var VM0=1,qM0=3,DM0=4,FM0=5,AM0=7,LM0=8,OM0=9,PM0=11,MM0=12,NM0=13,IM0=14,EM0=15,_M0=17,TM0=18,RM0=19,wM0=20,SM0=21,CM0=22,bM0=23,kM0=24,xM0=25,yM0=[null,"INDEX_SIZE_ERR",null,"HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR",null,"NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR",null,"TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR"],fM0=[null,"INDEX_SIZE_ERR (1): the index is not in the allowed range",null,"HIERARCHY_REQUEST_ERR (3): the operation would yield an incorrect nodes model","WRONG_DOCUMENT_ERR (4): the object is in the wrong Document, a call to importNode is required","INVALID_CHARACTER_ERR (5): the string contains invalid characters",null,"NO_MODIFICATION_ALLOWED_ERR (7): the object can not be modified","NOT_FOUND_ERR (8): the object can not be found here","NOT_SUPPORTED_ERR (9): this operation is not supported","INUSE_ATTRIBUTE_ERR (10): setAttributeNode called on owned Attribute","INVALID_STATE_ERR (11): the object is in an invalid state","SYNTAX_ERR (12): the string did not match the expected pattern","INVALID_MODIFICATION_ERR (13): the object can not be modified in this way","NAMESPACE_ERR (14): the operation is not allowed by Namespaces in XML","INVALID_ACCESS_ERR (15): the object does not support the operation or argument",null,"TYPE_MISMATCH_ERR (17): the type of the object does not match the expected type","SECURITY_ERR (18): the operation is insecure","NETWORK_ERR (19): a network error occurred","ABORT_ERR (20): the user aborted an operation","URL_MISMATCH_ERR (21): the given URL does not match another URL","QUOTA_EXCEEDED_ERR (22): the quota has been exceeded","TIMEOUT_ERR (23): a timeout occurred","INVALID_NODE_TYPE_ERR (24): the supplied node is invalid or has an invalid ancestor for this operation","DATA_CLONE_ERR (25): the object can not be cloned."],QB6={INDEX_SIZE_ERR:VM0,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:qM0,WRONG_DOCUMENT_ERR:DM0,INVALID_CHARACTER_ERR:FM0,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:AM0,NOT_FOUND_ERR:LM0,NOT_SUPPORTED_ERR:OM0,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:PM0,SYNTAX_ERR:MM0,INVALID_MODIFICATION_ERR:NM0,NAMESPACE_ERR:IM0,INVALID_ACCESS_ERR:EM0,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:_M0,SECURITY_ERR:TM0,NETWORK_ERR:RM0,ABORT_ERR:wM0,URL_MISMATCH_ERR:SM0,QUOTA_EXCEEDED_ERR:CM0,TIMEOUT_ERR:bM0,INVALID_NODE_TYPE_ERR:kM0,DATA_CLONE_ERR:xM0};function $2$(J){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=J,this.message=fM0[J],this.name=yM0[J]}$2$.prototype.__proto__=Error.prototype;for(Nn in QB6)e5$={value:QB6[Nn]},Object.defineProperty($2$,Nn,e5$),Object.defineProperty($2$.prototype,Nn,e5$);var e5$,Nn});var X2$=N9((vM0)=>{vM0.isApiWritable=!globalThis.__domino_frozen__});var tG=N9((mM0)=>{var oG=J2$(),SW=oG,gM0=X2$().isApiWritable;mM0.NAMESPACE={HTML:"http://www.w3.org/1999/xhtml",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink"};mM0.IndexSizeError=function(){throw new oG(SW.INDEX_SIZE_ERR)};mM0.HierarchyRequestError=function(){throw new oG(SW.HIERARCHY_REQUEST_ERR)};mM0.WrongDocumentError=function(){throw new oG(SW.WRONG_DOCUMENT_ERR)};mM0.InvalidCharacterError=function(){throw new oG(SW.INVALID_CHARACTER_ERR)};mM0.NoModificationAllowedError=function(){throw new oG(SW.NO_MODIFICATION_ALLOWED_ERR)};mM0.NotFoundError=function(){throw new oG(SW.NOT_FOUND_ERR)};mM0.NotSupportedError=function(){throw new oG(SW.NOT_SUPPORTED_ERR)};mM0.InvalidStateError=function(){throw new oG(SW.INVALID_STATE_ERR)};mM0.SyntaxError=function(){throw new oG(SW.SYNTAX_ERR)};mM0.InvalidModificationError=function(){throw new oG(SW.INVALID_MODIFICATION_ERR)};mM0.NamespaceError=function(){throw new oG(SW.NAMESPACE_ERR)};mM0.InvalidAccessError=function(){throw new oG(SW.INVALID_ACCESS_ERR)};mM0.TypeMismatchError=function(){throw new oG(SW.TYPE_MISMATCH_ERR)};mM0.SecurityError=function(){throw new oG(SW.SECURITY_ERR)};mM0.NetworkError=function(){throw new oG(SW.NETWORK_ERR)};mM0.AbortError=function(){throw new oG(SW.ABORT_ERR)};mM0.UrlMismatchError=function(){throw new oG(SW.URL_MISMATCH_ERR)};mM0.QuotaExceededError=function(){throw new oG(SW.QUOTA_EXCEEDED_ERR)};mM0.TimeoutError=function(){throw new oG(SW.TIMEOUT_ERR)};mM0.InvalidNodeTypeError=function(){throw new oG(SW.INVALID_NODE_TYPE_ERR)};mM0.DataCloneError=function(){throw new oG(SW.DATA_CLONE_ERR)};mM0.nyi=function(){throw Error("NotYetImplemented")};mM0.shouldOverride=function(){throw Error("Abstract function; should be overriding in subclass.")};mM0.assert=function(J,Y){if(!J)throw Error("Assertion failed: "+(Y||"")+`
562
562
  `+Error().stack)};mM0.expose=function(J,Y){for(var Z in J)Object.defineProperty(Y.prototype,Z,{value:J[Z],writable:gM0})};mM0.merge=function(J,Y){for(var Z in Y)J[Z]=Y[Z]};mM0.documentOrder=function(J,Y){return 3-(J.compareDocumentPosition(Y)&6)};mM0.toASCIILowerCase=function(J){return J.replace(/[A-Z]+/g,function(Y){return Y.toLowerCase()})};mM0.toASCIIUpperCase=function(J){return J.replace(/[a-z]+/g,function(Y){return Y.toUpperCase()})}});var NS$=N9((R01,GB6)=>{var Sk=Om(),FN0=MS$(),AN0=tG();GB6.exports=ZB6;function ZB6(){}ZB6.prototype={addEventListener:function(Y,Z,W){if(!Z)return;if(W===void 0)W=!1;if(!this._listeners)this._listeners=Object.create(null);if(!this._listeners[Y])this._listeners[Y]=[];var z=this._listeners[Y];for(var H=0,F=z.length;H<F;H++){var P=z[H];if(P.listener===Z&&P.capture===W)return}var E={listener:Z,capture:W};if(typeof Z==="function")E.f=Z;z.push(E)},removeEventListener:function(Y,Z,W){if(W===void 0)W=!1;if(this._listeners){var z=this._listeners[Y];if(z)for(var H=0,F=z.length;H<F;H++){var P=z[H];if(P.listener===Z&&P.capture===W){if(z.length===1)this._listeners[Y]=void 0;else z.splice(H,1);return}}}},dispatchEvent:function(Y){return this._dispatchEvent(Y,!1)},_dispatchEvent:function(Y,Z){if(typeof Z!=="boolean")Z=!1;function W(w,S){var{type:v,eventPhase:x}=S;if(S.currentTarget=w,x!==Sk.CAPTURING_PHASE&&w._handlers&&w._handlers[v]){var c=w._handlers[v],r;if(typeof c==="function")r=c.call(S.currentTarget,S);else{var n=c.handleEvent;if(typeof n!=="function")throw TypeError("handleEvent property of event handler object isnot a function.");r=n.call(c,S)}switch(S.type){case"mouseover":if(r===!0)S.preventDefault();break;case"beforeunload":default:if(r===!1)S.preventDefault();break}}var B$=w._listeners&&w._listeners[v];if(!B$)return;B$=B$.slice();for(var _$=0,A$=B$.length;_$<A$;_$++){if(S._immediatePropagationStopped)return;var H$=B$[_$];if(x===Sk.CAPTURING_PHASE&&!H$.capture||x===Sk.BUBBLING_PHASE&&H$.capture)continue;if(H$.f)H$.f.call(S.currentTarget,S);else{var M$=H$.listener.handleEvent;if(typeof M$!=="function")throw TypeError("handleEvent property of event listener object is not a function.");M$.call(H$.listener,S)}}}if(!Y._initialized||Y._dispatching)AN0.InvalidStateError();Y.isTrusted=Z,Y._dispatching=!0,Y.target=this;var z=[];for(var H=this.parentNode;H;H=H.parentNode)z.push(H);Y.eventPhase=Sk.CAPTURING_PHASE;for(var F=z.length-1;F>=0;F--)if(W(z[F],Y),Y._propagationStopped)break;if(!Y._propagationStopped)Y.eventPhase=Sk.AT_TARGET,W(this,Y);if(Y.bubbles&&!Y._propagationStopped){Y.eventPhase=Sk.BUBBLING_PHASE;for(var P=0,E=z.length;P<E;P++)if(W(z[P],Y),Y._propagationStopped)break}if(Y._dispatching=!1,Y.eventPhase=Sk.AT_TARGET,Y.currentTarget=null,Z&&!Y.defaultPrevented&&Y instanceof FN0)switch(Y.type){case"mousedown":this._armed={x:Y.clientX,y:Y.clientY,t:Y.timeStamp};break;case"mouseout":case"mouseover":this._armed=null;break;case"mouseup":if(this._isClick(Y))this._doClick(Y);this._armed=null;break}return!Y.defaultPrevented},_isClick:function(J){return this._armed!==null&&J.type==="mouseup"&&J.isTrusted&&J.button===0&&J.timeStamp-this._armed.t<1000&&Math.abs(J.clientX-this._armed.x)<10&&Math.abs(J.clientY-this._armed.Y)<10},_doClick:function(J){if(this._click_in_progress)return;this._click_in_progress=!0;var Y=this;while(Y&&!Y._post_click_activation_steps)Y=Y.parentNode;if(Y&&Y._pre_click_activation_steps)Y._pre_click_activation_steps();var Z=this.ownerDocument.createEvent("MouseEvent");Z.initMouseEvent("click",!0,!0,this.ownerDocument.defaultView,1,J.screenX,J.screenY,J.clientX,J.clientY,J.ctrlKey,J.altKey,J.shiftKey,J.metaKey,J.button,null);var W=this._dispatchEvent(Z,!0);if(Y){if(W){if(Y._post_click_activation_steps)Y._post_click_activation_steps(Z)}else if(Y._cancelled_activation_steps)Y._cancelled_activation_steps()}},_setEventHandler:function(Y,Z){if(!this._handlers)this._handlers=Object.create(null);this._handlers[Y]=Z},_getEventHandler:function(Y){return this._handlers&&this._handlers[Y]||null}}});var IS$=N9((w01,WB6)=>{var UE=tG(),yF=WB6.exports={valid:function(J){return UE.assert(J,"list falsy"),UE.assert(J._previousSibling,"previous falsy"),UE.assert(J._nextSibling,"next falsy"),!0},insertBefore:function(J,Y){UE.assert(yF.valid(J)&&yF.valid(Y));var Z=J,W=J._previousSibling,z=Y,H=Y._previousSibling;Z._previousSibling=H,W._nextSibling=z,H._nextSibling=Z,z._previousSibling=W,UE.assert(yF.valid(J)&&yF.valid(Y))},replace:function(J,Y){if(UE.assert(yF.valid(J)&&(Y===null||yF.valid(Y))),Y!==null)yF.insertBefore(Y,J);yF.remove(J),UE.assert(yF.valid(J)&&(Y===null||yF.valid(Y)))},remove:function(J){UE.assert(yF.valid(J));var Y=J._previousSibling;if(Y===J)return;var Z=J._nextSibling;Y._nextSibling=Z,Z._previousSibling=Y,J._previousSibling=J._nextSibling=J,UE.assert(yF.valid(J))}}});var ES$=N9((S01,DB6)=>{DB6.exports={serializeOne:EN0,\u{275}escapeMatchingClosingTag:HB6,\u{275}escapeClosingCommentTag:VB6,\u{275}escapeProcessingInstructionContent:qB6};var BB6=tG(),Ck=BB6.NAMESPACE,zB6={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},LN0={area:!0,base:!0,basefont:!0,bgsound:!0,br:!0,col:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},ON0={},UB6=/[&<>\u00A0]/g,jB6=/[&"<>\u00A0]/g;function PN0(J){if(!UB6.test(J))return J;return J.replace(UB6,(Y)=>{switch(Y){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case"\xA0":return"&nbsp;"}})}function MN0(J){if(!jB6.test(J))return J;return J.replace(jB6,(Y)=>{switch(Y){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case"\xA0":return"&nbsp;"}})}function NN0(J){var Y=J.namespaceURI;if(!Y)return J.localName;if(Y===Ck.XML)return"xml:"+J.localName;if(Y===Ck.XLINK)return"xlink:"+J.localName;if(Y===Ck.XMLNS)if(J.localName==="xmlns")return"xmlns";else return"xmlns:"+J.localName;return J.name}function HB6(J,Y){let Z="</"+Y;if(!J.toLowerCase().includes(Z))return J;let W=[...J],z=J.matchAll(new RegExp(Z,"ig"));for(let H of z)W[H.index]="&lt;";return W.join("")}var IN0=/--!?>/;function VB6(J){if(!IN0.test(J))return J;return J.replace(/(--\!?)>/g,"$1&gt;")}function qB6(J){return J.includes(">")?J.replaceAll(">","&gt;"):J}function EN0(J,Y){var Z="";switch(J.nodeType){case 1:var W=J.namespaceURI,z=W===Ck.HTML,H=z||W===Ck.SVG||W===Ck.MATHML?J.localName:J.tagName;Z+="<"+H;for(var F=0,P=J._numattrs;F<P;F++){var E=J._attr(F);if(Z+=" "+NN0(E),E.value!==void 0)Z+='="'+MN0(E.value)+'"'}if(Z+=">",!(z&&LN0[H])){var w=J.serialize();if(zB6[H.toUpperCase()])w=HB6(w,H);if(z&&ON0[H]&&w.charAt(0)===`
563
563
  `)Z+=`
@@ -723,7 +723,7 @@ ${Z.text}`};Y[Y.length-1]=z;continue}Y.push(Z)}return Y}function ok({signature:J
723
723
  `)}}else E.push(JSON.stringify({key:x.id,request:c.args}),`
724
724
  `);for(let n of c.warnings)Z.push({requestId:x.id,warning:n})}let w=await this.getHeaders(Y.headers),S=`${this.batchConfig.baseURL}/${Yu(this.modelId)}:batchGenerateContent`,v;if(E==null){let{value:x}=await W4({url:S,headers:w,body:H,failedResponseHandler:Gz,successfulResponseHandler:Z9(Lv$),abortSignal:Y.abortSignal,fetch:this.batchConfig.fetch});v=x}else{let x=new Blob(E,{type:"application/jsonl"});if(E.length=0,x.size>Zv0)throw new U7({argument:"requests",message:"Google batch input files must not exceed 2 GB."});let{value:c}=await W4({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:TJ(w,{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(x.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${W}-input`}},failedResponseHandler:Gz,successfulResponseHandler:Dv0,abortSignal:Y.abortSignal,fetch:this.batchConfig.fetch}),{value:r}=await iR({url:c,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:x,values:{byteLength:x.size,mediaType:"application/jsonl"}},failedResponseHandler:Gz,successfulResponseHandler:Z9(Uv0),abortSignal:Y.abortSignal,fetch:this.batchConfig.fetch}),{value:n}=await W4({url:S,headers:w,body:{batch:{displayName:W,...Y.webhookUrl!=null&&{webhookConfig:{uris:[Y.webhookUrl]}},inputConfig:{fileName:r.file.name}}},failedResponseHandler:Gz,successfulResponseHandler:Z9(Lv$),abortSignal:Y.abortSignal,fetch:this.batchConfig.fetch});v=n}return{batchId:v.name,...Ov$(v),warnings:Z}}async experimental_doGetBatchStatus(Y){return Ov$(await this.retrieveBatch(Y))}async experimental_doGetBatchResults(Y){var Z,W,z,H,F,P,E,w,S,v;let x=await this.retrieveBatch(Y),c=Ov$(x);if(c.status==="pending")throw new U7({argument:"batchId",message:`Google batch "${Y.batchId}" is not complete.`});let r=(P=(z=(W=(Z=x.metadata)==null?void 0:Z.output)==null?void 0:W.inlinedResponses)==null?void 0:z.inlinedResponses)!=null?P:(F=(H=x.response)==null?void 0:H.inlinedResponses)==null?void 0:F.inlinedResponses;if(r!=null)return PE(this.iterateBatchResults(r.map((A$)=>({key:A$.metadata.key,response:A$.response,error:A$.error}))));let n=(v=(w=(E=x.metadata)==null?void 0:E.output)==null?void 0:w.responsesFile)!=null?v:(S=x.response)==null?void 0:S.responsesFile;if(n==null){if(c.status==="completed")throw new TB({data:x,message:`Google batch "${Y.batchId}" completed without batch output.`});return new ReadableStream({start(A$){A$.close()}})}let B$=n.split("/").map((A$)=>encodeURIComponent(A$)).join("/"),{value:_$}=await aK({url:`${this.getBaseOrigin()}/download/v1beta/${B$}:download?alt=media`,headers:await this.getHeaders(Y.headers),failedResponseHandler:Gz,successfulResponseHandler:em(jv0),abortSignal:Y.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return PE(this.iterateBatchResults(_$))}async retrieveBatch(Y){let{value:Z}=await aK({url:`${this.batchConfig.baseURL}/${Y.batchId}`,headers:await this.getHeaders(Y.headers),failedResponseHandler:Gz,successfulResponseHandler:Z9(Lv$),abortSignal:Y.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return Z}async*iterateBatchResults(Y){var Z,W,z;for await(let H of Y){if(H.error!=null){let S=YP6(H.error,"Google batch request failed."),v=H.error.status==="CANCELLED"||String(H.error.code)==="1"?"cancelled":"failed";yield{id:H.key,status:v,error:S};continue}if(H.response==null){yield{id:H.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let F=await uD({value:H.response,schema:Bv0});if(F.success&&(F.value.candidates==null||F.value.candidates.length===0)){let S=(Z=F.value.promptFeedback)!=null?Z:void 0,v=(W=S==null?void 0:S.blockReason)!=null?W:void 0;yield{id:H.key,status:"failed",error:{message:v==null?"Google returned a batch response without any candidates.":`Google blocked the batch request (${v}).`,code:v==null?"invalid_response":"prompt_blocked",...v!=null?{type:v}:{}},...S!=null?{providerMetadata:{google:{promptFeedback:{blockReason:(z=S.blockReason)!=null?z:null}}}}:{}};continue}let P=await uD({value:H.response,schema:XP6});if(!P.success){yield{id:H.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let E=this.convertGenerateContentResponse({response:P.value,warnings:[],providerOptionsNames:["google"]}),w=E.content.find((S)=>!Wv0.has(S.type));if(w!=null){yield{id:H.key,status:"failed",error:{message:`Google returned a "${w.type}" content block, but that content is not supported in AI SDK text batches.`,code:"unsupported_content"}};continue}yield{id:H.key,status:"succeeded",result:E}}}async getHeaders(Y){return TJ(this.batchConfig.headers?await HK(this.batchConfig.headers):void 0,Y)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,"")}};Fv0=EX({id:"google.code_execution",inputSchema:q.object({language:q.string().describe("The programming language of the code."),code:q.string().describe("The code to be executed.")}),outputSchema:q.object({outcome:q.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:q.string().describe("The output from the code execution.")})}),Av0=EX({id:"google.enterprise_web_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),E51=q.looseObject({fileSearchStoreNames:q.array(q.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:q.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:q.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}),Lv0=EX({id:"google.file_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),Ov0=EX({id:"google.google_maps",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),Pv0=q.looseObject({searchTypes:q.object({webSearch:q.object({}).optional(),imageSearch:q.object({}).optional()}).optional(),timeRangeFilter:q.object({startTime:q.string(),endTime:q.string()}).optional()}),Mv0=EX({id:"google.google_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),Nv0=EX({id:"google.url_context",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),Iv0=EX({id:"google.vertex_rag_store",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),Ev0={googleSearch:Mv0,enterpriseWebSearch:Av0,googleMaps:Ov0,urlContext:Nv0,fileSearch:Lv0,codeExecution:Fv0,vertexRagStore:Iv0},_v0=p0(()=>d0(q.object({googleSearch:Pv0.optional()}))),Tv0=class J{constructor(Y,Z,W){this.modelId=Y,this.settings=Z,this.config=W,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,{},Y.config)}get maxImagesPerCall(){if(this.settings.maxImagesPerCall!=null)return this.settings.maxImagesPerCall;return 10}get provider(){return this.config.provider}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x;if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:c,n:r,size:n,aspectRatio:B$,seed:_$,providerOptions:A$,headers:H$,abortSignal:M$,files:b$,mask:p$}=Y,o$=[];if(p$!=null)throw Error("Gemini image models do not support mask-based image editing.");if(r!=null&&r>1)throw Error("Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.");if(n!=null)o$.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let T6=[];if(c!=null)T6.push({type:"text",text:c});if(b$!=null&&b$.length>0)for(let D1 of b$)if(D1.type==="url")T6.push({type:"file",data:{type:"url",url:new URL(D1.url)},mediaType:"image/*"});else T6.push({type:"file",data:{type:"data",data:typeof D1.data==="string"?D1.data:new Uint8Array(D1.data)},mediaType:D1.mediaType});let j6=[{role:"user",content:T6}],Y6=await dJ({provider:"google",providerOptions:A$,schema:_v0}),{googleSearch:y$,responseModalities:_6,imageConfig:k6,...x$}=(Z=A$==null?void 0:A$.google)!=null?Z:{},m0=await new Pv$(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:(W=this.config.headers)!=null?W:{},fetch:this.config.fetch,generateId:(z=this.config.generateId)!=null?z:wY}).doGenerate({prompt:j6,seed:_$,providerOptions:{google:{...x$,responseModalities:["IMAGE"],imageConfig:B$!=null||k6!=null?{...k6,...B$!=null?{aspectRatio:B$}:{}}:void 0}},tools:(Y6==null?void 0:Y6.googleSearch)!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Y6.googleSearch}]:void 0,headers:H$,abortSignal:M$}),b6=(P=(F=(H=this.config._internal)==null?void 0:H.currentDate)==null?void 0:F.call(H))!=null?P:new Date,W0=[];for(let D1 of m0.content)if(D1.type==="file"&&D1.mediaType.startsWith("image/")&&D1.data.type==="data")W0.push(UY(D1.data.data));let J1=(w=(E=m0.providerMetadata)==null?void 0:E.google)!=null?w:{};return{images:W0,warnings:o$,providerMetadata:{google:{...J1,images:W0.map(()=>({}))}},response:{timestamp:b6,modelId:this.modelId,headers:(S=m0.response)==null?void 0:S.headers},usage:m0.usage?{inputTokens:m0.usage.inputTokens.total,outputTokens:m0.usage.outputTokens.total,totalTokens:((v=m0.usage.inputTokens.total)!=null?v:0)+((x=m0.usage.outputTokens.total)!=null?x:0)}:void 0}}};Sv0=p0(()=>d0(q.object({name:q.string(),displayName:q.string().nullish(),mimeType:q.string(),sizeBytes:q.string().nullish(),createTime:q.string().nullish(),updateTime:q.string().nullish(),expirationTime:q.string().nullish(),sha256Hash:q.string().nullish(),uri:q.string(),state:q.string()}))),Cv0=p0(()=>d0(q.looseObject({displayName:q.string().nullish(),pollIntervalMs:q.number().positive().nullish(),pollTimeoutMs:q.number().positive().nullish()}))),bv0=p0(()=>d0(q.looseObject({pollIntervalMs:q.number().positive().nullish(),pollTimeoutMs:q.number().positive().nullish(),personGeneration:q.enum(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:q.string().nullish(),referenceImages:q.array(q.object({bytesBase64Encoded:q.string().nullish(),gcsUri:q.string().nullish()})).nullish()})));cO6=q.object({name:q.string().nullish(),done:q.boolean().nullish(),error:q.object({code:q.number().nullish(),message:q.string(),status:q.string().nullish()}).nullish(),response:q.object({generateVideoResponse:q.object({generatedSamples:q.array(q.object({video:q.object({uri:q.string().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),mv0=p0(()=>d0(q.object({candidates:q.array(q.object({content:q.object({parts:q.array(q.object({inlineData:q.object({mimeType:q.string().nullish(),data:q.string().nullish()}).nullish()})).nullish()}).nullish()})).nullish()}))),uv0=q.object({voiceName:q.string()}),cv0=q.object({prebuiltVoiceConfig:uv0}),dO6=p0(()=>d0(q.object({multiSpeakerVoiceConfig:q.object({speakerVoiceConfigs:q.array(q.object({speaker:q.string(),voiceConfig:cv0}))}).optional()}))),pv0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({text:Y,voice:Z=dv0,outputFormat:W,instructions:z,speed:H,language:F,providerOptions:P}){let E=[],w=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],S;for(let B$ of w)if(S=await dJ({provider:B$,providerOptions:P,schema:dO6}),S!=null)break;if(S==null&&!w.includes("google"))S=await dJ({provider:"google",providerOptions:P,schema:dO6});let v=S==null?void 0:S.multiSpeakerVoiceConfig,x=v?{multiSpeakerVoiceConfig:v}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:Z}}},c=Y;if(z!=null)if(v)E.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else c=`${z}: ${Y}`;if(H!=null)E.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(F!=null)E.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let r="wav";if(W==="pcm")r="pcm";else if(W!=null&&W!=="wav")E.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${W}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:[{text:c}]}],generationConfig:{responseModalities:["AUDIO"],speechConfig:x}},warnings:E,outputFormat:r}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S;let v=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{requestBody:x,warnings:c,outputFormat:r}=await this.getArgs(Y),{value:n,responseHeaders:B$,rawValue:_$}=await W4({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers),body:x,failedResponseHandler:Gz,successfulResponseHandler:Z9(mv0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),A$,H$;for(let o$ of(H=n.candidates)!=null?H:[]){for(let T6 of(P=(F=o$.content)==null?void 0:F.parts)!=null?P:[])if((E=T6.inlineData)==null?void 0:E.data){A$=T6.inlineData.data,H$=(w=T6.inlineData.mimeType)!=null?w:void 0;break}if(A$!=null)break}let M$=(S=iv0(H$))!=null?S:lv0,b$=A$!=null?BK(A$):new Uint8Array(0),p$=r==="pcm"||b$.length===0?b$:rv0(b$,M$);if(r==="pcm"&&b$.length>0)c.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${M$} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`});return{audio:p$,warnings:c,request:{body:JSON.stringify(x)},response:{timestamp:v,modelId:this.modelId,headers:B$,body:_$},providerMetadata:{google:{sampleRate:M$,mimeType:H$!=null?H$:null}}}}};sv0={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};nv0=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),ov0=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);BP6=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],HP6=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],Iv$=p0(()=>d0(q.object({id:q.string().nullish(),created:q.string().nullish(),updated:q.string().nullish(),status:zP6(),model:q.string().nullish(),agent:q.string().nullish(),steps:q.array(VP6()).nullish(),usage:WP6().nullish(),service_tier:q.string().nullish(),previous_interaction_id:q.string().nullish(),response_modalities:q.array(q.string()).nullish()}).loose())),qP6=p0(()=>d0((()=>{let J=zP6(),Y=UP6(),Z=jP6(),W=q.object({event_type:q.literal("interaction.created"),event_id:q.string().nullish(),interaction:q.object({id:q.string().nullish(),created:q.string().nullish(),model:q.string().nullish(),agent:q.string().nullish(),status:J.nullish()}).loose()}).loose(),z=q.object({event_type:q.literal("step.start"),event_id:q.string().nullish(),index:q.number(),step:VP6()}).loose(),H=q.object({type:q.literal("text"),text:q.string()}).loose(),F=q.object({type:q.literal("thought_summary"),content:Z.nullish()}).loose(),P=q.object({type:q.literal("thought_signature"),signature:q.string().nullish()}).loose(),E=q.object({type:q.literal("arguments_delta"),arguments:q.string().nullish(),id:q.string().nullish(),signature:q.string().nullish()}).loose(),w=q.object({type:q.enum(["text_annotation_delta","text_annotation"]),annotations:q.array(Y).nullish()}).loose(),S=q.object({type:q.literal("image"),data:q.string().nullish(),mime_type:q.string().nullish(),resolution:q.enum(["low","medium","high","ultra_high"]).nullish(),uri:q.string().nullish()}).loose(),v=q.object({type:q.literal("video"),data:q.string().nullish(),mime_type:q.string().nullish(),uri:q.string().nullish()}).loose(),x=q.object({type:q.enum(BP6),id:q.string().nullish(),arguments:q.record(q.string(),q.unknown()).nullish(),name:q.string().nullish(),server_name:q.string().nullish(),search_type:q.string().nullish(),signature:q.string().nullish()}).loose(),c=q.object({type:q.enum(HP6),call_id:q.string().nullish(),result:q.unknown().nullish(),is_error:q.boolean().nullish(),name:q.string().nullish(),server_name:q.string().nullish(),signature:q.string().nullish()}).loose(),r=q.object({type:q.string()}).loose(),n=q.union([H,S,v,F,P,E,w,x,c,r]),B$=q.object({event_type:q.literal("step.delta"),event_id:q.string().nullish(),index:q.number(),delta:n}).loose(),_$=q.object({event_type:q.literal("step.stop"),event_id:q.string().nullish(),index:q.number()}).loose(),A$=q.object({event_type:q.literal("interaction.status_update"),event_id:q.string().nullish(),interaction_id:q.string().nullish(),status:J.nullish()}).loose(),H$=q.object({event_type:q.literal("interaction.in_progress"),event_id:q.string().nullish(),interaction_id:q.string().nullish(),status:J.nullish()}).loose(),M$=q.object({event_type:q.literal("interaction.requires_action"),event_id:q.string().nullish(),interaction_id:q.string().nullish(),status:J.nullish()}).loose(),b$=q.object({event_type:q.literal("interaction.completed"),event_id:q.string().nullish(),interaction:q.object({id:q.string().nullish(),status:J.nullish(),usage:WP6().nullish(),service_tier:q.string().nullish()}).loose()}).loose(),p$=q.object({event_type:q.literal("error"),event_id:q.string().nullish(),error:q.object({code:q.string().nullish(),message:q.string().nullish()}).loose().nullish()}).loose(),o$=q.object({event_type:q.string()}).loose();return q.union([W,z,B$,_$,A$,H$,M$,b$,p$,o$])})())),Zh0=p0(()=>d0(q.object({previousInteractionId:q.string().nullish(),store:q.boolean().nullish(),agent:q.string().nullish(),agentConfig:q.union([q.object({type:q.literal("dynamic")}).loose(),q.object({type:q.literal("deep-research"),thinkingSummaries:q.enum(["auto","none"]).nullish(),visualization:q.enum(["off","auto"]).nullish(),collaborativePlanning:q.boolean().nullish()})]).nullish(),thinkingLevel:q.enum(["minimal","low","medium","high"]).nullish(),thinkingSummaries:q.enum(["auto","none"]).nullish(),responseFormat:q.array(q.union([q.object({type:q.literal("text"),mimeType:q.string().nullish(),schema:q.unknown().nullish()}).loose(),q.object({type:q.literal("image"),mimeType:q.string().nullish(),aspectRatio:q.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:q.enum(["1K","2K","4K","512"]).nullish()}).loose(),q.object({type:q.literal("audio"),mimeType:q.string().nullish()}).loose()])).nullish(),imageConfig:q.object({aspectRatio:q.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:q.enum(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:q.enum(["low","medium","high","ultra_high"]).nullish(),responseModalities:q.array(q.enum(["text","image","audio","video","document"])).nullish(),serviceTier:q.enum(["flex","standard","priority"]).nullish(),systemInstruction:q.string().nullish(),signature:q.string().nullish(),interactionId:q.string().nullish(),pollingTimeoutMs:q.number().int().positive().nullish(),background:q.boolean().nullish(),environment:q.union([q.string(),q.object({type:q.literal("remote"),sources:q.array(q.union([q.object({type:q.literal("gcs"),source:q.string(),target:q.string().nullish()}),q.object({type:q.literal("repository"),source:q.string(),target:q.string().nullish()}),q.object({type:q.literal("inline"),content:q.string(),target:q.string()})])).nullish(),network:q.union([q.literal("disabled"),q.object({allowlist:q.array(q.object({domain:q.string(),transform:q.array(q.record(q.string(),q.string())).nullish()}))})]).nullish()})]).nullish()})));Gh0=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),Wh0=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);Bh0=new Set(["completed","failed","cancelled","incomplete"]);Mh0=class J{constructor(Y,Z){if(this.specificationVersion="v4",typeof Y==="string")this.modelId=Y,this.agent=void 0;else if("managedAgent"in Y)this.modelId=Y.managedAgent,this.agent=Y.managedAgent;else this.modelId=Y.agent,this.agent=Y.agent;this.config=Z}static[Y4](Y){return{...a4({modelId:Y.modelId,config:Y.config}),agent:Y.agent}}static[U4](Y){return new J(Y.agent!=null?{agent:Y.agent}:Y.modelId,Y.config)}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(Y){var Z,W,z,H,F,P,E,w,S,v,x,c,r,n,B$,_$,A$,H$,M$,b$,p$,o$,T6,j6,Y6,y$,_6;let k6=[],x$=await dJ({provider:"google",providerOptions:Y.providerOptions,schema:Zh0}),r0=this.agent!=null;if(!r0){if(Y.frequencyPenalty!=null)k6.push({type:"unsupported",feature:"frequencyPenalty"});if(Y.presencePenalty!=null)k6.push({type:"unsupported",feature:"presencePenalty"})}let m0=Y.tools!=null&&Y.tools.length>0,b6,W0;if(m0){let l8=Fh0({tools:Y.tools,toolChoice:Y.toolChoice});b6=l8.tools,W0=l8.toolChoice,k6.push(...l8.toolWarnings)}let J1=[];if(((Z=Y.responseFormat)==null?void 0:Z.type)==="json")if(r0)k6.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let l8={type:"text",mime_type:"application/json",...Y.responseFormat.schema!=null?{schema:Y.responseFormat.schema}:{}};J1.push(l8)}if((x$==null?void 0:x$.responseFormat)!=null){for(let l8 of x$.responseFormat)if(l8.type==="text")J1.push(EE({type:"text",mime_type:(W=l8.mimeType)!=null?W:void 0,schema:(z=l8.schema)!=null?z:void 0}));else if(l8.type==="image")J1.push(EE({type:"image",mime_type:(H=l8.mimeType)!=null?H:void 0,aspect_ratio:(F=l8.aspectRatio)!=null?F:void 0,image_size:(P=l8.imageSize)!=null?P:void 0}));else if(l8.type==="audio")J1.push(EE({type:"audio",mime_type:(E=l8.mimeType)!=null?E:void 0}))}let{input:D1,systemInstruction:Z0,warnings:B1}=$h0({prompt:Y.prompt,previousInteractionId:(w=x$==null?void 0:x$.previousInteractionId)!=null?w:void 0,store:(S=x$==null?void 0:x$.store)!=null?S:void 0,mediaResolution:(v=x$==null?void 0:x$.mediaResolution)!=null?v:void 0});k6.push(...B1);let x0=Z0,u0=(x=x$==null?void 0:x$.systemInstruction)!=null?x:void 0;if(x0!=null&&u0!=null)k6.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(x0==null&&u0!=null)x0=u0;let G9;if(r0){let l8=[];if(Y.temperature!=null)l8.push("temperature");if(Y.topP!=null)l8.push("topP");if(Y.topK!=null)l8.push("topK");if(Y.frequencyPenalty!=null)l8.push("frequencyPenalty");if(Y.presencePenalty!=null)l8.push("presencePenalty");if(Y.seed!=null)l8.push("seed");if(Y.stopSequences!=null&&Y.stopSequences.length>0)l8.push("stopSequences");if(Y.maxOutputTokens!=null)l8.push("maxOutputTokens");if((x$==null?void 0:x$.thinkingLevel)!=null)l8.push("thinkingLevel");if((x$==null?void 0:x$.thinkingSummaries)!=null)l8.push("thinkingSummaries");if((x$==null?void 0:x$.imageConfig)!=null)l8.push("imageConfig");if(l8.length>0)k6.push({type:"other",message:`google.interactions: ${l8.join(", ")} ${l8.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});G9=void 0}else if(G9=EE({temperature:(c=Y.temperature)!=null?c:void 0,top_p:(r=Y.topP)!=null?r:void 0,top_k:(n=Y.topK)!=null?n:void 0,seed:(B$=Y.seed)!=null?B$:void 0,stop_sequences:Y.stopSequences!=null&&Y.stopSequences.length>0?Y.stopSequences:void 0,max_output_tokens:(_$=Y.maxOutputTokens)!=null?_$:void 0,thinking_level:(A$=x$==null?void 0:x$.thinkingLevel)!=null?A$:void 0,thinking_summaries:(H$=x$==null?void 0:x$.thinkingSummaries)!=null?H$:void 0,tool_choice:W0}),(x$==null?void 0:x$.imageConfig)!=null){let l8=J1.some((L1)=>L1.type==="image");if(k6.push({type:"other",message:l8?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!l8)J1.push({type:"image",mime_type:"image/png",...x$.imageConfig.aspectRatio!=null?{aspect_ratio:x$.imageConfig.aspectRatio}:{},...x$.imageConfig.imageSize!=null?{image_size:x$.imageConfig.imageSize}:{}})}let f1;if(r0&&(x$==null?void 0:x$.agentConfig)!=null){let l8=x$.agentConfig;if(l8.type==="deep-research")f1=EE({type:"deep-research",thinking_summaries:(M$=l8.thinkingSummaries)!=null?M$:void 0,visualization:(b$=l8.visualization)!=null?b$:void 0,collaborative_planning:(p$=l8.collaborativePlanning)!=null?p$:void 0});else if(l8.type==="dynamic")f1={type:"dynamic"}}let l9;if((x$==null?void 0:x$.environment)!=null)if(!r0)k6.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof x$.environment==="string")l9=x$.environment;else{let l8=x$.environment,L1=(o$=l8.sources)==null?void 0:o$.map((SJ)=>{var L6;if(SJ.type==="inline")return{type:"inline",content:SJ.content,target:SJ.target};return EE({type:SJ.type,source:SJ.source,target:(L6=SJ.target)!=null?L6:void 0})}),Q1;if(l8.network==="disabled")Q1="disabled";else if(l8.network!=null)Q1={allowlist:l8.network.allowlist.map((SJ)=>{var L6;return EE({domain:SJ.domain,transform:(L6=SJ.transform)!=null?L6:void 0})})};l9=EE({type:"remote",sources:L1!=null&&L1.length>0?L1:void 0,network:Q1})}return{args:EE({...r0?{agent:this.agent}:{model:this.modelId},input:D1,system_instruction:x0,tools:b6,response_format:J1.length>0?J1:void 0,response_modalities:(x$==null?void 0:x$.responseModalities)!=null?x$.responseModalities:void 0,previous_interaction_id:(T6=x$==null?void 0:x$.previousInteractionId)!=null?T6:void 0,service_tier:(j6=x$==null?void 0:x$.serviceTier)!=null?j6:void 0,store:(Y6=x$==null?void 0:x$.store)!=null?Y6:void 0,generation_config:G9!=null&&Object.keys(G9).length>0?G9:void 0,agent_config:f1,environment:l9,background:(y$=x$==null?void 0:x$.background)!=null?y$:void 0}),warnings:k6,isAgent:r0,isBackground:(x$==null?void 0:x$.background)===!0,pollingTimeoutMs:(_6=x$==null?void 0:x$.pollingTimeoutMs)!=null?_6:void 0}}async doGenerate(Y){var Z,W,z,H,F,P;let{args:E,warnings:w,isAgent:S,pollingTimeoutMs:v}=await this.getArgs(Y),x=`${this.config.baseURL}/interactions`,c=TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers),r=await W4({url:x,headers:c,body:E,failedResponseHandler:Gz,successfulResponseHandler:Z9(Iv$),abortSignal:Y.abortSignal,fetch:this.config.fetch}),{responseHeaders:n,value:B$,rawValue:_$}=r;if(S&&!Ev$(B$.status)){let Y6=await Dh0({baseURL:this.config.baseURL,interactionId:B$.id,headers:c,fetch:this.config.fetch,abortSignal:Y.abortSignal,timeoutMs:v});B$=Y6.response,_$=Y6.rawResponse,n=(Z=Y6.responseHeaders)!=null?Z:n}let A$=typeof B$.id==="string"&&B$.id.length>0?B$.id:void 0,{content:H$,hasFunctionCall:M$}=DP6({steps:(W=B$.steps)!=null?W:null,generateId:(z=this.config.generateId)!=null?z:wY,interactionId:A$}),b$={unified:Cv$({status:B$.status,hasFunctionCall:M$}),raw:B$.status},p$=(F=(H=B$.service_tier)!=null?H:n==null?void 0:n["x-gemini-service-tier"])!=null?F:void 0,o$=QP6(B$.usage),T6={google:{...A$!=null?{interactionId:A$}:{},...p$!=null?{serviceTier:p$}:{},...o$!=null?{outputTokensByModality:o$}:{}}},j6;if(typeof B$.created==="string"){let Y6=new Date(B$.created);if(!Number.isNaN(Y6.getTime()))j6=Y6}return{content:H$,finishReason:b$,usage:Sv$(B$.usage),warnings:w,providerMetadata:T6,request:{body:E},response:{headers:n,body:_$,...A$!=null?{id:A$}:{},...j6?{timestamp:j6}:{},modelId:(P=B$.model)!=null?P:void 0}}}async doStream(Y){var Z;let{args:W,warnings:z,isBackground:H,pollingTimeoutMs:F}=await this.getArgs(Y),P=`${this.config.baseURL}/interactions`,E=TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers);if(H)return this.doStreamBackground({args:W,warnings:z,url:P,mergedHeaders:E,options:Y,pollingTimeoutMs:F});let w={...W,stream:!0},{responseHeaders:S,value:v}=await W4({url:P,headers:E,body:w,failedResponseHandler:Gz,successfulResponseHandler:k2(qP6),abortSignal:Y.abortSignal,fetch:this.config.fetch}),x=S==null?void 0:S["x-gemini-service-tier"],c=lO6({warnings:z,generateId:(Z=this.config.generateId)!=null?Z:wY,includeRawChunks:Y.includeRawChunks,serviceTier:x});return{stream:v.pipeThrough(c),request:{body:w},response:{headers:S}}}async doStreamBackground({args:Y,warnings:Z,url:W,mergedHeaders:z,options:H,pollingTimeoutMs:F}){var P,E;let w=await W4({url:W,headers:z,body:Y,failedResponseHandler:Gz,successfulResponseHandler:Z9(Iv$),abortSignal:H.abortSignal,fetch:this.config.fetch}),{responseHeaders:S,value:v}=w,x=v.id;if(x==null||x.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let c=S==null?void 0:S["x-gemini-service-tier"];if(Ev$(v.status))return{stream:Ph0({response:v,warnings:Z,generateId:(P=this.config.generateId)!=null?P:wY,includeRawChunks:H.includeRawChunks,headerServiceTier:c}),request:{body:Y},response:{headers:S}};let r=Oh0({baseURL:this.config.baseURL,interactionId:x,headers:z,fetch:this.config.fetch,abortSignal:H.abortSignal}),n=lO6({warnings:Z,generateId:(E=this.config.generateId)!=null?E:wY,includeRawChunks:H.includeRawChunks,serviceTier:c});return{stream:r.pipeThrough(n),request:{body:Y},response:{headers:S}}}};Rh0=q.object({languageCodes:q.array(q.string()).optional(),customVocabulary:q.array(q.string()).optional(),wordTimestamp:q.boolean().optional(),diarization:q.boolean().optional(),mode:q.enum(["SMART","VERBATIM"]).optional()});OP6=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async parseOptions(Y){return dJ({provider:"google",providerOptions:Y,schema:Rh0})}async doGenerate(Y){var Z,W,z,H,F,P;if(rO6(this.modelId))throw new U7({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let E=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,w=[],S=await this.parseOptions(Y.providerOptions),v=xh0(S),x={model:this.modelId,input:[{type:"audio",data:UY(Y.audio),mime_type:Y.mediaType}],...v!=null?{generation_config:{transcription_config:v}}:{}},{value:c,responseHeaders:r,rawValue:n}=await W4({url:`${this.config.baseURL}/interactions`,headers:TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers),body:x,failedResponseHandler:Gz,successfulResponseHandler:Z9(vh0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),B$="",_$=[];for(let A$ of(H=c.steps)!=null?H:[])for(let H$ of(F=A$.content)!=null?F:[]){if(H$.type!=="text"||H$.text==null)continue;B$+=H$.text;for(let M$ of(P=H$.annotations)!=null?P:[]){if(M$.type!=="word_info")continue;let b$=sO6(M$.start_offset),p$=sO6(M$.end_offset);if(M$.text==null||b$==null||p$==null)continue;_$.push({text:M$.text,startSecond:b$,endSecond:p$})}}return{text:B$,segments:_$,language:void 0,durationInSeconds:void 0,warnings:w,response:{timestamp:E,modelId:this.modelId,headers:r,body:n},...c.usage!=null?{providerMetadata:{google:{usage:c.usage}}}:{}}}async doStream(Y){var Z,W,z,H,F,P,E;if(!rO6(this.modelId))throw new U7({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let w=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,S=[],v=await this.parseOptions(Y.providerOptions);yh0(Y.inputAudioFormat);let x=TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers),c;for(let[B$,_$]of Object.entries(x))if(B$.toLowerCase()==="x-goog-api-key"&&_$!=null)c=_$;if(c==null)throw Error("Google Generative AI API key is required for streaming transcription.");let r=Object.fromEntries(Object.entries(x).filter(([B$])=>B$.toLowerCase()!=="x-goog-api-key")),n={model:Yu(this.modelId),inputAudioTranscription:(H=kh0(v))!=null?H:{}};return{request:{body:n},response:{timestamp:w,modelId:this.modelId},stream:bh0({webSocket:this.config.webSocket,url:Ch0(this.config.baseURL,c),headers:r,setup:n,inputAudioRate:(F=Y.inputAudioFormat.rate)!=null?F:16000,finishGraceMs:(E=(P=this.config._internal)==null?void 0:P.finishGraceMs)!=null?E:Sh0,warnings:S,audio:Y.audio,abortSignal:Y.abortSignal,includeRawChunks:Y.includeRawChunks})}}};fh0=q.object({type:q.string().nullish(),text:q.string().nullish(),speaker:q.string().nullish(),start_offset:q.string().nullish(),end_offset:q.string().nullish()}),vh0=q.object({status:q.string().nullish(),steps:q.array(q.object({type:q.string().nullish(),content:q.array(q.object({type:q.string().nullish(),text:q.string().nullish(),annotations:q.array(fh0).nullish()})).nullish()})).nullish(),usage:q.record(q.string(),q.unknown()).nullish()}),hh0=p0(()=>d0(q.object({echoTargetLanguage:q.boolean().optional()})));PP6=class J{constructor(Y,Z){this.specificationVersion="v4",this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async doStream(Y){var Z,W,z,H,F,P;if(Y.targetLanguage==null)throw new U7({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let E=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,w=await dJ({provider:"google",providerOptions:Y.providerOptions,schema:hh0}),S=[];if(sh0(Y.inputAudioFormat),Y.sourceLanguage!=null)S.push({type:"unsupported",feature:"sourceLanguage",details:"The Gemini Live translation API auto-detects the source language and does not accept a source language."});if(Y.outputAudioFormat!=null)S.push({type:"unsupported",feature:"outputAudioFormat",details:"The Gemini Live API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let v=TJ(this.config.headers(),Y.headers),x;for(let[n,B$]of Object.entries(v))if(n.toLowerCase()==="x-goog-api-key"&&B$!=null)x=B$;if(x==null)throw Error("Google Generative AI API key is required for streaming translation.");let c=Object.fromEntries(Object.entries(v).filter(([n])=>n.toLowerCase()!=="x-goog-api-key")),r=rh0({modelId:this.modelId,targetLanguage:Y.targetLanguage,providerOptions:w});return{request:{body:r},response:{timestamp:E,modelId:this.modelId},stream:lh0({webSocket:this.config.webSocket,url:dh0(this.config.baseURL,x),headers:c,setup:r,inputAudioRate:(H=Y.inputAudioFormat.rate)!=null?H:16000,finishGraceMs:(P=(F=this.config._internal)==null?void 0:F.finishGraceMs)!=null?P:mh0,warnings:S,audio:Y.audio,abortSignal:Y.abortSignal,includeRawChunks:Y.includeRawChunks})}}};ah0=["text/html","text/css","text/plain","text/xml","text/csv","text/rtf","text/javascript","application/json","application/pdf","image/bmp","image/jpeg","image/png","image/webp","video/mp4","video/mpeg","video/quicktime","video/avi","video/x-flv","video/mpg","video/webm","video/wmv","video/3gpp"],nh0=/^https:\/\/.*$/;th0=MP6()});var bP6={};EW(bP6,{groq:()=>Dg0,createGroq:()=>CP6,browserSearch:()=>wP6,VERSION:()=>SP6});function EP6(J){var Y,Z,W,z,H,F;if(J==null)return mZ();let P=(Y=J.prompt_tokens)!=null?Y:0,E=(W=(Z=J.prompt_tokens_details)==null?void 0:Z.cached_tokens)!=null?W:void 0,w=(z=J.completion_tokens)!=null?z:0,S=(F=(H=J.completion_tokens_details)==null?void 0:H.reasoning_tokens)!=null?F:void 0,v=S!=null?Math.max(0,w-S):w;return{inputTokens:{total:P,noCache:E!=null?P-E:P,cacheRead:E,cacheWrite:void 0},outputTokens:{total:w,text:v,reasoning:S},raw:J}}function eh0(J){var Y;let Z=[];for(let{role:W,content:z}of J)switch(W){case"system":{Z.push({role:"system",content:z});break}case"user":{if(z.length===1&&z[0].type==="text"){Z.push({role:"user",content:z[0].text});break}Z.push({role:"user",content:z.map((H)=>{switch(H.type){case"text":return{type:"text",text:H.text};case"file":switch(H.data.type){case"reference":throw new E9({functionality:"file parts with provider references"});case"text":throw new E9({functionality:"text file parts"});case"url":case"data":{if(C7(H.mediaType)!=="image")throw new E9({functionality:"Non-image file content parts"});return{type:"image_url",image_url:{url:H.data.type==="url"?H.data.url.toString():`data:${hQ({part:H})};base64,${UY(H.data.data)}`}}}}}})});break}case"assistant":{let H="",F="",P=[];for(let E of z)switch(E.type){case"reasoning":{F+=E.text;break}case"text":{H+=E.text;break}case"tool-call":{P.push({id:E.toolCallId,type:"function",function:{name:E.toolName,arguments:JSON.stringify(E.input)}});break}}Z.push({role:"assistant",content:H,...F.length>0?{reasoning:F}:null,...P.length>0?{tool_calls:P}:null});break}case"tool":{for(let H of z){if(H.type==="tool-approval-response")continue;let F=H.output,P;switch(F.type){case"text":case"error-text":P=F.value;break;case"execution-denied":P=(Y=F.reason)!=null?Y:"Tool call execution denied.";break;case"content":case"json":case"error-json":P=JSON.stringify(F.value);break}Z.push({role:"tool",tool_call_id:H.toolCallId,content:P})}break}default:throw Error(`Unsupported role: ${W}`)}return Z}function Jg0(J){return RP6.includes(J)}function Xg0(){return RP6.join(", ")}function Yg0({tools:J,toolChoice:Y,modelId:Z}){J=(J==null?void 0:J.length)?J:void 0;let W=[];if(J==null)return{tools:void 0,toolChoice:void 0,toolWarnings:W};let z=[];for(let F of J)if(F.type==="provider")if(F.id==="groq.browser_search")if(!Jg0(Z))W.push({type:"unsupported",feature:`provider-defined tool ${F.id}`,details:`Browser search is only supported on the following models: ${Xg0()}. Current model: ${Z}`});else z.push({type:"browser_search"});else W.push({type:"unsupported",feature:`provider-defined tool ${F.id}`});else z.push({type:"function",function:{name:F.name,description:F.description,parameters:F.inputSchema,...F.strict!=null?{strict:F.strict}:{}}});if(Y==null)return{tools:z,toolChoice:void 0,toolWarnings:W};let H=Y.type;switch(H){case"auto":case"none":case"required":return{tools:z,toolChoice:H,toolWarnings:W};case"tool":return{tools:z,toolChoice:{type:"function",function:{name:Y.toolName}},toolWarnings:W};default:throw new E9({functionality:`tool choice type: ${H}`})}}function _P6(J){switch(J){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}function Qg0(J,Y){return hF({message:J.message,type:J.type,...Kg0(J.type),data:Y})}function Kg0(J){switch(J){case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"api_error":case"internal_server_error":case"server_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":case"service_unavailable":return{statusCode:503,isRetryable:!0};case"timeout":case"timeout_error":return{statusCode:504,isRetryable:!0};case"authentication_error":case"invalid_api_key":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":case"model_not_found":return{statusCode:404,isRetryable:!1};case"bad_request":case"context_length_exceeded":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}function CP6(J={}){var Y;let Z=(Y=XW(J.baseURL))!=null?Y:"https://api.groq.com/openai/v1",W=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"GROQ_API_KEY",description:"Groq"})}`,...J.headers},`ai-sdk/groq/${SP6}`),z=(E)=>new Zg0(E,{provider:"groq.chat",url:({path:w})=>`${Z}${w}`,headers:W,fetch:J.fetch}),H=(E)=>{if(new.target)throw Error("The Groq model function cannot be called with the new keyword.");return z(E)},F=(E)=>{return new Ug0(E,{provider:"groq.transcription",url:({path:w})=>`${Z}${w}`,headers:W,fetch:J.fetch})},P=function(E){return H(E)};return P.specificationVersion="v4",P.languageModel=H,P.chat=z,P.embeddingModel=(E)=>{throw new CW({modelId:E,modelType:"embeddingModel"})},P.textEmbeddingModel=P.embeddingModel,P.imageModel=(E)=>{throw new CW({modelId:E,modelType:"imageModel"})},P.transcription=F,P.transcriptionModel=F,P.tools=qg0,P}var $g0,TP6,kv$,RP6,Zg0,Gg0,Wg0,zg0,Ug0,jg0,Bg0,Hg0,Vg0=async(J)=>{let{value:Y,responseHeaders:Z}=await Bg0(J),W=Hg0.decode(Y);return{value:{text:W},rawValue:W,responseHeaders:Z}},wP6,qg0,SP6="4.0.33",Dg0;var kP6=n9(()=>{g4();C1();C1();c8();C1();g4();C1();C1();c8();c8();C1();g4();C1();c8();C1();c8();C1();c8();$g0=q.object({reasoningFormat:q.enum(["parsed","raw","hidden"]).optional(),reasoningEffort:q.enum(["none","default","low","medium","high"]).optional(),parallelToolCalls:q.boolean().optional(),user:q.string().optional(),structuredOutputs:q.boolean().optional(),strictJsonSchema:q.boolean().optional(),serviceTier:q.enum(["on_demand","performance","flex","auto"]).optional()}),TP6=q.object({error:q.object({message:q.string(),type:q.string()})}),kv$=b2({errorSchema:TP6,errorToMessage:(J)=>J.error.message}),RP6=["openai/gpt-oss-20b","openai/gpt-oss-120b"];Zg0=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,responseFormat:w,seed:S,reasoning:v,tools:x,toolChoice:c,providerOptions:r}){var n,B$,_$;let A$=[],H$=await dJ({provider:"groq",providerOptions:r,schema:$g0}),M$=(n=H$==null?void 0:H$.structuredOutputs)!=null?n:!0,b$=(B$=H$==null?void 0:H$.strictJsonSchema)!=null?B$:!0;if(H!=null)A$.push({type:"unsupported",feature:"topK"});if((w==null?void 0:w.type)==="json"&&w.schema!=null&&!M$)A$.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let{tools:p$,toolChoice:o$,toolWarnings:T6}=Yg0({tools:x,toolChoice:c,modelId:this.modelId}),j6=H$==null?void 0:H$.reasoningEffort;if(j6==null&&wZ(v))if(v==="none")if(this.modelId==="qwen/qwen3.6-27b")j6="none";else A$.push({type:"unsupported",feature:"reasoning",details:`reasoning "${v}" is not supported by this model.`});else j6=$q({reasoning:v,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high"},warnings:A$});return{args:{model:this.modelId,user:H$==null?void 0:H$.user,parallel_tool_calls:H$==null?void 0:H$.parallelToolCalls,max_tokens:Z,temperature:W,top_p:z,frequency_penalty:F,presence_penalty:P,stop:E,seed:S,response_format:(w==null?void 0:w.type)==="json"?M$&&w.schema!=null?{type:"json_schema",json_schema:{schema:w.schema,strict:b$,name:(_$=w.name)!=null?_$:"response",description:w.description}}:{type:"json_object"}:void 0,reasoning_format:H$==null?void 0:H$.reasoningFormat,reasoning_effort:j6,service_tier:H$==null?void 0:H$.serviceTier,messages:eh0(Y),tools:p$,tool_choice:o$},warnings:[...A$,...T6]}}async doGenerate(Y){var Z,W,z;let{args:H,warnings:F}=await this.getArgs(Y),P=JSON.stringify(H),{responseHeaders:E,value:w,rawValue:S}=await W4({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:H,failedResponseHandler:kv$,successfulResponseHandler:Z9(Gg0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),v=w.choices[0],x=[],c=v.message.content;if(c!=null&&c.length>0)x.push({type:"text",text:c});let r=v.message.reasoning;if(r!=null&&r.length>0)x.push({type:"reasoning",text:r});if(v.message.tool_calls!=null)for(let n of v.message.tool_calls)x.push({type:"tool-call",toolCallId:n.id||wY(),toolName:n.function.name,input:n.function.arguments});return{content:x,finishReason:{unified:_P6(v.finish_reason),raw:(z=v.finish_reason)!=null?z:void 0},usage:EP6(w.usage),response:{...RZ(w),headers:E,body:S},warnings:F,request:{body:P}}}async doStream(Y){var Z,W;let{args:z,warnings:H}=await this.getArgs(Y),F={...z,stream:!0},{responseHeaders:P,value:E}=await W4({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:F,failedResponseHandler:kv$,successfulResponseHandler:k2(Wg0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),w,S={unified:"other",raw:void 0},v=void 0,x=!0,c=!1,r=!1,n;return{stream:E.pipeThrough(new TransformStream({start(B$){w=new WM(B$,{generateId:wY,typeValidation:"required"}),B$.enqueue({type:"stream-start",warnings:H})},transform(B$,_$){var A$;if(Y.includeRawChunks)_$.enqueue({type:"raw",rawValue:B$.rawValue});if(!B$.success){S={unified:"error",raw:void 0},_$.enqueue({type:"error",error:B$.error});return}let H$=B$.value;if("error"in H$){S={unified:"error",raw:void 0},_$.enqueue({type:"error",error:Qg0(H$.error,H$)});return}if(x)x=!1,_$.enqueue({type:"response-metadata",...RZ(H$)});if(((A$=H$.x_groq)==null?void 0:A$.usage)!=null)v=H$.x_groq.usage;let M$=H$.choices[0];if((M$==null?void 0:M$.finish_reason)!=null)S={unified:_P6(M$.finish_reason),raw:M$.finish_reason};if((M$==null?void 0:M$.delta)==null)return;let b$=M$.delta;if(b$.reasoning!=null&&b$.reasoning.length>0){if(!r)_$.enqueue({type:"reasoning-start",id:"reasoning-0"}),r=!0;_$.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:b$.reasoning})}if(b$.content!=null&&b$.content.length>0){if(r)_$.enqueue({type:"reasoning-end",id:"reasoning-0"}),r=!1;if(!c)_$.enqueue({type:"text-start",id:"txt-0"}),c=!0;_$.enqueue({type:"text-delta",id:"txt-0",delta:b$.content})}if(b$.tool_calls!=null){if(r)_$.enqueue({type:"reasoning-end",id:"reasoning-0"}),r=!1;for(let p$ of b$.tool_calls)w.processDelta(p$)}},flush(B$){if(r)B$.enqueue({type:"reasoning-end",id:"reasoning-0"});if(c)B$.enqueue({type:"text-end",id:"txt-0"});w.flush(),B$.enqueue({type:"finish",finishReason:S,usage:EP6(v),...n!=null?{providerMetadata:n}:{}})}})),request:{body:JSON.stringify(F)},response:{headers:P}}}},Gg0=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({message:q.object({content:q.string().nullish(),reasoning:q.string().nullish(),tool_calls:q.array(q.object({id:q.string().nullish(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),index:q.number(),finish_reason:q.string().nullish()})),usage:q.object({prompt_tokens:q.number().nullish(),completion_tokens:q.number().nullish(),total_tokens:q.number().nullish(),prompt_tokens_details:q.object({cached_tokens:q.number().nullish()}).nullish(),completion_tokens_details:q.object({reasoning_tokens:q.number().nullish()}).nullish()}).nullish()}),Wg0=q.union([q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({delta:q.object({content:q.string().nullish(),reasoning:q.string().nullish(),tool_calls:q.array(q.object({index:q.number(),id:q.string().nullish(),type:q.literal("function").optional(),function:q.object({name:q.string().nullish(),arguments:q.string().nullish()})})).nullish()}).nullish(),finish_reason:q.string().nullable().optional(),index:q.number()})),x_groq:q.object({usage:q.object({prompt_tokens:q.number().nullish(),completion_tokens:q.number().nullish(),total_tokens:q.number().nullish(),prompt_tokens_details:q.object({cached_tokens:q.number().nullish()}).nullish(),completion_tokens_details:q.object({reasoning_tokens:q.number().nullish()}).nullish()}).nullish()}).nullish()}),TP6]),zg0=p0(()=>d0(q.object({language:q.string().nullish(),prompt:q.string().nullish(),responseFormat:q.string().nullish(),temperature:q.number().min(0).max(1).nullish(),timestampGranularities:q.array(q.string()).nullish()}))),Ug0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}get provider(){return this.config.provider}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async getArgs({audio:Y,mediaType:Z,providerOptions:W}){var z,H,F,P,E;let w=[],S=await dJ({provider:"groq",providerOptions:W,schema:zg0}),v=new FormData,x=Y instanceof Uint8Array?new Blob([Y]):new Blob([BK(Y)]);v.append("model",this.modelId);let c=lR(Z);if(v.append("file",new File([x],"audio",{type:Z}),`audio.${c}`),S){let r={language:(z=S.language)!=null?z:void 0,prompt:(H=S.prompt)!=null?H:void 0,response_format:(F=S.responseFormat)!=null?F:void 0,temperature:(P=S.temperature)!=null?P:void 0,timestamp_granularities:(E=S.timestampGranularities)!=null?E:void 0};for(let n in r){let B$=r[n];if(B$!==void 0)if(Array.isArray(B$))for(let _$ of B$)v.append(`${n}[]`,String(_$));else v.append(n,String(B$))}}return{formData:v,responseFormat:S==null?void 0:S.responseFormat,warnings:w}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x;let c=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{formData:r,responseFormat:n,warnings:B$}=await this.getArgs(Y),_$=n==="text"?Vg0:Z9(jg0),{value:A$,responseHeaders:H$,rawValue:M$}=await nK({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:TJ((F=(H=this.config).headers)==null?void 0:F.call(H),Y.headers),formData:r,failedResponseHandler:kv$,successfulResponseHandler:_$,abortSignal:Y.abortSignal,fetch:this.config.fetch});return{text:A$.text,segments:(S=(w=(P=A$.segments)==null?void 0:P.map((b$)=>({text:b$.text,startSecond:b$.start,endSecond:b$.end})))!=null?w:(E=A$.words)==null?void 0:E.map((b$)=>({text:b$.word,startSecond:b$.start,endSecond:b$.end})))!=null?S:[],language:(v=A$.language)!=null?v:void 0,durationInSeconds:(x=A$.duration)!=null?x:void 0,warnings:B$,response:{timestamp:c,modelId:this.modelId,headers:H$,body:M$}}}},jg0=q.object({text:q.string(),x_groq:q.object({id:q.string()}),task:q.string().nullish(),language:q.string().nullish(),duration:q.number().nullish(),segments:q.array(q.object({id:q.number(),seek:q.number(),start:q.number(),end:q.number(),text:q.string(),tokens:q.array(q.number()),temperature:q.number(),avg_logprob:q.number(),compression_ratio:q.number(),no_speech_prob:q.number()})).nullish(),words:q.array(q.object({word:q.string(),start:q.number(),end:q.number()})).nullish()}),Bg0=rR(),Hg0=new TextDecoder,wP6=EX({id:"groq.browser_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:p0(()=>d0(q.object({})))}),qg0={browserSearch:wP6};Dg0=CP6()});var vP6={};EW(vP6,{createCerebras:()=>fP6,cerebras:()=>Pg0,VERSION:()=>yP6});function xP6({rawFinishReason:J,hasText:Y,responseFormatType:Z}){return Z==="json"&&J==="tool_calls"&&Y}function Og0(J){let{max_tokens:Y,parallelToolCalls:Z,topLogprobs:W,logitBias:z,serviceTier:H,reasoningFormat:F,promptCacheKey:P,...E}=J;return{...E,...Y!==void 0&&{max_completion_tokens:Y},...Z!==void 0&&{parallel_tool_calls:Z},...W!==void 0&&{top_logprobs:W},...z!==void 0&&{logit_bias:z},...H!==void 0&&{service_tier:H},...F!==void 0&&{reasoning_format:F},...P!==void 0&&{prompt_cache_key:P},messages:Array.isArray(J.messages)?J.messages.map((w)=>{if(w==null||typeof w!=="object"||w.role!=="assistant"||!("reasoning_content"in w))return w;let{reasoning_content:S,...v}=w;return{...v,...!("reasoning"in v)&&S!==void 0?{reasoning:S}:{}}}):J.messages}}function fP6(J={}){var Y;let Z=XW((Y=J.baseURL)!=null?Y:"https://api.cerebras.ai/v1"),W=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"CEREBRAS_API_KEY",description:"Cerebras API key"})}`,...J.headers},`ai-sdk/cerebras/${yP6}`),z=(F)=>{return new Fg0(F,{provider:"cerebras.chat",url:({path:P})=>`${Z}${P}`,headers:W,fetch:J.fetch,errorStructure:Lg0,supportsStructuredOutputs:!0,transformRequestBody:Og0})},H=(F)=>z(F);return H.specificationVersion="v4",H.languageModel=z,H.chat=z,H.embeddingModel=(F)=>{throw new CW({modelId:F,modelType:"embeddingModel"})},H.textEmbeddingModel=H.embeddingModel,H.imageModel=(F)=>{throw new CW({modelId:F,modelType:"imageModel"})},H}var Fg0,yP6="3.0.39",Ag0,Lg0,Pg0;var hP6=n9(()=>{g4();C1();KZ$();C1();c8();Fg0=class J extends Ju{static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async doGenerate(Y){var Z;let W=await super.doGenerate(Y);if(!xP6({rawFinishReason:W.finishReason.raw,hasText:W.content.some((z)=>z.type==="text"&&z.text.length>0),responseFormatType:(Z=Y.responseFormat)==null?void 0:Z.type}))return W;return{...W,content:W.content.filter((z)=>z.type!=="tool-call"),finishReason:{...W.finishReason,unified:"stop"}}}async doStream(Y){let Z=await super.doStream(Y),W=!1;return{...Z,stream:Z.stream.pipeThrough(new TransformStream({transform(z,H){var F,P;if(z.type==="text-delta"&&z.delta.length>0)W=!0;if(z.type==="finish"&&xP6({rawFinishReason:z.finishReason.raw,hasText:W,responseFormatType:(F=Y.responseFormat)==null?void 0:F.type})){H.enqueue({...z,finishReason:{...z.finishReason,unified:"stop"}});return}if(((P=Y.responseFormat)==null?void 0:P.type)==="json"&&W&&(z.type==="tool-input-start"||z.type==="tool-input-delta"||z.type==="tool-input-end"||z.type==="tool-call"))return;H.enqueue(z)}}))}}},Ag0=q.object({message:q.string(),type:q.string(),param:q.string(),code:q.string()}),Lg0={errorSchema:Ag0,errorToMessage:(J)=>J.message};Pg0=fP6()});var sP6={};EW(sP6,{mistral:()=>hg0,createMistral:()=>rP6,VERSION:()=>iP6});function gP6(J){var Y,Z,W,z,H;if(J==null)return mZ();let{prompt_tokens:F,completion_tokens:P}=J,E=(H=(z=(Z=J.num_cached_tokens)!=null?Z:(Y=J.prompt_tokens_details)==null?void 0:Y.cached_tokens)!=null?z:(W=J.prompt_token_details)==null?void 0:W.cached_tokens)!=null?H:0;return{inputTokens:{total:F,noCache:F-E,cacheRead:E||void 0,cacheWrite:void 0},outputTokens:{total:P,text:P,reasoning:void 0},raw:J}}function mP6({part:J}){if(J.data.type==="url")return J.data.url.toString();if(J.data.type==="data")return`data:${hQ({part:J})};base64,${UY(J.data.data)}`;throw new E9({functionality:`file part data type ${J.data.type}`})}function Mg0(J){var Y;let Z=[];for(let W=0;W<J.length;W++){let{role:z,content:H}=J[W],F=W===J.length-1;switch(z){case"system":{Z.push({role:"system",content:H});break}case"user":{Z.push({role:"user",content:H.map((P)=>{switch(P.type){case"text":return{type:"text",text:P.text};case"file":switch(P.data.type){case"reference":throw new E9({functionality:"file parts with provider references"});case"text":throw new E9({functionality:"text file parts"});case"url":case"data":if(C7(P.mediaType)==="image")return{type:"image_url",image_url:mP6({part:P})};else{if(P.data.type==="data"){if(hQ({part:P})!=="application/pdf")throw new E9({functionality:"Only images and PDF file parts are supported"})}else if(P.mediaType!=="application/pdf")throw new E9({functionality:"Only images and PDF file parts are supported"});return{type:"document_url",document_url:mP6({part:P})}}}}})});break}case"assistant":{let P="",E=!1,w=[],S=[];for(let v of H)switch(v.type){case"text":{P+=v.text,w.push({type:"text",text:v.text});break}case"tool-call":{S.push({id:v.toolCallId,type:"function",function:{name:v.toolName,arguments:JSON.stringify(v.input)}});break}case"reasoning":{E=!0,w.push({type:"thinking",thinking:[{type:"text",text:v.text}],closed:!0});break}default:throw Error(`Unsupported content type in assistant message: ${v.type}`)}Z.push({role:"assistant",content:E?w:P,prefix:F?!0:void 0,tool_calls:S.length>0?S:void 0});break}case"tool":{for(let P of H){if(P.type==="tool-approval-response")continue;let E=P.output,w;switch(E.type){case"text":case"error-text":w=E.value;break;case"execution-denied":w=(Y=E.reason)!=null?Y:"Tool call execution denied.";break;case"content":case"json":case"error-json":w=JSON.stringify(E.value);break}Z.push({role:"tool",name:P.toolName,tool_call_id:P.toolCallId,content:w})}break}default:throw Error(`Unsupported role: ${z}`)}}return Z}function uP6(J){switch(J){case"stop":return"stop";case"length":case"model_length":return"length";case"tool_calls":return"tool-calls";default:return"other"}}function Eg0({tools:J,toolChoice:Y}){J=(J==null?void 0:J.length)?J:void 0;let Z=[];if(J==null)return{tools:void 0,toolChoice:void 0,toolWarnings:Z};let W=[];for(let H of J)if(H.type==="provider")Z.push({type:"unsupported",feature:`provider-defined tool ${H.id}`});else W.push({type:"function",function:{name:H.name,description:H.description,parameters:H.inputSchema,...H.strict!=null?{strict:H.strict}:{}}});if(Y==null)return{tools:W,toolChoice:void 0,toolWarnings:Z};let z=Y.type;switch(z){case"auto":case"none":return{tools:W,toolChoice:z,toolWarnings:Z};case"required":return{tools:W,toolChoice:"any",toolWarnings:Z};case"tool":return{tools:W.filter((H)=>H.function.name===Y.toolName),toolChoice:"any",toolWarnings:Z};default:throw new E9({functionality:`tool choice type: ${z}`})}}function cP6(J){return J.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join("")}function dP6(J){if(typeof J==="string")return J;if(J==null)return;let Y=[];for(let Z of J){let{type:W}=Z;switch(W){case"text":Y.push(Z.text);break;case"thinking":case"image_url":case"reference":break;default:throw Error(`Unsupported type: ${W}`)}}return Y.length?Y.join(""):void 0}function io(J,Y,Z){if(Z==null)return;if(Array.isArray(Z)){for(let W of Z)J.append(Y,W);return}J.append(Y,String(Z))}function rP6(J={}){var Y;let Z=(Y=XW(J.baseURL))!=null?Y:"https://api.mistral.ai/v1",W=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"MISTRAL_API_KEY",description:"Mistral"})}`,...J.headers},`ai-sdk/mistral/${iP6}`),z=(w)=>new _g0(w,{provider:"mistral.chat",baseURL:Z,headers:W,fetch:J.fetch,generateId:J.generateId}),H=(w)=>new Sg0(w,{provider:"mistral.embedding",baseURL:Z,headers:W,fetch:J.fetch}),F=(w)=>new kg0(w,{provider:"mistral.speech",baseURL:Z,headers:W,fetch:J.fetch}),P=(w)=>new fg0(w,{provider:"mistral.transcription",baseURL:Z,headers:W,fetch:J.fetch}),E=function(w){if(new.target)throw Error("The Mistral model function cannot be called with the new keyword.");return z(w)};return E.specificationVersion="v4",E.languageModel=z,E.chat=z,E.embedding=H,E.embeddingModel=H,E.textEmbedding=H,E.textEmbeddingModel=H,E.speech=F,E.speechModel=F,E.transcription=P,E.transcriptionModel=P,E.imageModel=(w)=>{throw new CW({modelId:w,modelType:"imageModel"})},E}var Ng0,Ig0,ro,_g0,lP6,pP6,Tg0,Rg0,wg0,Sg0,Cg0,bg0,kg0,xg0,yg0,fg0,vg0,iP6="4.0.35",hg0;var aP6=n9(()=>{g4();C1();C1();c8();C1();g4();C1();C1();c8();C1();c8();g4();g4();C1();c8();c8();C1();c8();c8();g4();C1();c8();C1();c8();Ng0=q.object({safePrompt:q.boolean().optional(),documentImageLimit:q.number().optional(),documentPageLimit:q.number().optional(),structuredOutputs:q.boolean().optional(),strictJsonSchema:q.boolean().optional(),parallelToolCalls:q.boolean().optional(),promptCacheKey:q.string().optional(),reasoningEffort:q.enum(["high","none"]).optional()}),Ig0=q.object({object:q.literal("error"),message:q.string(),type:q.string(),param:q.string().nullable(),code:q.string().nullable()}),ro=b2({errorSchema:Ig0,errorToMessage:(J)=>J.message});_g0=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"application/pdf":[/^https:\/\/.*$/]};var W;this.modelId=Y,this.config=Z,this.generateId=(W=Z.generateId)!=null?W:wY}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,reasoning:E,stopSequences:w,responseFormat:S,seed:v,providerOptions:x,tools:c,toolChoice:r}){var n,B$,_$,A$,H$;let M$=[],b$=(n=await dJ({provider:"mistral",providerOptions:x,schema:Ng0}))!=null?n:{};if(H!=null)M$.push({type:"unsupported",feature:"topK"});let p$=this.modelId==="mistral-small-latest"||this.modelId==="mistral-small-2603"||this.modelId==="mistral-medium-3"||this.modelId==="mistral-medium-3.5",o$;if(p$)o$=(B$=b$.reasoningEffort)!=null?B$:wZ(E)?E==="none"?"none":$q({reasoning:E,effortMap:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high"},warnings:M$}):void 0;else if(wZ(E))M$.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let T6=(_$=b$.structuredOutputs)!=null?_$:!0,j6=(A$=b$.strictJsonSchema)!=null?A$:!1;if((S==null?void 0:S.type)==="json"&&!(S==null?void 0:S.schema))Y=kA6({messages:Y,schema:S.schema});let Y6={model:this.modelId,safe_prompt:b$.safePrompt,max_tokens:Z,temperature:W,top_p:z,...F!=null?{frequency_penalty:F}:{},...P!=null?{presence_penalty:P}:{},stop:w,random_seed:v,reasoning_effort:o$,response_format:(S==null?void 0:S.type)==="json"?T6&&(S==null?void 0:S.schema)!=null?{type:"json_schema",json_schema:{schema:S.schema,strict:j6,name:(H$=S.name)!=null?H$:"response",description:S.description}}:{type:"json_object"}:void 0,document_image_limit:b$.documentImageLimit,document_page_limit:b$.documentPageLimit,...b$.promptCacheKey!==void 0?{prompt_cache_key:b$.promptCacheKey}:{},messages:Mg0(Y)},{tools:y$,toolChoice:_6,toolWarnings:k6}=Eg0({tools:c,toolChoice:r});return{args:{...Y6,tools:y$,tool_choice:_6,...y$!=null&&b$.parallelToolCalls!==void 0?{parallel_tool_calls:b$.parallelToolCalls}:{}},warnings:[...M$,...k6]}}async doGenerate(Y){var Z,W,z;let{args:H,warnings:F}=await this.getArgs(Y),{responseHeaders:P,value:E,rawValue:w}=await W4({url:`${this.config.baseURL}/chat/completions`,headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:H,failedResponseHandler:ro,successfulResponseHandler:Z9(Tg0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),S=E.choices[0],v=[];if(S.message.content!=null&&Array.isArray(S.message.content)){for(let x of S.message.content)if(x.type==="thinking"){let c=cP6(x.thinking);if(c.length>0)v.push({type:"reasoning",text:c})}else if(x.type==="text"){if(x.text.length>0)v.push({type:"text",text:x.text})}}else{let x=dP6(S.message.content);if(x!=null&&x.length>0)v.push({type:"text",text:x})}if(S.message.tool_calls!=null)for(let x of S.message.tool_calls)v.push({type:"tool-call",toolCallId:x.id,toolName:x.function.name,input:x.function.arguments});return{content:v,finishReason:{unified:uP6(S.finish_reason),raw:(z=S.finish_reason)!=null?z:void 0},usage:gP6(E.usage),request:{body:H},response:{...RZ(E),headers:P,body:w},warnings:F}}async doStream(Y){var Z,W;let{args:z,warnings:H}=await this.getArgs(Y),F={...z,stream:!0},{responseHeaders:P,value:E}=await W4({url:`${this.config.baseURL}/chat/completions`,headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:F,failedResponseHandler:ro,successfulResponseHandler:k2(Rg0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),w={unified:"other",raw:void 0},S=void 0,v=!0,x=!1,c=null,r,n=this.generateId;return{stream:E.pipeThrough(new TransformStream({start(B$){r=new WM(B$,{generateId:n}),B$.enqueue({type:"stream-start",warnings:H})},transform(B$,_$){if(Y.includeRawChunks)_$.enqueue({type:"raw",rawValue:B$.rawValue});if(!B$.success){_$.enqueue({type:"error",error:B$.error});return}let A$=B$.value;if(v)v=!1,_$.enqueue({type:"response-metadata",...RZ(A$)});if(A$.usage!=null)S=A$.usage;let H$=A$.choices[0],M$=H$.delta,b$=dP6(M$.content);if(M$.content!=null&&Array.isArray(M$.content)){for(let p$ of M$.content)if(p$.type==="thinking"){let o$=cP6(p$.thinking);if(o$.length>0){if(c==null){if(x)_$.enqueue({type:"text-end",id:"0"}),x=!1;c=n(),_$.enqueue({type:"reasoning-start",id:c})}_$.enqueue({type:"reasoning-delta",id:c,delta:o$})}}}if(b$!=null&&b$.length>0){if(!x){if(c!=null)_$.enqueue({type:"reasoning-end",id:c}),c=null;_$.enqueue({type:"text-start",id:"0"}),x=!0}_$.enqueue({type:"text-delta",id:"0",delta:b$})}if((M$==null?void 0:M$.tool_calls)!=null)for(let p$ of M$.tool_calls)r.processDelta(p$);if(H$.finish_reason!=null)w={unified:uP6(H$.finish_reason),raw:H$.finish_reason}},flush(B$){if(c!=null)B$.enqueue({type:"reasoning-end",id:c});if(x)B$.enqueue({type:"text-end",id:"0"});r.flush(),B$.enqueue({type:"finish",finishReason:w,usage:gP6(S)})}})),request:{body:F},response:{headers:P}}}};lP6=q.union([q.string(),q.array(q.discriminatedUnion("type",[q.object({type:q.literal("text"),text:q.string()}),q.object({type:q.literal("image_url"),image_url:q.union([q.string(),q.object({url:q.string(),detail:q.string().nullable()})])}),q.object({type:q.literal("reference"),reference_ids:q.array(q.union([q.string(),q.number()]))}),q.object({type:q.literal("thinking"),thinking:q.array(q.object({type:q.literal("text"),text:q.string()}))})]))]).nullish(),pP6=q.object({prompt_tokens:q.number(),completion_tokens:q.number(),total_tokens:q.number(),num_cached_tokens:q.number().nullish(),prompt_tokens_details:q.object({cached_tokens:q.number().nullish()}).nullish(),prompt_token_details:q.object({cached_tokens:q.number().nullish()}).nullish()}),Tg0=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({message:q.object({role:q.literal("assistant"),content:lP6,tool_calls:q.array(q.object({id:q.string(),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),index:q.number(),finish_reason:q.string().nullish()})),object:q.literal("chat.completion"),usage:pP6}),Rg0=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({delta:q.object({role:q.enum(["assistant"]).optional(),content:lP6,tool_calls:q.array(q.object({index:q.number().nullish(),id:q.string().nullish(),function:q.object({name:q.string().nullish(),arguments:q.string().nullish()})})).nullish()}),finish_reason:q.string().nullish(),index:q.number()})),usage:pP6.nullish()}),wg0=q.object({metadata:q.record(q.string(),q.any()).optional(),outputDimension:q.number().int().positive().optional(),outputDtype:q.enum(["float","int8","uint8","binary","ubinary"]).optional()}),Sg0=class J{constructor(Y,Z){this.specificationVersion="v4",this.maxEmbeddingsPerCall=32,this.supportsParallelCalls=!1,this.modelId=Y,this.config=Z}get provider(){return this.config.provider}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async doEmbed({values:Y,abortSignal:Z,headers:W,providerOptions:z}){var H,F,P;if(Y.length>this.maxEmbeddingsPerCall)throw new JM({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Y});let E=(H=await dJ({provider:"mistral",providerOptions:z,schema:wg0}))!=null?H:{},{responseHeaders:w,value:S,rawValue:v}=await W4({url:`${this.config.baseURL}/embeddings`,headers:TJ((P=(F=this.config).headers)==null?void 0:P.call(F),W),body:{model:this.modelId,input:Y,metadata:E.metadata,output_dimension:E.outputDimension,output_dtype:E.outputDtype,encoding_format:"float"},failedResponseHandler:ro,successfulResponseHandler:Z9(Cg0),abortSignal:Z,fetch:this.config.fetch});return{warnings:[],embeddings:S.data.map((x)=>x.embedding),usage:S.usage?{tokens:S.usage.prompt_tokens}:void 0,response:{headers:w,body:v}}}},Cg0=q.object({data:q.array(q.object({embedding:q.array(q.number())})),usage:q.object({prompt_tokens:q.number()}).nullish()}),bg0=q.object({refAudio:q.string().min(1).optional()}),kg0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({text:Y,voice:Z,outputFormat:W="mp3",instructions:z,speed:H,language:F,providerOptions:P}){let E=[],w=await dJ({provider:"mistral",providerOptions:P,schema:bg0}),S="mp3";if(["pcm","wav","mp3","flac","opus"].includes(W))S=W;else E.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${W}. Using mp3 instead.`});if(z!=null)E.push({type:"unsupported",feature:"instructions",details:"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery."});if(H!=null)E.push({type:"unsupported",feature:"speed",details:"Mistral speech models do not support the `speed` option. It was ignored."});if(F!=null)E.push({type:"unsupported",feature:"language",details:"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice."});let v=w==null?void 0:w.refAudio,x={model:this.modelId,input:Y,voice_id:v==null?Z:void 0,ref_audio:v,response_format:S,stream:!1},c={...x,ref_audio:v==null?void 0:"[redacted]"};return{requestBody:x,requestBodyValues:c,warnings:E}}async doGenerate(Y){var Z,W,z,H,F;let P=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{requestBody:E,requestBodyValues:w,warnings:S}=await this.getArgs(Y),{value:v,responseHeaders:x,rawValue:c}=await iR({url:`${this.config.baseURL}/audio/speech`,headers:TJ({"Content-Type":"application/json"},(F=(H=this.config).headers)==null?void 0:F.call(H),Y.headers),body:{content:JSON.stringify(E),values:w},failedResponseHandler:ro,successfulResponseHandler:Z9(xg0),abortSignal:Y.abortSignal,fetch:this.config.fetch});return{audio:v.audio_data,warnings:S,request:{body:JSON.stringify(w)},response:{timestamp:P,modelId:this.modelId,headers:x,body:c}}}},xg0=q.object({audio_data:q.string()}),yg0=p0(()=>d0(q.object({language:q.string().min(1).optional(),temperature:q.number().optional(),timestampGranularities:q.array(q.enum(["segment","word"])).min(1).optional(),diarize:q.boolean().optional(),contextBias:q.array(q.string().min(1).regex(/^[^\s,]+$/,"Context bias items must not contain commas or whitespace.")).max(100).optional()}))),fg0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({audio:Y,mediaType:Z,providerOptions:W}){let z=[],H=await dJ({provider:"mistral",providerOptions:W,schema:yg0});if((H==null?void 0:H.language)!=null&&H.timestampGranularities!=null)throw new U7({argument:"providerOptions",message:"providerOptions.mistral.language cannot be combined with providerOptions.mistral.timestampGranularities"});let F=new FormData,P=Y instanceof Uint8Array?new Blob([Y]):new Blob([BK(Y)]);if(F.append("model",this.modelId),F.append("file",new File([P],"audio",{type:Z}),`audio.${lR(Z)}`),H!=null)io(F,"language",H.language),io(F,"temperature",H.temperature),io(F,"timestamp_granularities",H.timestampGranularities),io(F,"diarize",H.diarize),io(F,"context_bias",H.contextBias);return{formData:F,warnings:z}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x,c,r;let n=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{formData:B$,warnings:_$}=await this.getArgs(Y),{value:A$,responseHeaders:H$,rawValue:M$}=await nK({url:`${this.config.baseURL}/audio/transcriptions`,headers:TJ((F=(H=this.config).headers)==null?void 0:F.call(H),Y.headers),formData:B$,failedResponseHandler:ro,successfulResponseHandler:Z9(vg0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),b$=(E=(P=A$.segments)==null?void 0:P.map((T6)=>({text:T6.text,startSecond:T6.start,endSecond:T6.end})))!=null?E:[],p$={};if(A$.usage!=null)p$.usage={...A$.usage.prompt_tokens!=null&&{promptTokens:A$.usage.prompt_tokens},...A$.usage.completion_tokens!=null&&{completionTokens:A$.usage.completion_tokens},...A$.usage.total_tokens!=null&&{totalTokens:A$.usage.total_tokens},...A$.usage.prompt_audio_seconds!=null&&{promptAudioSeconds:A$.usage.prompt_audio_seconds},...A$.usage.request_count!=null&&{requestCount:A$.usage.request_count}};let o$=(w=A$.segments)==null?void 0:w.filter((T6)=>T6.type!=null||T6.score!=null||T6.speaker_id!=null).map((T6)=>({text:T6.text,startSecond:T6.start,endSecond:T6.end,...T6.type!=null&&{type:T6.type},...T6.score!=null&&{score:T6.score},...T6.speaker_id!=null&&{speakerId:T6.speaker_id}}));if(o$!=null&&o$.length>0)p$.segments=o$;return{text:A$.text,segments:b$,language:(S=A$.language)!=null?S:void 0,durationInSeconds:(r=(c=(v=A$.usage)==null?void 0:v.prompt_audio_seconds)!=null?c:(x=b$.at(-1))==null?void 0:x.endSecond)!=null?r:void 0,warnings:_$,response:{timestamp:n,modelId:A$.model,headers:H$,body:M$},...Object.keys(p$).length>0&&{providerMetadata:{mistral:p$}}}}};vg0=q.object({model:q.string(),text:q.string(),language:q.string().nullish(),segments:q.array(q.object({type:q.literal("transcription_segment").nullish(),text:q.string(),start:q.number(),end:q.number(),score:q.number().nullish(),speaker_id:q.string().nullish()})).nullish(),usage:q.object({prompt_tokens:q.number().nullish(),completion_tokens:q.number().nullish(),total_tokens:q.number().nullish(),prompt_audio_seconds:q.number().nullish(),request_count:q.number().nullish()}).nullish()});hg0=rP6()});var ZM6={};EW(ZM6,{deepseek:()=>zm0,deepSeek:()=>zm0,createDeepSeek:()=>KM6,VERSION:()=>QM6});async function lg0({prompt:J,responseFormat:Y,modelId:Z,providerOptionsName:W="deepseek",supportsAssistantPrefixCompletion:z=!1,supportsStructuredOutputs:H=!1}){var F;let P=Z.includes("deepseek-v4"),E=[],w=[];if((Y==null?void 0:Y.type)==="json"){if(Y.schema==null)E.push({role:"system",content:"Return JSON."});else if(!H)E.push({role:"system",content:"Return JSON that conforms to the following schema: "+JSON.stringify(Y.schema)}),w.push({type:"compatibility",feature:"responseFormat JSON schema",details:"JSON response schema is injected into the system message."})}let S=-1;for(let x=J.length-1;x>=0;x--)if(J[x].role==="user"){S=x;break}let v=-1;for(let{role:x,content:c,providerOptions:r}of J){v++;let n=await dJ({provider:W,providerOptions:r,schema:cg0});if((n==null?void 0:n.prefix)===!0&&x!=="assistant")throw new $M({prompt:J,message:"DeepSeek assistant prefix completion requires `prefix: true` on an assistant message."});switch(x){case"system":{E.push({role:"system",content:c,...(n==null?void 0:n.name)!=null&&{name:n.name}});break}case"user":{if(!c.some((A$)=>A$.type==="file"&&(A$.data.type==="reference"||A$.data.type==="url"||A$.data.type==="data")&&C7(A$.mediaType)==="image")){let A$="";for(let H$ of c)if(H$.type==="text")A$+=H$.text;else w.push({type:"unsupported",feature:`user message part type: ${H$.type}`});E.push({role:"user",content:A$,...(n==null?void 0:n.name)!=null&&{name:n.name}});break}let _$=[];for(let A$ of c)if(A$.type==="text")_$.push({type:"text",text:A$.text});else if(A$.type==="file"&&C7(A$.mediaType)==="image"){let H$=await dJ({provider:W,providerOptions:A$.providerOptions,schema:gg0});if(A$.data.type==="reference")_$.push({type:"file",file_id:JW({reference:A$.data.reference,provider:"deepseek"})});else if(A$.data.type==="url"||A$.data.type==="data"){let M$=hQ({part:A$});if(!dg0.has(M$))throw new E9({functionality:`DeepSeek image media type ${M$}`,message:"DeepSeek supports JPEG, PNG, GIF, and WebP image inputs."});if(A$.data.type==="url"){let b$=A$.data.url.toString();if(b$.length>8192)throw new $M({prompt:J,message:"DeepSeek image URLs must not exceed 8192 characters."});if((H$==null?void 0:H$.fileData)===!0)throw new $M({prompt:J,message:"DeepSeek `fileData` image parts require inline data, not a URL."});_$.push({type:"image_url",image_url:{url:b$,...(H$==null?void 0:H$.imageDetail)!=null&&{detail:H$.imageDetail}}})}else{let b$=`data:${M$==="image/jpg"?"image/jpeg":M$};base64,${UY(A$.data.data)}`;if((H$==null?void 0:H$.fileData)===!0){if(H$.imageDetail!=null)throw new $M({prompt:J,message:"DeepSeek `imageDetail` cannot be combined with `fileData`."});_$.push({type:"file",file_data:b$,...A$.filename!=null&&{filename:A$.filename}})}else _$.push({type:"image_url",image_url:{url:b$,...(H$==null?void 0:H$.imageDetail)!=null&&{detail:H$.imageDetail}}})}}else w.push({type:"unsupported",feature:`user message part type: ${A$.type}`})}else w.push({type:"unsupported",feature:`user message part type: ${A$.type}`});E.push({role:"user",content:_$,...(n==null?void 0:n.name)!=null&&{name:n.name}});break}case"assistant":{if((n==null?void 0:n.prefix)===!0){if(v!==J.length-1)throw new $M({prompt:J,message:"DeepSeek assistant prefix completion requires the prefixed assistant message to be the final message."});if(!z)throw new E9({functionality:"DeepSeek assistant prefix completion",message:"DeepSeek assistant prefix completion requires a beta base URL ending in `/beta`."})}let B$="",_$,A$=[];for(let H$ of c)switch(H$.type){case"text":{B$+=H$.text;break}case"reasoning":{if(v<=S&&!P)break;if(_$==null)_$=H$.text;else _$+=H$.text;break}case"tool-call":{A$.push({id:H$.toolCallId,type:"function",function:{name:H$.toolName,arguments:JSON.stringify(H$.input)}});break}}E.push({role:"assistant",content:B$,...(n==null?void 0:n.name)!=null&&{name:n.name},...(n==null?void 0:n.prefix)===!0&&{prefix:!0},reasoning_content:_$!=null?_$:P?"":void 0,tool_calls:A$.length>0?A$:void 0});break}case"tool":{if((n==null?void 0:n.name)!=null)w.push({type:"unsupported",feature:"message name on tool messages"});for(let B$ of c){if(B$.type==="tool-approval-response")continue;let _$=B$.output,A$;switch(_$.type){case"text":case"error-text":A$=_$.value;break;case"execution-denied":A$=(F=_$.reason)!=null?F:"Tool call execution denied.";break;case"content":case"json":case"error-json":A$=JSON.stringify(_$.value);break}E.push({role:"tool",tool_call_id:B$.toolCallId,content:A$})}break}default:{w.push({type:"unsupported",feature:`message role: ${x}`});break}}}return{messages:E,warnings:w}}function nP6(J){var Y,Z,W,z,H;if(J==null)return mZ();let F=(Y=J.prompt_tokens)!=null?Y:0,P=(Z=J.completion_tokens)!=null?Z:0,E=(W=J.prompt_cache_hit_tokens)!=null?W:0,w=(H=(z=J.completion_tokens_details)==null?void 0:z.reasoning_tokens)!=null?H:0;return{inputTokens:{total:F,noCache:F-E,cacheRead:E,cacheWrite:void 0},outputTokens:{total:P,text:Math.max(0,P-w),reasoning:w},raw:J}}function rg0({tools:J,toolChoice:Y,supportsStrictToolCalls:Z}){J=(J==null?void 0:J.length)?J:void 0;let W=[];if(J==null)return{tools:void 0,toolChoice:void 0,toolWarnings:W};let z=J.filter((E)=>E.type==="function"),H=z.some((E)=>E.strict===!0);if(H&&Z===!1)throw new E9({functionality:"DeepSeek strict tool calls",message:"DeepSeek strict tool calls require a beta base URL ending in `/beta`."});if(H&&Z===!0&&z.some((E)=>E.strict!==!0))throw new E9({functionality:"mixed DeepSeek strict and non-strict tool calls",message:"DeepSeek strict mode requires every function tool in the request to set `strict: true`."});let F=[];for(let E of J)if(E.type==="provider")W.push({type:"unsupported",feature:`provider-defined tool ${E.id}`});else F.push({type:"function",function:{name:E.name,description:E.description,parameters:E.inputSchema,...E.strict!=null?{strict:E.strict}:{}}});if(Y==null)return{tools:F,toolChoice:void 0,toolWarnings:W};let P=Y==null?void 0:Y.type;switch(P){case"auto":case"none":case"required":return{tools:F,toolChoice:P,toolWarnings:W};case"tool":return{tools:F,toolChoice:{type:"function",function:{name:Y.toolName}},toolWarnings:W};default:return{tools:F,toolChoice:void 0,toolWarnings:[...W,{type:"unsupported",feature:`tool choice type: ${P}`}]}}}function tP6(J){switch(J){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"tool_calls":return"tool-calls";case"insufficient_system_resource":return"error";default:return"other"}}function sg0(J,Y){var Z,W;let z=ag0(J);return hF({message:J.message,type:(Z=J.type)!=null?Z:void 0,code:(W=J.code)!=null?W:void 0,...z,data:Y})}function ag0(J){if(J.code==="insufficient_quota"||J.type==="insufficient_quota")return{statusCode:429,isRetryable:!1};let Y=ng0(J.code);if(Y!=null)return{statusCode:Y,isRetryable:og0(Y)};for(let Z of[J.code,J.type])switch(Z){case"rate_limit_exceeded":case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"server_error":case"api_error":case"internal_server_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":case"service_unavailable":return{statusCode:503,isRetryable:!0};case"timeout":case"timeout_error":return{statusCode:504,isRetryable:!0};case"authentication_error":case"invalid_api_key":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":case"model_not_found":return{statusCode:404,isRetryable:!1};case"bad_request":case"context_length_exceeded":case"invalid_request_error":return{statusCode:400,isRetryable:!1}}return{}}function ng0(J){let Y=typeof J==="string"&&/^\d{3}$/.test(J)?Number(J):J;return typeof Y==="number"&&Number.isInteger(Y)&&Y>=400&&Y<=599?Y:void 0}function og0(J){return J===408||J===409||J===429||J>=500}function tg0({reasoningEffort:J,warnings:Y}){let Z=J==="medium"?"high":J==="xhigh"?"max":J;if(Z!==J)Y.push({type:"compatibility",feature:"reasoningEffort",details:`reasoningEffort "${J}" is not a canonical DeepSeek value. mapped to "${Z}".`});return Z}function Zm0({fileBytes:J,mediaType:Y,filename:Z}){if(J.length>eP6)throw new U7({argument:"data",message:`DeepSeek file uploads must not exceed 64 MiB (${eP6.toLocaleString("en-US")} bytes). Received ${J.length.toLocaleString("en-US")} bytes.`});if(Z!=null){let H=Array.from(Z).length;if(H>$M6)throw new U7({argument:"filename",message:`DeepSeek filenames must not exceed ${$M6} characters. Received ${H} characters.`})}let W=Gm0(Y),z=uf$({data:J});if(z!=null&&!JM6.has(z))throw new U7({argument:"data",message:`DeepSeek file uploads support JPEG, PNG, GIF, and WebP images. Detected unsupported file content type "${z}".`});if(JM6.has(W))return;if(!Ym0.has(W))throw new U7({argument:"mediaType",message:`DeepSeek file uploads support JPEG, PNG, GIF, and WebP images. Received unsupported media type "${Y}".`});if(z!=null||Wm0(Z))return;throw new U7({argument:"mediaType",message:`DeepSeek file uploads support JPEG, PNG, GIF, and WebP images. Provide a supported media type or a filename ending in .jpg, .jpeg, .png, .gif, or .webp. Received "${Y}".`})}function Gm0(J){return J.split(";",1)[0].trim().toLowerCase()}function Wm0(J){if(J==null)return!1;let Y=J.lastIndexOf(".");return Y!==-1&&Qm0.has(J.slice(Y+1).toLowerCase())}function KM6(J={}){var Y,Z;let W=(Z=XW((Y=J.baseURL)!=null?Y:"https://api.deepseek.com"))!=null?Z:"https://api.deepseek.com",z=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...J.headers},`ai-sdk/deepseek/${QM6}`),H=(E)=>{return new eg0(E,{provider:"deepseek.chat",url:({path:w})=>`${W}${w}`,headers:z,fetch:J.fetch,supportsAssistantPrefixCompletion:W.endsWith("/beta"),supportsStrictToolCalls:W.endsWith("/beta")})},F=()=>new Km0({provider:"deepseek.files",baseURL:W,headers:z,fetch:J.fetch}),P=(E)=>H(E);return P.specificationVersion="v4",P.languageModel=H,P.chat=H,P.files=F,P.embeddingModel=(E)=>{throw new CW({modelId:E,modelType:"embeddingModel"})},P.textEmbeddingModel=P.embeddingModel,P.imageModel=(E)=>{throw new CW({modelId:E,modelType:"imageModel"})},P}var gg0,mg0,ug0,cg0,dg0,XM6,xv$,oP6,YM6,pg0,ig0,eg0,$m0,Jm0,Xm0,eP6=67108864,$M6=512,JM6,Ym0,Qm0,Km0=class{constructor(J){this.config=J,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:J,mediaType:Y,filename:Z,providerOptions:W}){var z,H;let F=await dJ({provider:"deepseek",providerOptions:W,schema:Jm0}),P=eV(J);Zm0({fileBytes:P,mediaType:Y,filename:Z});let E=new Blob([P],{type:Y}),w=new FormData;if(Z!=null)w.append("file",E,Z);else w.append("file",E);if(w.append("purpose","user_data"),(F==null?void 0:F.expiresAfter)!=null)w.append("expires_after[anchor]","created_at"),w.append("expires_after[seconds]",String(F.expiresAfter));let{value:S}=await nK({url:`${this.config.baseURL}/files`,headers:TJ(this.config.headers()),formData:w,failedResponseHandler:Xm0,successfulResponseHandler:Z9($m0),fetch:this.config.fetch});return{warnings:[],providerReference:{deepseek:S.id},...((z=S.filename)!=null?z:Z)?{filename:(H=S.filename)!=null?H:Z}:{},...Y!=null?{mediaType:Y}:{},providerMetadata:{deepseek:{...S.object!=null?{object:S.object}:{},...S.filename!=null?{filename:S.filename}:{},...S.purpose!=null?{purpose:S.purpose}:{},...S.bytes!=null?{bytes:S.bytes}:{},...S.created_at!=null?{createdAt:S.created_at}:{},...S.expires_at!=null?{expiresAt:S.expires_at}:{}}}}}},QM6="3.0.35",zm0;var GM6=n9(()=>{g4();C1();C1();g4();C1();c8();c8();C1();C1();c8();g4();C1();g4();C1();C1();c8();C1();c8();gg0=q.object({imageDetail:q.enum(["low","high","original","auto"]).optional(),fileData:q.literal(!0).optional()}),mg0=q.object({logprobs:q.boolean().optional(),topLogprobs:q.number().int().min(0).max(20).optional(),userId:q.string().regex(/^[a-zA-Z0-9_-]+$/,"userId must match /^[a-zA-Z0-9_-]+$/").max(512,"userId must be at most 512 characters long").optional(),thinking:q.object({type:q.enum(["adaptive","enabled","disabled"]).optional()}).optional(),reasoningEffort:q.enum(["low","medium","high","xhigh","max"]).optional(),strictJsonSchema:q.boolean().optional()}),ug0=q.object({name:q.string().optional()}),cg0=ug0.extend({prefix:q.literal(!0).optional()}),dg0=new Set(["image/gif","image/jpeg","image/jpg","image/png","image/webp"]);XM6=q.looseObject({prompt_tokens:q.number().nullish(),completion_tokens:q.number().nullish(),prompt_cache_hit_tokens:q.number().nullish(),prompt_cache_miss_tokens:q.number().nullish(),total_tokens:q.number().nullish(),prompt_tokens_details:q.looseObject({cached_tokens:q.number().nullish()}).nullish(),completion_tokens_details:q.looseObject({reasoning_tokens:q.number().nullish()}).nullish()}).nullish(),xv$=q.object({error:q.object({message:q.string(),type:q.string().nullish(),param:q.any().nullish(),code:q.union([q.string(),q.number()]).nullish()})}),oP6=q.object({token:q.string(),logprob:q.number(),bytes:q.array(q.number()).nullable(),top_logprobs:q.array(q.object({token:q.string(),logprob:q.number(),bytes:q.array(q.number()).nullable()}))}),YM6=q.object({content:q.array(oP6).nullish(),reasoning_content:q.array(oP6).nullish()}).nullish(),pg0=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),object:q.literal("chat.completion").nullish(),system_fingerprint:q.string().nullish(),choices:q.array(q.object({index:q.number().nullish(),message:q.object({role:q.literal("assistant").nullish(),content:q.string().nullish(),reasoning_content:q.string().nullish(),tool_calls:q.array(q.object({id:q.string().nullish(),type:q.literal("function").nullish(),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),logprobs:YM6,finish_reason:q.string().nullish()})),usage:XM6}),ig0=p0(()=>d0(q.union([q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),object:q.literal("chat.completion.chunk").nullish(),system_fingerprint:q.string().nullish(),choices:q.array(q.object({index:q.number().nullish(),delta:q.object({role:q.enum(["assistant"]).nullish(),content:q.string().nullish(),reasoning_content:q.string().nullish(),tool_calls:q.array(q.object({index:q.number(),id:q.string().nullish(),type:q.literal("function").nullish(),function:q.object({name:q.string().nullish(),arguments:q.string().nullish()})})).nullish()}).nullish(),logprobs:YM6,finish_reason:q.string().nullish()})),usage:XM6}),xv$])));eg0=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Y,this.config=Z,this.failedResponseHandler=b2({errorSchema:xv$,errorToMessage:(W)=>W.error.message})}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,reasoning:E,providerOptions:w,stopSequences:S,responseFormat:v,seed:x,toolChoice:c,tools:r}){var n,B$,_$,A$;let H$=(n=await dJ({provider:this.providerOptionsName,providerOptions:w,schema:mg0}))!=null?n:{},M$=this.config.supportsStructuredOutputs===!0,b$=this.config.supportsPenaltySampling===!0,{messages:p$,warnings:o$}=await lg0({prompt:Y,responseFormat:v,modelId:this.modelId,providerOptionsName:this.providerOptionsName,supportsAssistantPrefixCompletion:this.config.supportsAssistantPrefixCompletion,supportsStructuredOutputs:M$}),T6=[...o$];if(H!=null)T6.push({type:"unsupported",feature:"topK"});if(x!=null)T6.push({type:"unsupported",feature:"seed"});if(!b$&&F!=null)T6.push({type:"deprecated",setting:"frequencyPenalty",message:"frequencyPenalty is deprecated by DeepSeek and has been omitted. Remove frequencyPenalty from the request."});if(!b$&&P!=null)T6.push({type:"deprecated",setting:"presencePenalty",message:"presencePenalty is deprecated by DeepSeek and has been omitted. Remove presencePenalty from the request."});let{tools:j6,toolChoice:Y6,toolWarnings:y$}=rg0({tools:r,toolChoice:c,supportsStrictToolCalls:this.config.supportsStrictToolCalls}),_6=(B$=H$.thinking)==null?void 0:B$.type;if(_6==="adaptive")T6.push({type:"compatibility",feature:"thinking.type",details:'thinking.type "adaptive" is not a canonical DeepSeek value. mapped to "enabled".'});let k6=this.config.supportsThinking===!1?void 0:_6!=null?{type:_6==="adaptive"?"enabled":_6}:wZ(E)?{type:E==="none"?"disabled":"enabled"}:void 0,x$=this.config.supportsThinking!==!1&&(k6==null?void 0:k6.type)!=="disabled"&&(k6!=null||this.modelId==="deepseek-reasoner"||this.modelId.includes("deepseek-v4"));if(x$&&W!=null)T6.push({type:"unsupported",feature:"temperature",details:"temperature has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use temperature."});if(x$&&z!=null)T6.push({type:"unsupported",feature:"topP",details:"topP has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use topP."});let r0=H$.reasoningEffort!=null?tg0({reasoningEffort:H$.reasoningEffort,warnings:T6}):wZ(E)&&E!=="none"?$q({reasoning:E,effortMap:{minimal:"low",low:"low",medium:"high",high:"high",xhigh:"max"},warnings:T6}):void 0;return{args:{model:this.modelId,...(H$.logprobs===!0||H$.topLogprobs!=null)&&{logprobs:!0},...H$.topLogprobs!=null&&{top_logprobs:H$.topLogprobs},max_tokens:Z,temperature:x$?void 0:W,top_p:x$?void 0:z,frequency_penalty:b$?F:void 0,presence_penalty:b$?P:void 0,response_format:(v==null?void 0:v.type)==="json"?M$&&v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:(_$=H$.strictJsonSchema)!=null?_$:!0,name:(A$=v.name)!=null?A$:"response",description:v.description}}:{type:"json_object"}:void 0,stop:S,messages:p$,tools:j6,tool_choice:Y6,thinking:k6,...H$.userId!=null&&{user_id:H$.userId},...(k6==null?void 0:k6.type)!=="disabled"&&r0!=null&&{reasoning_effort:r0}},warnings:[...T6,...y$]}}async doGenerate(Y){var Z,W,z,H,F;let{args:P,warnings:E}=await this.getArgs({...Y}),{responseHeaders:w,value:S,rawValue:v}=await W4({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:P,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Z9(pg0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),x=S.choices[0],c=[],r=x.message.reasoning_content;if(r!=null&&r.length>0)c.push({type:"reasoning",text:r});if(x.message.tool_calls!=null)for(let B$ of x.message.tool_calls)c.push({type:"tool-call",toolCallId:B$.id||wY(),toolName:B$.function.name,input:B$.function.arguments});let n=x.message.content;if(n!=null&&n.length>0)c.push({type:"text",text:n});return{content:c,finishReason:{unified:tP6(x.finish_reason),raw:(z=x.finish_reason)!=null?z:void 0},usage:nP6(S.usage),providerMetadata:{[this.providerOptionsName]:{promptCacheHitTokens:(H=S.usage)==null?void 0:H.prompt_cache_hit_tokens,promptCacheMissTokens:(F=S.usage)==null?void 0:F.prompt_cache_miss_tokens,...S.object!=null&&{responseObject:S.object},...x.index!=null&&{choiceIndex:x.index},...x.message.role!=null&&{messageRole:x.message.role},...x.message.tool_calls!=null&&{toolCallTypes:x.message.tool_calls.map((B$)=>B$.type).filter((B$)=>B$!=null)},...x.logprobs!=null&&{logprobs:x.logprobs},...S.system_fingerprint!=null&&{systemFingerprint:S.system_fingerprint}}},request:{body:P},response:{...RZ(S),headers:w,body:v},warnings:E}}async doStream(Y){var Z,W;let{args:z,warnings:H}=await this.getArgs({...Y}),F={...z,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:P,value:E}=await W4({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:F,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:k2(ig0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),w,S={unified:"other",raw:void 0},v=void 0,x=void 0,c=!0,r=this.providerOptionsName,n=!1,B$=!1,_$,A$,H$,M$=new Map,b$=[],p$=[];return{stream:E.pipeThrough(new TransformStream({start(o$){w=new WM(o$,{generateId:wY}),o$.enqueue({type:"stream-start",warnings:H})},transform(o$,T6){var j6,Y6;if(Y.includeRawChunks)T6.enqueue({type:"raw",rawValue:o$.rawValue});if(!o$.success){S={unified:"error",raw:void 0},T6.enqueue({type:"error",error:o$.error});return}let y$=o$.value;if("error"in y$){S={unified:"error",raw:void 0},T6.enqueue({type:"error",error:sg0(y$.error,y$)});return}if(c)c=!1,T6.enqueue({type:"response-metadata",...RZ(y$)});if(y$.usage!=null)v=y$.usage;if(y$.object!=null)_$=y$.object;if(y$.system_fingerprint!=null)x=y$.system_fingerprint;let _6=y$.choices[0];if((_6==null?void 0:_6.index)!=null)A$=_6.index;if((_6==null?void 0:_6.finish_reason)!=null)S={unified:tP6(_6.finish_reason),raw:_6.finish_reason};if(((j6=_6==null?void 0:_6.logprobs)==null?void 0:j6.content)!=null)b$.push(..._6.logprobs.content);if(((Y6=_6==null?void 0:_6.logprobs)==null?void 0:Y6.reasoning_content)!=null)p$.push(..._6.logprobs.reasoning_content);if((_6==null?void 0:_6.delta)==null)return;let k6=_6.delta;if(k6.role!=null)H$=k6.role;let x$=k6.reasoning_content;if(x$){if(!n)T6.enqueue({type:"reasoning-start",id:"reasoning-0"}),n=!0;T6.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:x$})}if(k6.content){if(!B$)T6.enqueue({type:"text-start",id:"txt-0"}),B$=!0;if(n)T6.enqueue({type:"reasoning-end",id:"reasoning-0"}),n=!1;T6.enqueue({type:"text-delta",id:"txt-0",delta:k6.content})}if(k6.tool_calls!=null){if(n)T6.enqueue({type:"reasoning-end",id:"reasoning-0"}),n=!1;for(let r0 of k6.tool_calls){if(r0.type!=null)M$.set(r0.index,r0.type);w.processDelta(r0)}}},flush(o$){var T6,j6;if(n)o$.enqueue({type:"reasoning-end",id:"reasoning-0"});if(B$)o$.enqueue({type:"text-end",id:"txt-0"});w.flush(),o$.enqueue({type:"finish",finishReason:S,usage:nP6(v),providerMetadata:{[r]:{promptCacheHitTokens:(T6=v==null?void 0:v.prompt_cache_hit_tokens)!=null?T6:void 0,promptCacheMissTokens:(j6=v==null?void 0:v.prompt_cache_miss_tokens)!=null?j6:void 0,..._$!=null&&{responseObject:_$},...A$!=null&&{choiceIndex:A$},...H$!=null&&{messageRole:H$},...M$.size>0&&{toolCallTypes:[...M$.entries()].sort(([Y6],[y$])=>Y6-y$).map(([,Y6])=>Y6)},...(b$.length>0||p$.length>0)&&{logprobs:{...b$.length>0&&{content:b$},...p$.length>0&&{reasoning_content:p$}}},...x!=null&&{systemFingerprint:x}}}})}})),request:{body:F},response:{headers:P}}}},$m0=p0(()=>d0(q.object({id:q.string(),object:q.literal("file").nullish(),bytes:q.number().int().nonnegative().nullish(),created_at:q.number().int().nonnegative().nullish(),filename:q.string().nullish(),purpose:q.literal("user_data").nullish(),expires_at:q.number().int().nonnegative().nullish()}))),Jm0=p0(()=>d0(q.object({expiresAfter:q.number().int().min(3600).max(2592000).optional()}))),Xm0=b2({errorSchema:xv$,errorToMessage:(J)=>J.error.message}),JM6=new Set(["image/gif","image/jpeg","image/jpg","image/png","image/webp"]),Ym0=new Set(["","application/binary","application/octet-stream","binary/octet-stream","image","image/*"]),Qm0=new Set(["gif","jpeg","jpg","png","webp"]);zm0=KM6()});var vM6={};EW(vM6,{xaiTools:()=>wM6,xai:()=>eu0,xSearch:()=>NM6,webSearch:()=>MM6,viewXVideo:()=>RM6,viewImage:()=>TM6,mcpServer:()=>PM6,imageGeneration:()=>OM6,createXai:()=>fM6,codeExecution:()=>_M6,VERSION:()=>SM6,Experimental_XaiRealtimeModel:()=>EM6});async function Um0(J){var Y;let Z=[],W=[];for(let{role:z,content:H}of J)switch(z){case"system":{Z.push({role:"system",content:H});break}case"user":{if(H.length===1&&H[0].type==="text"){Z.push({role:"user",content:H[0].text});break}let F=[];for(let P of H)switch(P.type){case"text":{F.push({type:"text",text:P.text});break}case"file":{switch(P.data.type){case"reference":{F.push({type:"file",file:{file_id:JW({reference:P.data.reference,provider:"xai"})}});break}case"text":throw new E9({functionality:"text file parts"});case"url":case"data":{if(C7(P.mediaType)==="image"){let E=await dJ({provider:"xai",providerOptions:P.providerOptions,schema:qM6});F.push({type:"image_url",image_url:{url:P.data.type==="url"?P.data.url.toString():`data:${hQ({part:P})};base64,${UY(P.data.data)}`,...(E==null?void 0:E.imageDetail)!=null&&{detail:E.imageDetail}}})}else throw new E9({functionality:`file part media type ${P.mediaType}`});break}}break}}Z.push({role:"user",content:F});break}case"assistant":{let F="",P=[];for(let E of H)switch(E.type){case"text":{F+=E.text;break}case"tool-call":{P.push({id:E.toolCallId,type:"function",function:{name:E.toolName,arguments:JSON.stringify(E.input)}});break}}Z.push({role:"assistant",content:F,tool_calls:P.length>0?P:void 0});break}case"tool":{for(let F of H){if(F.type==="tool-approval-response")continue;let P=F.output,E;switch(P.type){case"text":case"error-text":E=P.value;break;case"execution-denied":E=(Y=P.reason)!=null?Y:"Tool call execution denied.";break;case"content":case"json":case"error-json":E=JSON.stringify(P.value);break}Z.push({role:"tool",tool_call_id:F.toolCallId,content:E})}break}default:throw Error(`Unsupported role: ${z}`)}return{messages:Z,warnings:W}}function hv$(J){var Y,Z,W,z;let H=(Z=(Y=J.prompt_tokens_details)==null?void 0:Y.cached_tokens)!=null?Z:0,F=(z=(W=J.completion_tokens_details)==null?void 0:W.reasoning_tokens)!=null?z:0,P=H<=J.prompt_tokens;return{inputTokens:{total:P?J.prompt_tokens:J.prompt_tokens+H,noCache:P?J.prompt_tokens-H:J.prompt_tokens,cacheRead:H,cacheWrite:void 0},outputTokens:{total:J.completion_tokens+F,text:J.completion_tokens,reasoning:F},raw:J}}function ao({id:J,model:Y,created:Z,created_at:W}){return RZ({id:J,model:Y,created:Z!=null?Z:W})}function gv$(J){switch(J){case"stop":return"stop";case"length":return"length";case"tool_calls":case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}}function DM6(J){return!jm0.test(J)}function FZ$(J){if(Array.isArray(J))return J.map(FZ$);if(J==null||typeof J!=="object")return J;let Y={};for(let[Z,W]of Object.entries(J)){if(Z==="additionalProperties"&&W===!1)continue;Y[Z]=FZ$(W)}return Y}function Mm0({tools:J,toolChoice:Y}){J=(J==null?void 0:J.length)?J:void 0;let Z=[];if(J==null)return{tools:void 0,toolChoice:void 0,toolWarnings:Z};let W=[];for(let H of J)if(H.type==="provider")Z.push({type:"unsupported",feature:`provider-defined tool ${H.name}`});else W.push({type:"function",function:{name:H.name,description:H.description,parameters:FZ$(H.inputSchema),...H.strict!=null?{strict:H.strict}:{}}});if(Y==null)return{tools:W,toolChoice:void 0,toolWarnings:Z};let z=Y.type;switch(z){case"auto":case"none":return{tools:W,toolChoice:z,toolWarnings:Z};case"required":return{tools:W,toolChoice:"required",toolWarnings:Z};case"tool":return{tools:W,toolChoice:{type:"function",function:{name:Y.toolName}},toolWarnings:Z};default:throw new E9({functionality:`tool choice type: ${z}`})}}async function wm0({prompt:J}){var Y,Z,W,z,H,F,P,E,w;let S=[],v=[];for(let x of J)switch(x.role){case"system":{S.push({role:"system",content:x.content});break}case"user":{let c=[];for(let r of x.content)switch(r.type){case"text":{c.push({type:"input_text",text:r.text});break}case"file":{switch(r.data.type){case"reference":{c.push({type:"input_file",file_id:JW({reference:r.data.reference,provider:"xai"})});break}case"text":throw new E9({functionality:"text file parts"});case"url":case"data":{if(C7(r.mediaType)==="image"){let n=r.data.type==="url"?r.data.url.toString():`data:${hQ({part:r})};base64,${UY(r.data.data)}`,B$=await dJ({provider:"xai",providerOptions:r.providerOptions,schema:qM6});c.push({type:"input_image",image_url:n,...(B$==null?void 0:B$.imageDetail)!=null&&{detail:B$.imageDetail}})}else if(r.data.type==="url")c.push({type:"input_file",file_url:r.data.url.toString()});else throw new E9({functionality:`file part media type ${r.mediaType} as inline data (xAI Responses requires a URL or a Files API reference for non-image files)`});break}}break}default:{let n=r;v.push({type:"other",message:"xAI Responses API does not support this content type in user messages"})}}S.push({role:"user",content:c});break}case"assistant":{for(let c of x.content)switch(c.type){case"text":{let r=typeof((Z=(Y=c.providerOptions)==null?void 0:Y.xai)==null?void 0:Z.itemId)==="string"?c.providerOptions.xai.itemId:void 0;S.push({role:"assistant",content:c.text,id:r});break}case"tool-call":{if(c.providerExecuted)break;let r=typeof((z=(W=c.providerOptions)==null?void 0:W.xai)==null?void 0:z.itemId)==="string"?c.providerOptions.xai.itemId:void 0;S.push({type:"function_call",id:r!=null?r:c.toolCallId,call_id:c.toolCallId,name:c.toolName,arguments:JSON.stringify(c.input),status:"completed"});break}case"tool-result":break;case"reasoning":{let r=typeof((F=(H=c.providerOptions)==null?void 0:H.xai)==null?void 0:F.itemId)==="string"?c.providerOptions.xai.itemId:void 0,n=typeof((E=(P=c.providerOptions)==null?void 0:P.xai)==null?void 0:E.reasoningEncryptedContent)==="string"?c.providerOptions.xai.reasoningEncryptedContent:void 0;if(r!=null||n!=null){let B$=[];if(c.text.length>0)B$.push({type:"summary_text",text:c.text});S.push({type:"reasoning",id:r!=null?r:"",summary:B$,status:"completed",...n!=null&&{encrypted_content:n}})}else v.push({type:"other",message:"Reasoning parts without itemId or encrypted content cannot be sent back to xAI. Skipping."});break}case"reasoning-file":case"custom":case"file":{v.push({type:"other",message:`xAI Responses API does not support ${c.type} in assistant messages`});break}default:{let r=c;v.push({type:"other",message:"xAI Responses API does not support this content type in assistant messages"})}}break}case"tool":{for(let c of x.content){if(c.type==="tool-approval-response")continue;let r=c.output,n;switch(r.type){case"text":case"error-text":n=r.value;break;case"execution-denied":n=(w=r.reason)!=null?w:"tool execution denied";break;case"json":case"error-json":n=JSON.stringify(r.value);break;case"content":n=[];for(let B$ of r.value)switch(B$.type){case"text":{n.push({type:"input_text",text:B$.text});break}case"file":{if(C7(B$.mediaType)==="image"&&(B$.data.type==="data"||B$.data.type==="url"))n.push({type:"input_image",image_url:B$.data.type==="url"?B$.data.url.toString():`data:${hQ({part:B$})};base64,${UY(B$.data.data)}`});break}case"custom":break;default:{let _$=B$}}break;default:{let B$=r;n=""}}S.push({type:"function_call_output",call_id:c.toolCallId,output:n})}break}default:{let c=x;v.push({type:"other",message:"unsupported message role"})}}return{input:S,inputWarnings:v}}function yv$(J){var Y,Z,W,z;let H=(Z=(Y=J.input_tokens_details)==null?void 0:Y.cached_tokens)!=null?Z:0,F=(z=(W=J.output_tokens_details)==null?void 0:W.reasoning_tokens)!=null?z:0,P=H<=J.input_tokens;return{inputTokens:{total:P?J.input_tokens:J.input_tokens+H,noCache:P?J.input_tokens-H:J.input_tokens,cacheRead:H,cacheWrite:void 0},outputTokens:{total:J.output_tokens,text:J.output_tokens-F,reasoning:F},raw:J}}function DZ$(J){switch(J){case"stop":case"completed":return"stop";case"length":case"max_output_tokens":return"length";case"tool_calls":case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}}async function tm0({tools:J,toolChoice:Y}){let Z=(J==null?void 0:J.length)?J:void 0,W=[];if(Z==null)return{tools:void 0,toolChoice:void 0,toolWarnings:W};let z=[],H=new Map;for(let P of Z)if(H.set(P.name,P),P.type==="provider")switch(P.id){case"xai.web_search":{let E=await ZQ({value:P.args,schema:im0});z.push({type:"web_search",allowed_domains:E.allowedDomains,excluded_domains:E.excludedDomains,enable_image_search:E.enableImageSearch,enable_image_understanding:E.enableImageUnderstanding});break}case"xai.x_search":{let E=await ZQ({value:P.args,schema:am0});z.push({type:"x_search",allowed_x_handles:E.allowedXHandles,excluded_x_handles:E.excludedXHandles,from_date:E.fromDate,to_date:E.toDate,enable_image_understanding:E.enableImageUnderstanding,enable_video_understanding:E.enableVideoUnderstanding});break}case"xai.code_execution":{z.push({type:"code_interpreter"});break}case"xai.view_image":{z.push({type:"view_image"});break}case"xai.view_x_video":{z.push({type:"view_x_video"});break}case"xai.image_generation":{let E=await ZQ({value:P.args,schema:gm0});z.push({type:"image_generation",action:E.action});break}case"xai.file_search":{let E=await ZQ({value:P.args,schema:ym0});z.push({type:"file_search",vector_store_ids:E.vectorStoreIds,max_num_results:E.maxNumResults});break}case"xai.mcp":{let E=await ZQ({value:P.args,schema:dm0});z.push({type:"mcp",server_url:E.serverUrl,server_label:E.serverLabel,server_description:E.serverDescription,allowed_tools:E.allowedTools,headers:E.headers,authorization:E.authorization});break}default:{W.push({type:"unsupported",feature:`provider-defined tool ${P.name}`});break}}else z.push({type:"function",name:P.name,description:P.description,parameters:FZ$(P.inputSchema),...P.strict!=null?{strict:P.strict}:{}});if(Y==null)return{tools:z,toolChoice:void 0,toolWarnings:W};let F=Y.type;switch(F){case"auto":case"none":return{tools:z,toolChoice:F,toolWarnings:W};case"required":return{tools:z,toolChoice:"required",toolWarnings:W};case"tool":{let P=H.get(Y.toolName);if(P==null)return{tools:z,toolChoice:void 0,toolWarnings:W};if(P.type==="provider")return W.push({type:"unsupported",feature:`toolChoice for server-side tool "${P.name}"`}),{tools:z,toolChoice:void 0,toolWarnings:W};return{tools:z,toolChoice:{type:"function",name:P.name},toolWarnings:W}}default:throw new E9({functionality:`tool choice type: ${F}`})}}function WM6({message:J,code:Y,eventType:Z,data:W}){let z=$u0(Y);return hF({message:J,type:Z,code:Y!=null?Y:void 0,...z!=null?{statusCode:z,isRetryable:Ju0(z)}:em0(Y),data:W})}function em0(J){switch(J){case"rate_limit_exceeded":case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"insufficient_quota":return{statusCode:429,isRetryable:!1};case"api_error":case"internal_server_error":case"server_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":case"service_unavailable":return{statusCode:503,isRetryable:!0};case"timeout":case"timeout_error":return{statusCode:504,isRetryable:!0};case"authentication_error":case"invalid_api_key":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":case"model_not_found":return{statusCode:404,isRetryable:!1};case"bad_request":case"context_length_exceeded":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}function $u0(J){let Y=typeof J==="string"&&/^\d{3}$/.test(J)?Number(J):J;return typeof Y==="number"&&Number.isInteger(Y)&&Y>=400&&Y<=599?Y:void 0}function Ju0(J){return J===408||J===409||J===429||J>=500}function UM6(J){var Y;let Z=Cm0.safeParse(J);if(!Z.success)return{};let W=Z.data,z=(Y=W.sources)==null?void 0:Y.flatMap((F)=>{let P=Sm0.safeParse(F);return P.success?[P.data]:[]}),H=z!=null&&z.length>0?{sources:z}:{};switch(W.type){case"search":return{action:{type:"search",...W.query!=null&&{query:W.query},...W.queries!=null&&{queries:W.queries}},...H};case"open_page":return{action:{type:"openPage",url:W.url},...H};case"find_in_page":return{action:{type:"findInPage",url:W.url,pattern:W.pattern},...H}}}function fv$(J){var Y,Z,W,z,H,F;let P=pR({total:(Y=J.state)==null?void 0:Y.num_requests,pending:(Z=J.state)==null?void 0:Z.num_pending,completed:(W=J.state)==null?void 0:W.num_success,failed:((z=J.state)==null?void 0:z.num_error)!=null&&((H=J.state)==null?void 0:H.num_cancelled)!=null?J.state.num_error+J.state.num_cancelled:void 0}),E=J.cancel_time!=null||J.cancel_by_xai_message!=null,w=Uu0(J.expire_time);return{status:E||w?"failed":P!=null&&P.total>0&&P.pending===0?"completed":"pending",...P!=null?{requestCounts:P}:{},...E?{error:{message:(F=J.cancel_by_xai_message)!=null?F:`xAI batch "${J.batch_id}" was cancelled.`,code:"batch_cancelled"}}:w?{error:{message:`xAI batch "${J.batch_id}" expired.`,code:"batch_expired"}}:{},...J.create_time!=null?{createdAt:J.create_time}:{},...J.expire_time!=null?{expiresAt:J.expire_time}:{}}}function Uu0(J){if(J==null)return!1;let Y=Date.parse(J);return!Number.isNaN(Y)&&Y<=Date.now()}function ju0(J){var Y;let Z=(Y=J.batch_result)==null?void 0:Y.error;return{message:J.error_message||(Z==null?void 0:Z.message)||"xAI batch request failed.",...(Z==null?void 0:Z.code)!=null&&Z.code!==0&&Z.code!=="0"?{code:String(Z.code)}:{}}}function Bu0(J){let Y=String(J).toLowerCase();return J===1||Y==="1"||Y==="cancelled"||Y==="batch_cancelled"}function BM6(J){return{id:J,status:"failed",error:{message:"xAI returned an invalid Responses batch result.",code:"invalid_response"}}}function Hu0(J){var Y,Z,W,z,H,F;if(J.error!=null)return{success:!1,error:{message:J.error,...J.code!=null?{code:J.code}:{}}};let P=(Y=J.choices)==null?void 0:Y[0];if(P==null)return{success:!1,error:{message:"xAI returned a batch response without any choices.",code:"invalid_response"}};if((Z=P.message.tool_calls)==null?void 0:Z.length)return Vu0("tool_calls");let E=[];if(P.message.content)E.push({type:"text",text:P.message.content});if(P.message.reasoning_content)E.push({type:"reasoning",text:P.message.reasoning_content});for(let w of(W=J.citations)!=null?W:[])E.push({type:"source",sourceType:"url",id:w,url:w});return{success:!0,result:{content:E,finishReason:{unified:gv$(P.finish_reason),raw:(z=P.finish_reason)!=null?z:void 0},usage:J.usage?hv$(J.usage):mZ(),response:ao(J),warnings:[],...(((H=J.usage)==null?void 0:H.cost_in_usd_ticks)!=null||J.service_tier!=null)&&{providerMetadata:{xai:{...((F=J.usage)==null?void 0:F.cost_in_usd_ticks)!=null?{costInUsdTicks:J.usage.cost_in_usd_ticks}:{},...J.service_tier!=null?{serviceTier:J.service_tier}:{}}}}}}}function Vu0(J){return{success:!1,error:{message:`xAI returned "${J}" content, but tool content is not supported in AI SDK text batches.`,code:"unsupported_content"}}}function qu0(J){var Y,Z,W,z,H,F,P,E,w,S,v,x,c,r,n,B$,_$,A$,H$;let M$=J,b$=M$.type;switch(b$){case"session.created":return{type:"session-created",sessionId:(Y=M$.session)==null?void 0:Y.id,raw:J};case"session.updated":return{type:"session-updated",raw:J};case"conversation.created":return{type:"custom",rawType:b$,raw:J};case"input_audio_buffer.speech_started":return{type:"speech-started",itemId:M$.item_id,raw:J};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:M$.item_id,raw:J};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:M$.item_id,previousItemId:M$.previous_item_id,raw:J};case"conversation.item.added":return{type:"conversation-item-added",itemId:(W=(Z=M$.item)==null?void 0:Z.id)!=null?W:M$.item_id,item:M$.item,raw:J};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:M$.item_id,transcript:(z=M$.transcript)!=null?z:"",raw:J};case"response.created":return{type:"response-created",responseId:(F=(H=M$.response)==null?void 0:H.id)!=null?F:M$.response_id,raw:J};case"response.done":return{type:"response-done",responseId:(E=(P=M$.response)==null?void 0:P.id)!=null?E:M$.response_id,status:(S=(w=M$.response)==null?void 0:w.status)!=null?S:"completed",raw:J};case"response.output_item.added":return{type:"output-item-added",responseId:M$.response_id,itemId:(x=(v=M$.item)==null?void 0:v.id)!=null?x:M$.item_id,raw:J};case"response.output_item.done":return{type:"output-item-done",responseId:M$.response_id,itemId:(r=(c=M$.item)==null?void 0:c.id)!=null?r:M$.item_id,raw:J};case"response.content_part.added":return{type:"content-part-added",responseId:M$.response_id,itemId:M$.item_id,raw:J};case"response.content_part.done":return{type:"content-part-done",responseId:M$.response_id,itemId:M$.item_id,raw:J};case"response.output_audio.delta":return{type:"audio-delta",responseId:M$.response_id,itemId:M$.item_id,delta:M$.delta,raw:J};case"response.output_audio.done":return{type:"audio-done",responseId:M$.response_id,itemId:M$.item_id,raw:J};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:M$.response_id,itemId:M$.item_id,delta:M$.delta,raw:J};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:M$.response_id,itemId:M$.item_id,transcript:M$.transcript,raw:J};case"response.text.delta":return{type:"text-delta",responseId:M$.response_id,itemId:M$.item_id,delta:M$.delta,raw:J};case"response.text.done":return{type:"text-done",responseId:M$.response_id,itemId:M$.item_id,text:M$.text,raw:J};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:M$.response_id,itemId:M$.item_id,callId:M$.call_id,delta:M$.delta,raw:J};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:M$.response_id,itemId:M$.item_id,callId:M$.call_id,name:M$.name,arguments:M$.arguments,raw:J};case"mcp_list_tools.in_progress":case"mcp_list_tools.completed":case"mcp_list_tools.failed":case"response.mcp_call_arguments.delta":case"response.mcp_call_arguments.done":case"response.mcp_call.in_progress":case"response.mcp_call.completed":case"response.mcp_call.failed":return{type:"custom",rawType:b$,raw:J};case"error":return{type:"error",message:(_$=(B$=(n=M$.error)==null?void 0:n.message)!=null?B$:M$.message)!=null?_$:"Unknown error",code:(H$=(A$=M$.error)==null?void 0:A$.code)!=null?H$:M$.code,raw:J};default:return{type:"custom",rawType:b$,raw:J}}}function Du0(J){switch(J.type){case"session-update":return{type:"session.update",session:IM6(J.config)};case"input-audio-append":return{type:"input_audio_buffer.append",audio:J.audio};case"input-audio-commit":return{type:"input_audio_buffer.commit"};case"input-audio-clear":return{type:"input_audio_buffer.clear"};case"conversation-item-create":{let Y=J.item;switch(Y.type){case"text-message":return{type:"conversation.item.create",item:{type:"message",role:Y.role,content:[{type:"input_text",text:Y.text}]}};case"audio-message":return{type:"conversation.item.create",item:{type:"message",role:Y.role,content:[{type:"input_audio",audio:Y.audio}]}};case"function-call-output":return{type:"conversation.item.create",item:{type:"function_call_output",call_id:Y.callId,output:Y.output}}}break}case"conversation-item-truncate":return;case"response-create":return{type:"response.create",...J.options!=null?{response:{...J.options.modalities!=null?{modalities:J.options.modalities}:{},...J.options.instructions!=null?{instructions:J.options.instructions}:{}}}:{}};case"response-cancel":return{type:"response.cancel"}}}function IM6(J){var Y;let Z={};if(J.instructions!=null)Z.instructions=J.instructions;if(J.voice!=null)Z.voice=J.voice;let W={};if(J.inputAudioFormat!=null)W.input={format:{type:J.inputAudioFormat.type,...J.inputAudioFormat.rate!=null?{rate:J.inputAudioFormat.rate}:{}}};if(J.outputAudioFormat!=null)W.output={format:{type:J.outputAudioFormat.type,...J.outputAudioFormat.rate!=null?{rate:J.outputAudioFormat.rate}:{}}};if(Object.keys(W).length>0)Z.audio=W;if(J.turnDetection!=null)if(J.turnDetection.type==="disabled")Z.turn_detection=null;else{let z={type:"server_vad"};if(J.turnDetection.threshold!=null)z.threshold=J.turnDetection.threshold;if(J.turnDetection.silenceDurationMs!=null)z.silence_duration_ms=J.turnDetection.silenceDurationMs;if(J.turnDetection.prefixPaddingMs!=null)z.prefix_padding_ms=J.turnDetection.prefixPaddingMs;Z.turn_detection=z}if(J.tools!=null&&J.tools.length>0)Z.tools=J.tools.map((z)=>({type:z.type,name:z.name,description:z.description,parameters:z.parameters}));if(J.providerOptions!=null){let z=J.providerOptions;if(Array.isArray(z.tools)){let H=(Y=Z.tools)!=null?Y:[];Z.tools=[...H,...z.tools]}for(let[H,F]of Object.entries(z))if(H!=="tools")Z[H]=F}return Z}function Su0(J){let Y=encodeURIComponent(J);return Y==="."?"%252E":Y===".."?"%252E%252E":Y}function CM6(J){var Y,Z;return(Z=(Y=J.frameImages)==null?void 0:Y.find((W)=>W.frameType==="first_frame"))==null?void 0:Z.image}function bu0(J){var Y,Z;return(Z=(Y=J.frameImages)==null?void 0:Y.find((W)=>W.frameType==="last_frame"))==null?void 0:Z.image}function ku0(J){var Y;return(Y=CM6(J))!=null?Y:J.image}function kM6(J){if(J.type==="url")return J.url;let Y=typeof J.data==="string"?J.data:ME(J.data);return`data:${J.mediaType};base64,${Y}`}function xu0(J,Y,Z){if(J.inputReferences!=null&&J.inputReferences.length>0){let W=[];for(let z of J.inputReferences){if(!bM6(z)){Z.push({type:"unsupported",feature:"inputReferences",details:pv$(z)?'xAI reference-to-video accepts image references only. The video reference was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video.':"xAI reference-to-video accepts image references only. The non-image reference was ignored."});continue}W.push(z)}return W.length>0?W.map((z)=>({url:kM6(z)})):void 0}if((Y==null?void 0:Y.referenceImageUrls)!=null&&Y.referenceImageUrls.length>0)return Y.referenceImageUrls.map((W)=>({url:W}));return}function xM6(J){var Y,Z;return(Z=(Y=J.inputReferences)==null?void 0:Y.some(bM6))!=null?Z:!1}function yu0(J,Y){if((Y==null?void 0:Y.mode)!=null)return Y.mode;if((Y==null?void 0:Y.videoUrl)!=null)return"edit-video";let Z=J.frameImages!=null&&J.frameImages.length>0,W=(Y==null?void 0:Y.referenceImageUrls)!=null&&Y.referenceImageUrls.length>0;if(!Z&&(xM6(J)||W))return"reference-to-video";return}async function mu0({response:J,url:Y,requestBodyValues:Z}){if(J.body==null)return"";let W=J.body.getReader(),z=[],H=0;try{while(!0){let{done:E,value:w}=await W.read();if(E)break;if(H+=w.length,H>HM6)throw new Z5({message:`xAI video status response exceeded ${HM6} bytes`,url:Y,requestBodyValues:Z,statusCode:J.status,responseHeaders:mD(J)});z.push(w)}}finally{W.releaseLock()}let F=new Uint8Array(H),P=0;for(let E of z)F.set(E,P),P+=E.length;return gu0.decode(F)}function iu0({webSocket:J,url:Y,headers:Z,warnings:W,language:z,expectedDoneCount:H,audio:F,abortSignal:P,includeRawChunks:E}){let w=!1,S=()=>{};return new ReadableStream({start:(v)=>{let x=new Map,c=new Map,r=new Map,n,B$,_$;S=(b$)=>{if(B$!=null)B$.cancel().catch(()=>{});else F.cancel().catch(()=>{});_$==null||_$.close(b$)};let A$=(b$)=>{if(w)return;w=!0,S(),v.error(b$)},H$=()=>{if(w||x.size<H)return;w=!0;let b$=[...x.entries()].sort(([p$],[o$])=>p$-o$).map(([,p$])=>p$).join(`
725
725
  `);v.enqueue({type:"finish",text:b$,segments:[],language:z,durationInSeconds:n}),v.close(),S(1000)},M$=async(b$)=>{B$=F.getReader();try{while(!0){let{done:p$,value:o$}=await B$.read();if(p$||w)break;b$.send(o$ instanceof Uint8Array?o$:BK(o$)),await QM(b$)}}finally{B$.releaseLock(),B$=void 0}if(!w)b$.send(JSON.stringify({type:"audio.done"}))};_$=KM({url:Y,headers:Z,webSocket:J,abortSignal:P,onAbort:A$,onProcessingError:A$,onMessageText:async(b$)=>{var p$,o$,T6,j6,Y6,y$,_6,k6,x$;let r0=await Zz({text:b$});if(!r0.success)return;let m0=r0.value;if(E)v.enqueue({type:"raw",rawValue:m0});switch(m0.type){case"transcript.created":{v.enqueue({type:"stream-start",warnings:W});let b6=_$==null?void 0:_$.socket;if(b6==null){A$(Error("WebSocket is not connected."));break}M$(b6).catch(A$);break}case"transcript.partial":{let b6=nu0(m0.channel_index),W0=(p$=m0.channel_index)!=null?p$:0;if(m0.is_final&&m0.speech_final){let J1=ou0(m0);if(m0.text)c.set(W0,[...(o$=c.get(W0))!=null?o$:[],m0.text]);r.delete(W0),v.enqueue({type:"transcript-final",id:b6,text:(T6=m0.text)!=null?T6:"",...J1,channelIndex:m0.channel_index})}else r.set(W0,(j6=m0.text)!=null?j6:""),v.enqueue({type:"transcript-partial",id:b6,text:(Y6=m0.text)!=null?Y6:"",startSecond:m0.start,durationInSeconds:m0.duration,channelIndex:m0.channel_index});break}case"transcript.done":{let b6=(y$=m0.channel_index)!=null?y$:0,W0=[...(_6=c.get(b6))!=null?_6:[],...r.get(b6)?[r.get(b6)]:[]].join(" ");x.set(b6,m0.text||W0),n=(k6=m0.duration)!=null?k6:n,H$();break}case"error":{A$(Error((x$=m0.message)!=null?x$:"xAI STT error"));break}}},onSocketError:()=>{A$(Error("xAI streaming transcription error."+(J==null?" Note: the native WebSocket implementation in browsers, Node.js, Deno, and Bun cannot send the Authorization header required by xAI. Pass a header-capable WebSocket implementation (e.g. the 'ws' package) via createXai({ webSocket }).":"")))},onClose:()=>{if(w)return;w=!0,S(),v.close()}})},cancel:()=>{if(w)return;w=!0,S()}})}function ru0({baseURL:J,inputAudioFormat:Y,providerOptions:Z}){var W,z,H,F,P,E;let w=om(`${J}/stt`);if(xL(w,"sample_rate",(W=Z==null?void 0:Z.sampleRate)!=null?W:Y.rate),xL(w,"encoding",(z=Z==null?void 0:Z.audioFormat)!=null?z:au0(Y.type)),xL(w,"language",Z==null?void 0:Z.language),xL(w,"diarize",Z==null?void 0:Z.diarize),xL(w,"filler_words",Z==null?void 0:Z.fillerWords),xL(w,"multichannel",Z==null?void 0:Z.multichannel),xL(w,"channels",Z==null?void 0:Z.channels),xL(w,"interim_results",(H=Z==null?void 0:Z.streaming)==null?void 0:H.interimResults),xL(w,"endpointing",(F=Z==null?void 0:Z.streaming)==null?void 0:F.endpointing),xL(w,"smart_turn",(P=Z==null?void 0:Z.streaming)==null?void 0:P.smartTurn),xL(w,"smart_turn_timeout",(E=Z==null?void 0:Z.streaming)==null?void 0:E.smartTurnTimeout),(Z==null?void 0:Z.keyterm)!=null){let S=Array.isArray(Z.keyterm)?Z.keyterm:[Z.keyterm];for(let v of S)w.searchParams.append("keyterm",v)}return w}function xL(J,Y,Z){if(Z!=null)J.searchParams.set(Y,String(Z))}function su0(J){return J==="audio/pcm"||J==="audio/pcmu"||J==="audio/pcma"}function au0(J){switch(J){case"audio/pcmu":return"mulaw";case"audio/pcma":return"alaw";default:return"pcm"}}function nu0(J){return J==null?void 0:`channel-${J}`}function ou0(J){return{...J.start!=null?{startSecond:J.start}:{},...J.start!=null&&J.duration!=null?{endSecond:J.start+J.duration}:{}}}function fM6(J={}){var Y;let Z=XW((Y=J.baseURL)!=null?Y:"https://api.x.ai/v1"),W=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"XAI_API_KEY",description:"xAI API key"})}`,...J.headers},`ai-sdk/xai/${SM6}`),z=(r)=>{return new Nm0(r,{provider:"xai.chat",baseURL:Z,headers:W,generateId:wY,fetch:J.fetch})},H=(r)=>{return new zu0(r,{provider:"xai.responses",baseURL:Z,headers:W,generateId:wY,fetch:J.fetch})},F=(r)=>{return new Tm0(r,{provider:"xai.image",baseURL:Z,headers:W,fetch:J.fetch})},P=(r)=>{return new fu0(r,{provider:"xai.video",baseURL:Z,headers:W,fetch:J.fetch})},E=(r)=>{return new EM6(r,{provider:"xai.realtime",baseURL:Z!=null?Z:"https://api.x.ai/v1",headers:W,fetch:J.fetch})},w=()=>{return new du0("",{provider:"xai.speech",baseURL:Z,headers:W,fetch:J.fetch})},S=()=>{return new pu0("",{provider:"xai.transcription",baseURL:Z,headers:W,fetch:J.fetch,webSocket:J.webSocket})},v=Object.assign((r)=>E(r),{getToken:async(r)=>{let B$=await E(r.model).doCreateClientSecret({sessionConfig:r.sessionConfig,expiresAfterSeconds:r.expiresAfterSeconds});return{token:B$.token,url:B$.url,expiresAt:B$.expiresAt}}}),x=()=>new Iu0({provider:"xai.files",baseURL:Z,headers:W,fetch:J.fetch}),c=(r)=>H(r);return c.specificationVersion="v4",c.languageModel=H,c.chat=z,c.responses=H,c.embeddingModel=(r)=>{throw new CW({modelId:r,modelType:"embeddingModel"})},c.textEmbeddingModel=c.embeddingModel,c.imageModel=F,c.image=F,c.videoModel=P,c.video=P,c.experimental_realtime=v,c.speechModel=w,c.speech=w,c.transcriptionModel=S,c.transcription=S,c.files=x,c.tools=wM6,c}var qM6,jm0,Bm0,Hm0,Vm0,qm0,Dm0,Fm0,Am0,Lm0,Om0,Pm0,Jq,Nm0,FM6,AM6,Im0,Em0,_m0,Tm0,Rm0,LM6,mv$,uv$,cv$,tk,Sm0,Cm0,bm0,dv$,lv$,so,km0,xm0,ym0,fm0,vm0,hm0=(J)=>vm0(J),gm0,mm0,um0,cm0,OM6=(J={})=>cm0(J),dm0,lm0,pm0,PM6=(J)=>pm0(J),im0,rm0,sm0,MM6=(J={})=>sm0(J),am0,nm0,om0,NM6=(J={})=>om0(J),zM6,Xu0="/v1/responses",Yu0="ai-sdk-text-batch",Qu0=1000,jM6,Ku0,Zu0,Gu0,Wu0=class{constructor(J){this.options=J}async startBatch(J){var Y,Z;let W=[],z=J.webhookUrl==null?[]:[{warning:{type:"unsupported",feature:"webhookUrl",details:"The xAI Batch API does not support per-batch webhook URLs."}}];for(let v of J.requests){let x=await this.options.prepareRequest(v);W.push(JSON.stringify({custom_id:v.id,method:"POST",url:Xu0,body:x.body}),`
726
- `);for(let c of x.warnings)z.push({requestId:v.id,warning:c})}let H="batch.jsonl",F=new Blob(W,{type:"application/jsonl"});W.length=0;let P=new FormData;P.append("file",F,H);let E=TJ((Z=(Y=this.options.config).headers)==null?void 0:Z.call(Y),J.headers),{value:w}=await nK({url:this.getUrl("/files"),headers:E,formData:P,failedResponseHandler:Jq,successfulResponseHandler:Z9(LM6),abortSignal:J.abortSignal,fetch:this.options.config.fetch}),{value:S}=await W4({url:this.getUrl("/batches"),headers:E,body:{name:Yu0,input_file_id:w.id},failedResponseHandler:Jq,successfulResponseHandler:Z9(jM6),abortSignal:J.abortSignal,fetch:this.options.config.fetch});return{batchId:S.batch_id,...fv$(S),warnings:z}}async getBatchStatus(J){return fv$(await this.retrieveBatch(J))}async getBatchResults(J){let Y=await this.retrieveBatch(J);if(fv$(Y).status==="pending")throw new U7({argument:"batchId",message:`xAI batch "${J.batchId}" is not complete.`});return PE(this.iterateBatchResults(J))}async retrieveBatch(J){var Y,Z;let{value:W}=await aK({url:this.getUrl(`/batches/${encodeURIComponent(J.batchId)}`),headers:TJ((Z=(Y=this.options.config).headers)==null?void 0:Z.call(Y),J.headers),failedResponseHandler:Jq,successfulResponseHandler:Z9(jM6),abortSignal:J.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return W}async*iterateBatchResults(J){var Y,Z,W;let z;do{let H=new URLSearchParams({limit:String(Qu0)});if(z!=null)H.set("pagination_token",z);let{value:F}=await aK({url:this.getUrl(`/batches/${encodeURIComponent(J.batchId)}/results?${H}`),headers:TJ((Z=(Y=this.options.config).headers)==null?void 0:Z.call(Y),J.headers),failedResponseHandler:Jq,successfulResponseHandler:Z9(Gu0),abortSignal:J.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});for(let P of F.results)yield await this.convertBatchResult(P);z=(W=F.pagination_token)!=null?W:void 0}while(z!=null)}async convertBatchResult(J){var Y,Z,W,z,H,F;let P=(Y=J.batch_result)==null?void 0:Y.error;if(((W=(Z=J.error_message)==null?void 0:Z.length)!=null?W:0)>0||(P==null?void 0:P.code)!=null&&P.code!==0&&P.code!=="0"||(P==null?void 0:P.code)==null&&((H=(z=P==null?void 0:P.message)==null?void 0:z.length)!=null?H:0)>0){let w=ju0(J);return{id:J.batch_request_id,status:Bu0(P==null?void 0:P.code)?"cancelled":"failed",error:w}}let E=(F=J.batch_result)==null?void 0:F.response;if((E==null?void 0:E.chat_get_completion)!=null){let w=await uD({value:E.chat_get_completion,schema:AM6});if(!w.success)return BM6(J.batch_request_id);let S=Hu0(w.value);return S.success?{id:J.batch_request_id,status:"succeeded",result:S.result}:{id:J.batch_request_id,status:"failed",error:S.error}}return BM6(J.batch_request_id)}getUrl(J){var Y;return`${(Y=this.options.config.baseURL)!=null?Y:"https://api.x.ai/v1"}${J}`}},zu0,EM6=class{constructor(J,Y){this.specificationVersion="v4",this.modelId=J,this.provider=Y.provider,this.config=Y}async doCreateClientSecret(J){var Y;let Z=(Y=this.config.fetch)!=null?Y:fetch,W=`${this.config.baseURL}/realtime/client_secrets`,z={};if(J.expiresAfterSeconds!=null)z.expires_after={seconds:J.expiresAfterSeconds};let H=await Z(W,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify(z)});if(!H.ok){let P=await H.text();throw Error(`xAI realtime client secret request failed: ${H.status} ${P}`)}let F=await H.json();return{token:F.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:F.expires_at}}getWebSocketConfig(J){return{url:J.url,protocols:[`xai-client-secret.${J.token}`]}}parseServerEvent(J){return qu0(J)}serializeClientEvent(J){return Du0(J)}buildSessionConfig(J){return IM6(J)}},Fu0,Au0,_M6=(J={})=>Au0(J),Lu0,Ou0,TM6=(J={})=>Ou0(J),Pu0,Mu0,RM6=(J={})=>Mu0(J),wM6,SM6="4.0.48",Nu0,Iu0=class{constructor(J){this.config=J,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:J,mediaType:Y,filename:Z,providerOptions:W}){var z,H;let F=await dJ({provider:"xai",providerOptions:W,schema:Nu0}),P=eV(J),E=new Blob([P],{type:Y}),w=new FormData;if(Z!=null)w.append("file",E,Z);else w.append("file",E);if((F==null?void 0:F.teamId)!=null)w.append("team_id",F.teamId);let{value:S}=await nK({url:`${this.config.baseURL}/files`,headers:TJ(this.config.headers()),formData:w,failedResponseHandler:Jq,successfulResponseHandler:Z9(LM6),fetch:this.config.fetch});return{warnings:[],providerReference:{xai:S.id},...((z=S.filename)!=null?z:Z)?{filename:(H=S.filename)!=null?H:Z}:{},...Y!=null?{mediaType:Y}:{},providerMetadata:{xai:{...S.filename!=null?{filename:S.filename}:{},...S.bytes!=null?{bytes:S.bytes}:{},...S.created_at!=null?{createdAt:S.created_at}:{}}}}}},vv$,Eu0,_u0,Tu0,Ru0,wu0,Cu0,pv$=(J)=>J.mediaType!=null&&C7(J.mediaType)==="video",bM6=(J)=>J.mediaType==null||C7(J.mediaType)==="image",fu0=class{constructor(J,Y){this.modelId=J,this.config=Y,this.specificationVersion="v4",this.maxVideosPerCall=1}get provider(){return this.config.provider}async buildRequestBody(J){let Y=[],Z=await dJ({provider:"xai",providerOptions:J.providerOptions,schema:wu0}),W=yu0(J,Z),z=W==="edit-video",H=W==="extend-video",F=W==="reference-to-video";if(J.fps!=null)Y.push({type:"unsupported",feature:"fps",details:"xAI video models do not support custom FPS."});if(J.seed!=null)Y.push({type:"unsupported",feature:"seed",details:"xAI video models do not support seed."});if(J.n!=null&&J.n>1)Y.push({type:"unsupported",feature:"n",details:"xAI video models do not support generating multiple videos per call. Only 1 video will be generated."});if(z&&J.duration!=null)Y.push({type:"unsupported",feature:"duration",details:"xAI video editing does not support custom duration."});if(z&&J.aspectRatio!=null)Y.push({type:"unsupported",feature:"aspectRatio",details:"xAI video editing does not support custom aspect ratio."});if(z&&((Z==null?void 0:Z.resolution)!=null||J.resolution!=null))Y.push({type:"unsupported",feature:"resolution",details:"xAI video editing does not support custom resolution."});if(H&&J.aspectRatio!=null)Y.push({type:"unsupported",feature:"aspectRatio",details:"xAI video extension does not support custom aspect ratio."});if(H&&((Z==null?void 0:Z.resolution)!=null||J.resolution!=null))Y.push({type:"unsupported",feature:"resolution",details:"xAI video extension does not support custom resolution."});let P={model:this.modelId,prompt:J.prompt},E=!z,w=!z&&!H,S=!z&&!H;if(E&&J.duration!=null)P.duration=J.duration;if(w&&J.aspectRatio!=null)P.aspect_ratio=J.aspectRatio;if(S&&(Z==null?void 0:Z.resolution)!=null)P.resolution=Z.resolution;else if(S&&J.resolution!=null){let c=Cu0[J.resolution];if(c!=null)P.resolution=c;else Y.push({type:"unsupported",feature:"resolution",details:`Unrecognized resolution "${J.resolution}". Use providerOptions.xai.resolution with "480p", "720p", or "1080p" instead.`})}if(z)P.video={url:Z.videoUrl};if(H)P.video={url:Z.videoUrl};let v=ku0(J);if(v!=null)if(pv$(v)){let c=CM6(J)!=null;Y.push({type:"unsupported",feature:c?"frameImages":"image",details:'xAI does not accept a video as a start/frame image. The video was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.'})}else P.image={url:kM6(v)};let x=bu0(J);if(x!=null)Y.push({type:"unsupported",feature:"frameImages",details:pv$(x)?'xAI does not accept a video as a start/frame image. The video last frame was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.':`xAI video models do not support last_frame. Use providerOptions.xai.mode "extend-video" to continue from a video's last frame. The last frame image was ignored.`});if(F){let c=xu0(J,Z,Y);if(c!=null)P.reference_images=c;else Y.push({type:"unsupported",feature:"referenceImages",details:"xAI reference-to-video requires at least one image reference. The video will be generated without reference images."});let r=Z==null?void 0:Z.referenceVoiceIds;if(r!=null&&r.length>0)P.reference_audios=r.map((n)=>({voice_id:n}));if(P.resolution==="1080p")Y.push({type:"unsupported",feature:"resolution",details:"xAI reference-to-video is limited to 720p. The request was downgraded from 1080p to 720p."}),P.resolution="720p"}if(P.resolution==="1080p"&&this.modelId==="grok-imagine-video")Y.push({type:"unsupported",feature:"resolution",details:'xAI model "grok-imagine-video" does not support 1080p. Use "grok-imagine-video-1.5" for 1080p, or a lower resolution. The request was sent with 1080p.'});if(J.inputReferences!=null&&J.inputReferences.length>0&&!F)Y.push({type:"unsupported",feature:"inputReferences",details:xM6(J)?"xAI only supports inputReferences for reference-to-video generation. The reference images were ignored.":"xAI reference-to-video requires at least one image reference. The references were ignored."});if((Z==null?void 0:Z.referenceVoiceIds)!=null&&Z.referenceVoiceIds.length>0&&!F)Y.push({type:"unsupported",feature:"referenceVoiceIds",details:"xAI only supports reference voices for reference-to-video generation. The reference voices were ignored."});if(!H&&(Z==null?void 0:Z.user)!==void 0)P.user=Z.user;if(Z!=null){for(let[c,r]of Object.entries(Z))if(!["mode","pollIntervalMs","pollTimeoutMs","resolution","videoUrl","referenceImageUrls","referenceVoiceIds","user"].includes(c))P[c]=r}return{body:P,warnings:Y,xaiOptions:Z,isEdit:z,isExtension:H,hasReferenceImages:F,effectiveMode:W}}async doStart(J){var Y,Z,W,z;let H=(W=(Z=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:Z.call(Y))!=null?W:new Date,{body:F,warnings:P,isEdit:E,isExtension:w}=await this.buildRequestBody(J),S=(z=this.config.baseURL)!=null?z:"https://api.x.ai/v1",v;if(E)v=`${S}/videos/edits`;else if(w)v=`${S}/videos/extensions`;else v=`${S}/videos/generations`;let{value:x,responseHeaders:c}=await W4({url:v,headers:TJ(this.config.headers(),J.headers),body:F,failedResponseHandler:Jq,successfulResponseHandler:Z9(vu0),abortSignal:J.abortSignal,fetch:this.config.fetch}),r=x.request_id;if(!r)throw new UQ({name:"XAI_VIDEO_GENERATION_ERROR",message:"No request_id returned from xAI API."});return{operation:{requestId:r},warnings:P,response:{timestamp:H,modelId:this.modelId,headers:c}}}async doStatus(J){var Y,Z,W,z,H,F,P,E,w,S,v;let x=(W=(Z=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:Z.call(Y))!=null?W:new Date,{requestId:c}=J.operation,r=(z=this.config.baseURL)!=null?z:"https://api.x.ai/v1",{value:n,responseHeaders:B$}=await aK({url:`${r}/videos/${Su0(c)}`,validateUrl:!1,headers:TJ(this.config.headers(),J.headers),successfulResponseHandler:uu0,failedResponseHandler:Jq,abortSignal:J.abortSignal,fetch:this.config.fetch});if(n.status==="expired")return{status:"error",error:"Video generation request expired.",response:{timestamp:x,modelId:this.modelId,headers:B$}};if(n.status==="failed"){let _$=(P=(H=n.error)==null?void 0:H.message)!=null?P:(F=n.error)==null?void 0:F.code;return{status:"error",error:_$!=null?`Video generation failed: ${_$}`:"Video generation failed.",response:{timestamp:x,modelId:this.modelId,headers:B$}}}if(n.status==="done"||n.status==null&&((E=n.video)==null?void 0:E.url)){if(((w=n.video)==null?void 0:w.respect_moderation)===!1)return{status:"error",error:"Video generation was blocked due to a content policy violation.",response:{timestamp:x,modelId:this.modelId,headers:B$}};if(!((S=n.video)==null?void 0:S.url))return{status:"error",error:"Video generation completed but no video URL was returned.",response:{timestamp:x,modelId:this.modelId,headers:B$}};return{status:"completed",videos:[{type:"url",url:n.video.url,mediaType:"video/mp4"}],warnings:[],response:{timestamp:x,modelId:this.modelId,headers:B$},providerMetadata:{xai:{requestId:c,videoUrl:n.video.url,...n.video.duration!=null?{duration:n.video.duration}:{},...((v=n.usage)==null?void 0:v.cost_in_usd_ticks)!=null?{costInUsdTicks:n.usage.cost_in_usd_ticks}:{},...n.progress!=null?{progress:n.progress}:{}}}}}return{status:"pending",response:{timestamp:x,modelId:this.modelId,headers:B$}}}},vu0,yM6,hu0,HM6=1048576,gu0,uu0=async(J)=>{if(J.response.status===202){let Y=mD(J.response),Z=await mu0(J);if(Z.trim().length===0)return{responseHeaders:Y,value:{status:"pending"}};let W=await Zz({text:Z,schema:yM6});return{responseHeaders:Y,value:W.success?W.value:{status:"pending"}}}return hu0(J)},cu0,du0,lu0,VM6,pu0,tu0,eu0;var hM6=n9(()=>{g4();C1();g4();C1();c8();g4();C1();c8();C1();c8();C1();c8();g4();C1();c8();c8();g4();C1();c8();C1();c8();C1();g4();C1();c8();c8();g4();C1();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();C1();c8();g4();C1();c8();C1();c8();C1();c8();C1();c8();g4();C1();c8();C1();c8();qM6=q.object({imageDetail:q.enum(["low","high","auto"]).optional()});jm0=/^grok-4\.20(-\d{4})?-(non-)?reasoning$/;Bm0=q.object({type:q.literal("web"),country:q.string().length(2).optional(),excludedWebsites:q.array(q.string()).max(5).optional(),allowedWebsites:q.array(q.string()).max(5).optional(),safeSearch:q.boolean().optional()}),Hm0=q.object({type:q.literal("x"),excludedXHandles:q.array(q.string()).optional(),includedXHandles:q.array(q.string()).optional(),postFavoriteCount:q.number().int().optional(),postViewCount:q.number().int().optional(),xHandles:q.array(q.string()).optional()}),Vm0=q.object({type:q.literal("news"),country:q.string().length(2).optional(),excludedWebsites:q.array(q.string()).max(5).optional(),safeSearch:q.boolean().optional()}),qm0=q.object({type:q.literal("rss"),links:q.array(q.string().url()).max(1)}),Dm0=q.discriminatedUnion("type",[Bm0,Hm0,Vm0,qm0]),Fm0=q.object({reasoningEffort:q.enum(["none","low","medium","high","xhigh"]).optional(),logprobs:q.boolean().optional(),topLogprobs:q.number().int().min(0).max(8).optional(),serviceTier:q.enum(["default","priority"]).optional(),parallel_function_calling:q.boolean().optional(),searchParameters:q.object({mode:q.enum(["off","auto","on"]),returnCitations:q.boolean().optional(),fromDate:q.string().optional(),toDate:q.string().optional(),maxSearchResults:q.number().min(1).max(50).optional(),sources:q.array(Dm0).optional()}).optional()}),Am0=q.object({error:q.object({message:q.string(),type:q.string().nullish(),param:q.any().nullish(),code:q.union([q.string(),q.number()]).nullish()})}),Lm0=q.object({code:q.string(),error:q.string()}),Om0=q.object({error:q.string()}),Pm0=q.union([Am0,Lm0,Om0]),Jq=b2({errorSchema:Pm0,errorToMessage:(J)=>{if(typeof J.error==="string")return"code"in J?`${J.code}: ${J.error}`:J.error;return J.error.message}});Nm0=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,seed:w,reasoning:S,responseFormat:v,providerOptions:x,tools:c,toolChoice:r}){var n,B$,_$;let A$=[],H$=(n=await dJ({provider:"xai",providerOptions:x,schema:Fm0}))!=null?n:{};if(H!=null)A$.push({type:"unsupported",feature:"topK"});if(F!=null)A$.push({type:"unsupported",feature:"frequencyPenalty"});if(P!=null)A$.push({type:"unsupported",feature:"presencePenalty"});if(E!=null)A$.push({type:"unsupported",feature:"stopSequences"});let{messages:M$,warnings:b$}=await Um0(Y);A$.push(...b$);let{tools:p$,toolChoice:o$,toolWarnings:T6}=Mm0({tools:c,toolChoice:r});A$.push(...T6);let j6=H$.reasoningEffort;if(j6==null&&wZ(S))if(!DM6(this.modelId))A$.push({type:"unsupported",feature:"reasoning",details:`reasoning "${S}" is not supported by this model.`});else if(S==="none")j6="none";else j6=$q({reasoning:S,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:this.modelId==="grok-4.6"?"xhigh":"high"},warnings:A$});return{args:{model:this.modelId,logprobs:H$.logprobs===!0||H$.topLogprobs!=null?!0:void 0,top_logprobs:H$.topLogprobs,max_completion_tokens:Z,temperature:W,top_p:z,seed:w,reasoning_effort:j6,service_tier:H$.serviceTier,parallel_function_calling:H$.parallel_function_calling,response_format:(v==null?void 0:v.type)==="json"?v.schema!=null?{type:"json_schema",json_schema:{name:(B$=v.name)!=null?B$:"response",schema:v.schema,strict:!0}}:{type:"json_object"}:void 0,search_parameters:H$.searchParameters?{mode:H$.searchParameters.mode,return_citations:H$.searchParameters.returnCitations,from_date:H$.searchParameters.fromDate,to_date:H$.searchParameters.toDate,max_search_results:H$.searchParameters.maxSearchResults,sources:(_$=H$.searchParameters.sources)==null?void 0:_$.map((y$)=>{var _6;return{type:y$.type,...y$.type==="web"&&{country:y$.country,excluded_websites:y$.excludedWebsites,allowed_websites:y$.allowedWebsites,safe_search:y$.safeSearch},...y$.type==="x"&&{excluded_x_handles:y$.excludedXHandles,included_x_handles:(_6=y$.includedXHandles)!=null?_6:y$.xHandles,post_favorite_count:y$.postFavoriteCount,post_view_count:y$.postViewCount},...y$.type==="news"&&{country:y$.country,excluded_websites:y$.excludedWebsites,safe_search:y$.safeSearch},...y$.type==="rss"&&{links:y$.links}}})}:void 0,messages:M$,tools:p$,tool_choice:o$},warnings:A$}}async doGenerate(Y){var Z,W,z,H;let{args:F,warnings:P}=await this.getArgs(Y),E=`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/chat/completions`,{responseHeaders:w,value:S,rawValue:v}=await W4({url:E,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:F,failedResponseHandler:Jq,successfulResponseHandler:Z9(AM6),abortSignal:Y.abortSignal,fetch:this.config.fetch});if(S.error!=null)throw new Z5({message:S.error,url:E,requestBodyValues:F,statusCode:200,responseHeaders:w,responseBody:JSON.stringify(v),isRetryable:S.code==="The service is currently unavailable"});let x=S.choices[0],c=[];if(x.message.content!=null&&x.message.content.length>0){let r=x.message.content,n=F.messages[F.messages.length-1];if((n==null?void 0:n.role)==="assistant"&&r===n.content)r="";if(r.length>0)c.push({type:"text",text:r})}if(x.message.reasoning_content!=null&&x.message.reasoning_content.length>0)c.push({type:"reasoning",text:x.message.reasoning_content});if(x.message.tool_calls!=null)for(let r of x.message.tool_calls)c.push({type:"tool-call",toolCallId:r.id,toolName:r.function.name,input:r.function.arguments});if(S.citations!=null)for(let r of S.citations)c.push({type:"source",sourceType:"url",id:this.config.generateId(),url:r});return{content:c,finishReason:{unified:gv$(x.finish_reason),raw:(H=x.finish_reason)!=null?H:void 0},usage:S.usage?hv$(S.usage):{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...S.service_tier!=null&&{providerMetadata:{xai:{serviceTier:S.service_tier}}},request:{body:F},response:{...ao(S),headers:w,body:v},warnings:P}}async doStream(Y){var Z,W,z;let{args:H,warnings:F}=await this.getArgs(Y),P={...H,stream:!0,stream_options:{include_usage:!0}},E=`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/chat/completions`,{responseHeaders:w,value:S}=await W4({url:E,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:P,failedResponseHandler:Jq,successfulResponseHandler:async({response:H$})=>{let M$=mD(H$),b$=H$.headers.get("content-type");if(b$==null?void 0:b$.includes("application/json")){let p$=await H$.text(),o$=await Zz({text:p$,schema:Em0});if(o$.success)throw new Z5({message:o$.value.error,url:E,requestBodyValues:P,statusCode:200,responseHeaders:M$,responseBody:p$,isRetryable:o$.value.code==="The service is currently unavailable"});throw new Z5({message:"Invalid JSON response",url:E,requestBodyValues:P,statusCode:200,responseHeaders:M$,responseBody:p$})}return k2(Im0)({response:H$,url:E,requestBodyValues:P})},abortSignal:Y.abortSignal,fetch:this.config.fetch}),v={unified:"other",raw:void 0},x=void 0,c=void 0,r=!0,n={},B$={},_$=void 0,A$=this;return{stream:S.pipeThrough(new TransformStream({start(H$){H$.enqueue({type:"stream-start",warnings:F})},transform(H$,M$){if(Y.includeRawChunks)M$.enqueue({type:"raw",rawValue:H$.rawValue});if(!H$.success){M$.enqueue({type:"error",error:H$.error});return}let b$=H$.value;if(r)M$.enqueue({type:"response-metadata",...ao(b$)}),r=!1;if(b$.citations!=null)for(let j6 of b$.citations)M$.enqueue({type:"source",sourceType:"url",id:A$.config.generateId(),url:j6});if(b$.usage!=null)x=hv$(b$.usage);if(b$.service_tier!=null)c=b$.service_tier;let p$=b$.choices[0];if((p$==null?void 0:p$.finish_reason)!=null)v={unified:gv$(p$.finish_reason),raw:p$.finish_reason};if((p$==null?void 0:p$.delta)==null)return;let{delta:o$,index:T6}=p$;if(o$.content!=null&&o$.content.length>0){let j6=o$.content;if(_$!=null&&!n[_$].ended)M$.enqueue({type:"reasoning-end",id:_$}),n[_$].ended=!0,_$=void 0;let Y6=P.messages[P.messages.length-1];if((Y6==null?void 0:Y6.role)==="assistant"&&j6===Y6.content)return;let y$=`text-${b$.id||T6}`;if(n[y$]==null)n[y$]={type:"text",ended:!1},M$.enqueue({type:"text-start",id:y$});M$.enqueue({type:"text-delta",id:y$,delta:j6})}if(o$.reasoning_content!=null&&o$.reasoning_content.length>0){let j6=`reasoning-${b$.id||T6}`;if(B$[j6]===o$.reasoning_content)return;if(B$[j6]=o$.reasoning_content,n[j6]==null)n[j6]={type:"reasoning",ended:!1},_$=j6,M$.enqueue({type:"reasoning-start",id:j6});M$.enqueue({type:"reasoning-delta",id:j6,delta:o$.reasoning_content})}if(o$.tool_calls!=null){if(_$!=null&&!n[_$].ended)M$.enqueue({type:"reasoning-end",id:_$}),n[_$].ended=!0,_$=void 0;for(let j6 of o$.tool_calls){let Y6=j6.id;M$.enqueue({type:"tool-input-start",id:Y6,toolName:j6.function.name}),M$.enqueue({type:"tool-input-delta",id:Y6,delta:j6.function.arguments}),M$.enqueue({type:"tool-input-end",id:Y6}),M$.enqueue({type:"tool-call",toolCallId:Y6,toolName:j6.function.name,input:j6.function.arguments})}}},flush(H$){for(let[M$,b$]of Object.entries(n))if(!b$.ended)H$.enqueue({type:b$.type==="text"?"text-end":"reasoning-end",id:M$});H$.enqueue({type:"finish",finishReason:v,usage:x!=null?x:{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...c!=null&&{providerMetadata:{xai:{serviceTier:c}}}})}})),request:{body:P},response:{headers:w}}}},FM6=q.object({prompt_tokens:q.number(),completion_tokens:q.number(),total_tokens:q.number(),cost_in_usd_ticks:q.number().nullish(),prompt_tokens_details:q.object({text_tokens:q.number().nullish(),audio_tokens:q.number().nullish(),image_tokens:q.number().nullish(),cached_tokens:q.number().nullish()}).catchall(q.json()).nullish(),completion_tokens_details:q.object({reasoning_tokens:q.number().nullish(),audio_tokens:q.number().nullish(),accepted_prediction_tokens:q.number().nullish(),rejected_prediction_tokens:q.number().nullish()}).catchall(q.json()).nullish()}).catchall(q.json()),AM6=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({message:q.object({role:q.literal("assistant"),content:q.string().nullish(),reasoning_content:q.string().nullish(),tool_calls:q.array(q.object({id:q.string(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),index:q.number(),finish_reason:q.string().nullish()})).nullish(),object:q.literal("chat.completion").nullish(),usage:FM6.nullish(),citations:q.array(q.string().url()).nullish(),service_tier:q.string().nullish(),code:q.string().nullish(),error:q.string().nullish()}),Im0=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({delta:q.object({role:q.enum(["assistant"]).optional(),content:q.string().nullish(),reasoning_content:q.string().nullish(),tool_calls:q.array(q.object({id:q.string(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),finish_reason:q.string().nullish(),index:q.number()})),usage:FM6.nullish(),citations:q.array(q.string().url()).nullish(),service_tier:q.string().nullish()}),Em0=q.object({code:q.string(),error:q.string()}),_m0=q.object({aspect_ratio:q.string().optional(),output_format:q.string().optional(),sync_mode:q.boolean().optional(),resolution:q.enum(["1k","2k"]).optional(),quality:q.enum(["low","medium","high"]).optional(),user:q.string().optional()}),Tm0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4",this.maxImagesPerCall=3}get provider(){return this.config.provider}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async doGenerate({prompt:Y,n:Z,size:W,aspectRatio:z,seed:H,providerOptions:F,headers:P,abortSignal:E,files:w,mask:S}){var v,x,c,r,n,B$,_$;let A$=[];if(W!=null)A$.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});if(H!=null)A$.push({type:"unsupported",feature:"seed"});if(S!=null)A$.push({type:"unsupported",feature:"mask"});let H$=await dJ({provider:"xai",providerOptions:F,schema:_m0}),M$=w!=null&&w.length>0,b$=M$?w.map((x$)=>qA6(x$)):[],p$=M$?"/images/edits":"/images/generations",o$={model:this.modelId,prompt:Y,n:Z,response_format:"b64_json"};if(z!=null)o$.aspect_ratio=z;if((H$==null?void 0:H$.output_format)!=null)o$.output_format=H$.output_format;if((H$==null?void 0:H$.sync_mode)!=null)o$.sync_mode=H$.sync_mode;if((H$==null?void 0:H$.aspect_ratio)!=null&&z==null)o$.aspect_ratio=H$.aspect_ratio;if((H$==null?void 0:H$.resolution)!=null)o$.resolution=H$.resolution;if((H$==null?void 0:H$.quality)!=null)o$.quality=H$.quality;if((H$==null?void 0:H$.user)!=null)o$.user=H$.user;if(b$.length===1)o$.image={url:b$[0],type:"image_url"};else if(b$.length>1)o$.images=b$.map((x$)=>({url:x$,type:"image_url"}));let T6=(v=this.config.baseURL)!=null?v:"https://api.x.ai/v1",j6=(r=(c=(x=this.config._internal)==null?void 0:x.currentDate)==null?void 0:c.call(x))!=null?r:new Date,{value:Y6,responseHeaders:y$}=await W4({url:`${T6}${p$}`,headers:TJ((B$=(n=this.config).headers)==null?void 0:B$.call(n),P),body:o$,failedResponseHandler:Jq,successfulResponseHandler:Z9(Rm0),abortSignal:E,fetch:this.config.fetch});if(Y6.data.some((x$)=>x$.respect_moderation===!1))throw Error("Image generation was blocked due to a content policy violation.");return{images:Y6.data.every((x$)=>x$.b64_json!=null)?Y6.data.map((x$)=>x$.b64_json):await Promise.all(Y6.data.map((x$)=>this.downloadImage(x$.url,E))),warnings:A$,response:{timestamp:j6,modelId:this.modelId,headers:y$},providerMetadata:{xai:{images:Y6.data.map((x$)=>({...x$.revised_prompt?{revisedPrompt:x$.revised_prompt}:{}})),...((_$=Y6.usage)==null?void 0:_$.cost_in_usd_ticks)!=null?{costInUsdTicks:Y6.usage.cost_in_usd_ticks}:{}}}}}async downloadImage(Y,Z){let{value:W}=await aK({url:Y,validateUrl:!0,trustedOrigin:this.config.baseURL,abortSignal:Z,failedResponseHandler:hA6(),successfulResponseHandler:rR(),fetch:this.config.fetch});return W}},Rm0=q.object({data:q.array(q.object({url:q.string().nullish(),b64_json:q.string().nullish(),revised_prompt:q.string().nullish(),respect_moderation:q.boolean().nullish()})),usage:q.object({cost_in_usd_ticks:q.number().nullish()}).nullish()}),LM6=p0(()=>d0(q.object({id:q.string(),object:q.string().nullish(),bytes:q.number().nullish(),created_at:q.number().nullish(),filename:q.string().nullish(),purpose:q.string().nullish(),status:q.string().nullish()})));mv$=q.union([q.object({type:q.literal("url_citation"),url:q.string(),title:q.string().optional()}),q.object({type:q.string()})]),uv$=q.object({type:q.string(),text:q.string().optional(),logprobs:q.array(q.any()).optional(),annotations:q.array(mv$).optional()}),cv$=q.object({type:q.string(),text:q.string()}),tk=q.object({name:q.string().optional(),arguments:q.string().optional(),input:q.string().optional(),call_id:q.string().optional(),id:q.string(),status:q.string(),action:q.any().optional()}),Sm0=q.object({type:q.literal("url"),url:q.string()}),Cm0=q.discriminatedUnion("type",[q.object({type:q.literal("search"),query:q.string().nullish(),queries:q.array(q.string()).nullish(),sources:q.array(q.unknown()).nullish()}),q.object({type:q.literal("open_page"),url:q.string().nullish(),sources:q.array(q.unknown()).nullish()}),q.object({type:q.literal("find_in_page"),url:q.string().nullish(),pattern:q.string().nullish(),sources:q.array(q.unknown()).nullish()})]),bm0=q.object({name:q.string().optional(),arguments:q.string().optional(),output:q.string().optional(),error:q.string().optional(),id:q.string(),status:q.string(),server_label:q.string().optional()}),dv$=q.discriminatedUnion("type",[q.object({type:q.literal("web_search_call"),...tk.shape}),q.object({type:q.literal("x_search_call"),...tk.shape}),q.object({type:q.literal("code_interpreter_call"),...tk.shape}),q.object({type:q.literal("code_execution_call"),...tk.shape}),q.object({type:q.literal("view_image_call"),...tk.shape}),q.object({type:q.literal("view_x_video_call"),...tk.shape}),q.object({type:q.literal("file_search_call"),id:q.string(),status:q.string(),queries:q.array(q.string()).optional(),results:q.array(q.object({file_id:q.string(),filename:q.string(),score:q.number(),text:q.string()})).nullish()}),q.object({type:q.literal("image_generation_call"),id:q.string(),status:q.string(),prompt:q.string().nullish(),result:q.string().nullish()}),q.object({type:q.literal("custom_tool_call"),...tk.shape}),q.object({type:q.literal("mcp_call"),...bm0.shape}),q.object({type:q.literal("message"),role:q.string(),content:q.array(uv$),id:q.string(),status:q.string()}),q.object({type:q.literal("function_call"),name:q.string(),arguments:q.string(),call_id:q.string(),id:q.string()}),q.object({type:q.literal("reasoning"),id:q.string(),summary:q.array(cv$),content:q.array(q.object({type:q.string(),text:q.string()})).nullish(),status:q.string(),encrypted_content:q.string().nullish()})]),lv$=q.object({input_tokens:q.number(),output_tokens:q.number(),total_tokens:q.number().optional(),input_tokens_details:q.object({cached_tokens:q.number().optional()}).catchall(q.json()).optional(),output_tokens_details:q.object({reasoning_tokens:q.number().optional()}).catchall(q.json()).optional(),num_sources_used:q.number().optional(),num_server_side_tools_used:q.number().optional(),cost_in_usd_ticks:q.number().nullish()}).catchall(q.json()),so=q.object({id:q.string().nullish(),created_at:q.number().nullish(),model:q.string().nullish(),object:q.literal("response"),output:q.array(dv$),usage:lv$.nullish(),status:q.string(),service_tier:q.string().nullish()}),km0=q.union([q.object({type:q.literal("response.created"),response:so.partial({usage:!0,status:!0})}),q.object({type:q.literal("response.in_progress"),response:so.partial({usage:!0,status:!0})}),q.object({type:q.literal("response.output_item.added"),item:dv$,output_index:q.number()}),q.object({type:q.literal("response.output_item.done"),item:dv$,output_index:q.number()}),q.object({type:q.literal("response.content_part.added"),item_id:q.string(),output_index:q.number(),content_index:q.number(),part:uv$}),q.object({type:q.literal("response.content_part.done"),item_id:q.string(),output_index:q.number(),content_index:q.number(),part:uv$}),q.object({type:q.literal("response.output_text.delta"),item_id:q.string(),output_index:q.number(),content_index:q.number(),delta:q.string(),logprobs:q.array(q.any()).optional()}),q.object({type:q.literal("response.output_text.done"),item_id:q.string(),output_index:q.number(),content_index:q.number(),text:q.string(),logprobs:q.array(q.any()).optional(),annotations:q.array(mv$).optional()}),q.object({type:q.literal("response.output_text.annotation.added"),item_id:q.string(),output_index:q.number(),content_index:q.number(),annotation_index:q.number(),annotation:mv$}),q.object({type:q.literal("response.reasoning_summary_part.added"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),part:cv$}),q.object({type:q.literal("response.reasoning_summary_part.done"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),part:cv$}),q.object({type:q.literal("response.reasoning_summary_text.delta"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.reasoning_summary_text.done"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),text:q.string()}),q.object({type:q.literal("response.reasoning_text.delta"),item_id:q.string(),output_index:q.number(),content_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.reasoning_text.done"),item_id:q.string(),output_index:q.number(),content_index:q.number(),text:q.string()}),q.object({type:q.literal("response.web_search_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.web_search_call.searching"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.web_search_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.x_search_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.x_search_call.searching"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.x_search_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.file_search_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.file_search_call.searching"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.file_search_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.image_generation_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.image_generation_call.generating"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.image_generation_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_execution_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_execution_call.executing"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_execution_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.executing"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.interpreting"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call_code.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.code_interpreter_call_code.done"),item_id:q.string(),output_index:q.number(),code:q.string()}),q.object({type:q.literal("response.custom_tool_call_input.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.custom_tool_call_input.done"),item_id:q.string(),output_index:q.number(),input:q.string()}),q.object({type:q.literal("response.function_call_arguments.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.function_call_arguments.done"),item_id:q.string(),output_index:q.number(),arguments:q.string()}),q.object({type:q.literal("response.mcp_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call.executing"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call.failed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call_arguments.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.mcp_call_arguments.done"),item_id:q.string(),output_index:q.number(),arguments:q.string().optional()}),q.object({type:q.literal("response.mcp_call_output.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.mcp_call_output.done"),item_id:q.string(),output_index:q.number(),output:q.string().optional()}),q.object({type:q.literal("response.incomplete"),response:q.object({incomplete_details:q.object({reason:q.string()}).nullish(),usage:lv$.nullish(),service_tier:q.string().nullish()})}),q.object({type:q.literal("response.failed"),response:q.object({error:q.object({code:q.string().nullish(),message:q.string()}).nullish(),incomplete_details:q.object({reason:q.string()}).nullish(),usage:lv$.nullish()})}),q.object({type:q.literal("error"),code:q.string().nullish(),message:q.string(),param:q.string().nullish()}),q.object({type:q.literal("response.done"),response:so}),q.object({type:q.literal("response.completed"),response:so})]),xm0=q.object({reasoningEffort:q.enum(["none","low","medium","high","xhigh"]).optional(),reasoningSummary:q.enum(["auto","concise","detailed"]).optional(),logprobs:q.boolean().optional(),topLogprobs:q.number().int().min(0).max(8).optional(),serviceTier:q.enum(["default","priority"]).optional(),store:q.boolean().optional(),previousResponseId:q.string().optional(),include:q.array(q.enum(["file_search_call.results"])).nullish()}),ym0=p0(()=>d0(q.object({vectorStoreIds:q.array(q.string()),maxNumResults:q.number().optional()}))),fm0=p0(()=>d0(q.object({queries:q.array(q.string()),results:q.array(q.object({fileId:q.string(),filename:q.string(),score:q.number().min(0).max(1),text:q.string()})).nullable()}))),vm0=EX({id:"xai.file_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:fm0}),gm0=p0(()=>d0(q.object({action:q.enum(["auto","generate","edit"]).optional()}))),mm0=p0(()=>d0(q.object({}))),um0=p0(()=>d0(q.object({result:q.string(),prompt:q.string().optional()}))),cm0=EX({id:"xai.image_generation",inputSchema:mm0,outputSchema:um0}),dm0=p0(()=>d0(q.object({serverUrl:q.string().describe("The URL of the MCP server"),serverLabel:q.string().optional().describe("A label for the MCP server"),serverDescription:q.string().optional().describe("Description of the MCP server"),allowedTools:q.array(q.string()).optional().describe("List of allowed tool names"),headers:q.record(q.string(),q.string()).optional().describe("Custom headers to send"),authorization:q.string().optional().describe("Authorization header value")}))),lm0=p0(()=>d0(q.object({name:q.string(),arguments:q.string(),result:q.unknown()}))),pm0=EX({id:"xai.mcp",inputSchema:p0(()=>d0(q.object({}))),outputSchema:lm0}),im0=p0(()=>d0(q.object({allowedDomains:q.array(q.string()).max(5).optional(),excludedDomains:q.array(q.string()).max(5).optional(),enableImageSearch:q.boolean().optional(),enableImageUnderstanding:q.boolean().optional()}))),rm0=p0(()=>d0(q.object({action:q.discriminatedUnion("type",[q.object({type:q.literal("search"),query:q.string().optional(),queries:q.array(q.string()).optional()}),q.object({type:q.literal("openPage"),url:q.string().nullish()}),q.object({type:q.literal("findInPage"),url:q.string().nullish(),pattern:q.string().nullish()})]).optional(),sources:q.array(q.object({type:q.literal("url"),url:q.string()})).optional()}))),sm0=EX({id:"xai.web_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:rm0}),am0=p0(()=>d0(q.object({allowedXHandles:q.array(q.string()).max(10).optional(),excludedXHandles:q.array(q.string()).max(10).optional(),fromDate:q.string().optional(),toDate:q.string().optional(),enableImageUnderstanding:q.boolean().optional(),enableVideoUnderstanding:q.boolean().optional()}))),nm0=p0(()=>d0(q.object({query:q.string(),posts:q.array(q.object({author:q.string(),text:q.string(),url:q.string(),likes:q.number()}))}))),om0=EX({id:"xai.x_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:nm0});zM6=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/],"text/*":[/^https?:\/\/.*$/]},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,seed:w,responseFormat:S,providerOptions:v,tools:x,toolChoice:c,reasoning:r}){var n,B$,_$,A$,H$,M$,b$,p$,o$;let T6=[],j6=(n=await dJ({provider:"xai",providerOptions:v,schema:xm0}))!=null?n:{};if(H!=null)T6.push({type:"unsupported",feature:"topK"});if(F!=null)T6.push({type:"unsupported",feature:"frequencyPenalty"});if(P!=null)T6.push({type:"unsupported",feature:"presencePenalty"});if(E!=null)T6.push({type:"unsupported",feature:"stopSequences"});let Y6=(B$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.web_search"))==null?void 0:B$.name,y$=(_$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.x_search"))==null?void 0:_$.name,_6=(A$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.code_execution"))==null?void 0:A$.name,k6=(H$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.mcp"))==null?void 0:H$.name,x$=(M$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.file_search"))==null?void 0:M$.name,r0=(b$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.image_generation"))==null?void 0:b$.name,{input:m0,inputWarnings:b6}=await wm0({prompt:Y,store:(p$=j6.store)!=null?p$:!0});T6.push(...b6);let{tools:W0,toolChoice:J1,toolWarnings:D1}=await tm0({tools:x,toolChoice:c});T6.push(...D1);let Z0=j6.include?[...j6.include]:void 0;if(j6.store===!1)if(Z0==null)Z0=["reasoning.encrypted_content"];else Z0=[...Z0,"reasoning.encrypted_content"];let B1=j6.reasoningEffort;if(B1==null&&wZ(r))if(!DM6(this.modelId))T6.push({type:"unsupported",feature:"reasoning",details:`reasoning "${r}" is not supported by this model.`});else if(r==="none")B1="none";else B1=$q({reasoning:r,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:this.modelId==="grok-4.6"?"xhigh":"high"},warnings:T6});let x0={model:this.modelId,input:m0,logprobs:j6.logprobs===!0||j6.topLogprobs!=null?!0:void 0,top_logprobs:j6.topLogprobs,max_output_tokens:Z,temperature:W,top_p:z,seed:w,...(S==null?void 0:S.type)==="json"&&{text:{format:S.schema!=null?{type:"json_schema",strict:!0,name:(o$=S.name)!=null?o$:"response",description:S.description,schema:S.schema}:{type:"json_object"}}},...(B1!=null||j6.reasoningSummary!=null)&&{reasoning:{...B1!=null&&{effort:B1},...j6.reasoningSummary!=null&&{summary:j6.reasoningSummary}}},...j6.store===!1&&{store:j6.store},...Z0!=null&&{include:Z0},...j6.previousResponseId!=null&&{previous_response_id:j6.previousResponseId},...j6.serviceTier!=null&&{service_tier:j6.serviceTier}};if(W0&&W0.length>0)x0.tools=W0;if(J1!=null)x0.tool_choice=J1;return{args:x0,warnings:T6,webSearchToolName:Y6,xSearchToolName:y$,codeExecutionToolName:_6,mcpToolName:k6,fileSearchToolName:x$,imageGenerationToolName:r0}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x,c,r,n,B$,_$,A$,H$;let{args:M$,warnings:b$,webSearchToolName:p$,xSearchToolName:o$,codeExecutionToolName:T6,mcpToolName:j6,fileSearchToolName:Y6,imageGenerationToolName:y$}=await this.getArgs(Y),{responseHeaders:_6,value:k6,rawValue:x$}=await W4({url:`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/responses`,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:M$,failedResponseHandler:Jq,successfulResponseHandler:Z9(so),abortSignal:Y.abortSignal,fetch:this.config.fetch}),r0=[],m0=!1,b6=["web_search","web_search_with_snippets","browse_page"],W0=["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"];for(let J1 of k6.output){if(J1.type==="file_search_call"){let D1=Y6!=null?Y6:"file_search";r0.push({type:"tool-call",toolCallId:J1.id,toolName:D1,input:"",providerExecuted:!0}),r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,result:{queries:(H=J1.queries)!=null?H:[],results:(P=(F=J1.results)==null?void 0:F.map((Z0)=>({fileId:Z0.file_id,filename:Z0.filename,score:Z0.score,text:Z0.text})))!=null?P:null}});continue}if(J1.type==="image_generation_call"){let D1=y$!=null?y$:"image_generation";if(r0.push({type:"tool-call",toolCallId:J1.id,toolName:D1,input:"{}",providerExecuted:!0}),J1.result!=null)r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,result:{result:J1.result,...J1.prompt!=null&&{prompt:J1.prompt}}});else r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,isError:!0,result:`Image generation failed (status: ${J1.status}).`});continue}if(J1.type==="web_search_call"||J1.type==="x_search_call"||J1.type==="code_interpreter_call"||J1.type==="code_execution_call"||J1.type==="view_image_call"||J1.type==="view_x_video_call"||J1.type==="custom_tool_call"||J1.type==="mcp_call"){let D1=(E=J1.name)!=null?E:"";if(b6.includes((w=J1.name)!=null?w:"")||J1.type==="web_search_call")D1=p$!=null?p$:"web_search";else if(W0.includes((S=J1.name)!=null?S:"")||J1.type==="x_search_call")D1=o$!=null?o$:"x_search";else if(J1.name==="code_execution"||J1.type==="code_interpreter_call"||J1.type==="code_execution_call")D1=T6!=null?T6:"code_execution";else if(J1.type==="mcp_call")D1=(v=j6!=null?j6:J1.name)!=null?v:"mcp";let Z0=J1.type==="custom_tool_call"?(x=J1.input)!=null?x:"":J1.type==="mcp_call"?(c=J1.arguments)!=null?c:"":(r=J1.arguments)!=null?r:"";if(r0.push({type:"tool-call",toolCallId:J1.id,toolName:D1,input:Z0,providerExecuted:!0}),J1.type==="web_search_call")r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,result:UM6(J1.action)});continue}switch(J1.type){case"message":{for(let D1 of J1.content){if(D1.text)r0.push({type:"text",text:D1.text});if(D1.annotations){for(let Z0 of D1.annotations)if(Z0.type==="url_citation"&&"url"in Z0)r0.push({type:"source",sourceType:"url",id:this.config.generateId(),url:Z0.url,title:(n=Z0.title)!=null?n:Z0.url})}}break}case"function_call":{m0=!0,r0.push({type:"tool-call",toolCallId:J1.call_id,toolName:J1.name,input:J1.arguments});break}case"reasoning":{let Z0=(J1.summary.length>0?J1.summary.map((B1)=>B1.text):((B$=J1.content)!=null?B$:[]).map((B1)=>B1.text)).filter((B1)=>B1&&B1.length>0).join("");if(Z0||J1.encrypted_content){let B1=J1.encrypted_content||J1.id;r0.push({type:"reasoning",text:Z0,...B1&&{providerMetadata:{xai:{...J1.encrypted_content&&{reasoningEncryptedContent:J1.encrypted_content},...J1.id&&{itemId:J1.id}}}}})}break}default:break}}return{content:r0,finishReason:{unified:m0?"tool-calls":DZ$(k6.status),raw:(_$=k6.status)!=null?_$:void 0},usage:k6.usage?yv$(k6.usage):{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...(((A$=k6.usage)==null?void 0:A$.cost_in_usd_ticks)!=null||k6.service_tier!=null)&&{providerMetadata:{xai:{...((H$=k6.usage)==null?void 0:H$.cost_in_usd_ticks)!=null&&{costInUsdTicks:k6.usage.cost_in_usd_ticks},...k6.service_tier!=null&&{serviceTier:k6.service_tier}}}},request:{body:M$},response:{...ao(k6),headers:_6,body:x$},warnings:b$}}async doStream(Y){var Z,W,z;let{args:H,warnings:F,webSearchToolName:P,xSearchToolName:E,codeExecutionToolName:w,mcpToolName:S,fileSearchToolName:v,imageGenerationToolName:x}=await this.getArgs(Y),c={...H,stream:!0},{responseHeaders:r,value:n}=await W4({url:`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/responses`,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:c,failedResponseHandler:Jq,successfulResponseHandler:k2(km0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),B$={unified:"other",raw:void 0},_$=!1,A$=void 0,H$=void 0,M$=void 0,b$=!0,p$={},o$=new Set,T6={},j6={},Y6=this;return{stream:n.pipeThrough(new TransformStream({start(y$){y$.enqueue({type:"stream-start",warnings:F})},transform(y$,_6){var k6,x$,r0,m0,b6,W0,J1,D1,Z0,B1,x0,u0,G9,f1,l9,WJ,l8;if(Y.includeRawChunks)_6.enqueue({type:"raw",rawValue:y$.rawValue});if(!y$.success){_6.enqueue({type:"error",error:y$.error});return}let L1=y$.value;if(L1.type==="response.created"||L1.type==="response.in_progress"){if(b$)_6.enqueue({type:"response-metadata",...ao(L1.response)}),b$=!1;return}if(L1.type==="response.reasoning_summary_part.added"){let Q1=`reasoning-${L1.item_id}`;if(j6[L1.item_id]==null)j6[L1.item_id]={},_6.enqueue({type:"reasoning-start",id:Q1,providerMetadata:{xai:{itemId:L1.item_id}}})}if(L1.type==="response.reasoning_summary_text.delta"){let Q1=`reasoning-${L1.item_id}`;_6.enqueue({type:"reasoning-delta",id:Q1,delta:L1.delta,providerMetadata:{xai:{itemId:L1.item_id}}});return}if(L1.type==="response.reasoning_summary_text.done")return;if(L1.type==="response.reasoning_text.delta"){let Q1=`reasoning-${L1.item_id}`;if(j6[L1.item_id]==null)j6[L1.item_id]={},_6.enqueue({type:"reasoning-start",id:Q1,providerMetadata:{xai:{itemId:L1.item_id}}});_6.enqueue({type:"reasoning-delta",id:Q1,delta:L1.delta,providerMetadata:{xai:{itemId:L1.item_id}}});return}if(L1.type==="response.reasoning_text.done")return;if(L1.type==="response.output_text.delta"){let Q1=`text-${L1.item_id}`;if(p$[Q1]==null)p$[Q1]={type:"text"},_6.enqueue({type:"text-start",id:Q1});_6.enqueue({type:"text-delta",id:Q1,delta:L1.delta});return}if(L1.type==="response.output_text.done"){if(L1.annotations){for(let Q1 of L1.annotations)if(Q1.type==="url_citation"&&"url"in Q1)_6.enqueue({type:"source",sourceType:"url",id:Y6.config.generateId(),url:Q1.url,title:(k6=Q1.title)!=null?k6:Q1.url})}return}if(L1.type==="response.output_text.annotation.added"){let Q1=L1.annotation;if(Q1.type==="url_citation"&&"url"in Q1)_6.enqueue({type:"source",sourceType:"url",id:Y6.config.generateId(),url:Q1.url,title:(x$=Q1.title)!=null?x$:Q1.url});return}if(L1.type==="response.done"||L1.type==="response.completed"||L1.type==="response.incomplete"){let Q1=L1.response;if(Q1.usage)A$=yv$(Q1.usage),H$=(r0=Q1.usage.cost_in_usd_ticks)!=null?r0:void 0;if(M$=(m0=Q1.service_tier)!=null?m0:void 0,L1.type==="response.incomplete"){let SJ="incomplete_details"in Q1?(b6=Q1.incomplete_details)==null?void 0:b6.reason:void 0;B$={unified:SJ?DZ$(SJ):"other",raw:SJ!=null?SJ:"incomplete"}}else if("status"in Q1&&Q1.status)B$={unified:_$?"tool-calls":DZ$(Q1.status),raw:Q1.status};return}if(L1.type==="response.failed"){let Q1=(W0=L1.response.incomplete_details)==null?void 0:W0.reason;if(B$={unified:Q1?DZ$(Q1):"error",raw:Q1!=null?Q1:"error"},L1.response.usage)A$=yv$(L1.response.usage);if(L1.response.error!=null)_6.enqueue({type:"error",error:WM6({message:L1.response.error.message,code:L1.response.error.code,eventType:L1.type,data:L1})});return}if(L1.type==="error"){_6.enqueue({type:"error",error:WM6({message:L1.message,code:L1.code,eventType:L1.type,data:L1})});return}if(L1.type==="response.custom_tool_call_input.delta"||L1.type==="response.custom_tool_call_input.done")return;if(L1.type==="response.function_call_arguments.delta"){let Q1=T6[L1.output_index];if(Q1!=null)_6.enqueue({type:"tool-input-delta",id:Q1.toolCallId,delta:L1.delta});return}if(L1.type==="response.function_call_arguments.done")return;if(L1.type==="response.image_generation_call.in_progress"||L1.type==="response.image_generation_call.generating"||L1.type==="response.image_generation_call.completed"){if(!o$.has(L1.item_id)){o$.add(L1.item_id);let Q1=x!=null?x:"image_generation";_6.enqueue({type:"tool-input-start",id:L1.item_id,toolName:Q1}),_6.enqueue({type:"tool-input-delta",id:L1.item_id,delta:"{}"}),_6.enqueue({type:"tool-input-end",id:L1.item_id}),_6.enqueue({type:"tool-call",toolCallId:L1.item_id,toolName:Q1,input:"{}",providerExecuted:!0})}return}if(L1.type==="response.output_item.added"||L1.type==="response.output_item.done"){let Q1=L1.item;if(Q1.type==="reasoning"){if(L1.type==="response.output_item.done"){let SJ=`reasoning-${Q1.id}`;if(!(Q1.id in j6))j6[Q1.id]={},_6.enqueue({type:"reasoning-start",id:SJ,providerMetadata:{xai:{...Q1.id&&{itemId:Q1.id}}}});_6.enqueue({type:"reasoning-end",id:SJ,providerMetadata:{xai:{...Q1.encrypted_content&&{reasoningEncryptedContent:Q1.encrypted_content},...Q1.id&&{itemId:Q1.id}}}}),delete j6[Q1.id]}return}if(Q1.type==="file_search_call"){let SJ=v!=null?v:"file_search";if(!o$.has(Q1.id))o$.add(Q1.id),_6.enqueue({type:"tool-input-start",id:Q1.id,toolName:SJ}),_6.enqueue({type:"tool-input-delta",id:Q1.id,delta:""}),_6.enqueue({type:"tool-input-end",id:Q1.id}),_6.enqueue({type:"tool-call",toolCallId:Q1.id,toolName:SJ,input:"",providerExecuted:!0});if(L1.type==="response.output_item.done")_6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:SJ,result:{queries:(J1=Q1.queries)!=null?J1:[],results:(Z0=(D1=Q1.results)==null?void 0:D1.map((L6)=>({fileId:L6.file_id,filename:L6.filename,score:L6.score,text:L6.text})))!=null?Z0:null}});return}if(Q1.type==="image_generation_call"){let SJ=x!=null?x:"image_generation";if(!o$.has(Q1.id))o$.add(Q1.id),_6.enqueue({type:"tool-input-start",id:Q1.id,toolName:SJ}),_6.enqueue({type:"tool-input-delta",id:Q1.id,delta:"{}"}),_6.enqueue({type:"tool-input-end",id:Q1.id}),_6.enqueue({type:"tool-call",toolCallId:Q1.id,toolName:SJ,input:"{}",providerExecuted:!0});if(L1.type==="response.output_item.done")if(Q1.result!=null)_6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:SJ,result:{result:Q1.result,...Q1.prompt!=null&&{prompt:Q1.prompt}}});else _6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:SJ,isError:!0,result:`Image generation failed (status: ${Q1.status}).`});return}if(Q1.type==="web_search_call"||Q1.type==="x_search_call"||Q1.type==="code_interpreter_call"||Q1.type==="code_execution_call"||Q1.type==="view_image_call"||Q1.type==="view_x_video_call"||Q1.type==="custom_tool_call"||Q1.type==="mcp_call"){let SJ=["web_search","web_search_with_snippets","browse_page"],L6=["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"],s6=(B1=Q1.name)!=null?B1:"";if(SJ.includes((x0=Q1.name)!=null?x0:"")||Q1.type==="web_search_call")s6=P!=null?P:"web_search";else if(L6.includes((u0=Q1.name)!=null?u0:"")||Q1.type==="x_search_call")s6=E!=null?E:"x_search";else if(Q1.name==="code_execution"||Q1.type==="code_interpreter_call"||Q1.type==="code_execution_call")s6=w!=null?w:"code_execution";else if(Q1.type==="mcp_call")s6=(G9=S!=null?S:Q1.name)!=null?G9:"mcp";let u6=Q1.type==="custom_tool_call"?(f1=Q1.input)!=null?f1:"":Q1.type==="mcp_call"?(l9=Q1.arguments)!=null?l9:"":(WJ=Q1.arguments)!=null?WJ:"";if((Q1.type==="custom_tool_call"?L1.type==="response.output_item.done":!o$.has(Q1.id))&&!o$.has(Q1.id))o$.add(Q1.id),_6.enqueue({type:"tool-input-start",id:Q1.id,toolName:s6}),_6.enqueue({type:"tool-input-delta",id:Q1.id,delta:u6}),_6.enqueue({type:"tool-input-end",id:Q1.id}),_6.enqueue({type:"tool-call",toolCallId:Q1.id,toolName:s6,input:u6,providerExecuted:!0});if(L1.type==="response.output_item.done")_6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:s6,result:Q1.type==="web_search_call"?UM6(Q1.action):{}});return}if(Q1.type==="message")for(let SJ of Q1.content){if(SJ.text&&SJ.text.length>0){let L6=`text-${Q1.id}`;if(p$[L6]==null)p$[L6]={type:"text"},_6.enqueue({type:"text-start",id:L6}),_6.enqueue({type:"text-delta",id:L6,delta:SJ.text})}if(SJ.annotations){for(let L6 of SJ.annotations)if(L6.type==="url_citation"&&"url"in L6)_6.enqueue({type:"source",sourceType:"url",id:Y6.config.generateId(),url:L6.url,title:(l8=L6.title)!=null?l8:L6.url})}}else if(Q1.type==="function_call"){if(L1.type==="response.output_item.added")T6[L1.output_index]={toolName:Q1.name,toolCallId:Q1.call_id},_6.enqueue({type:"tool-input-start",id:Q1.call_id,toolName:Q1.name});else if(L1.type==="response.output_item.done")_$=!0,T6[L1.output_index]=void 0,_6.enqueue({type:"tool-input-end",id:Q1.call_id}),_6.enqueue({type:"tool-call",toolCallId:Q1.call_id,toolName:Q1.name,input:Q1.arguments})}}},flush(y$){for(let[_6,k6]of Object.entries(p$))if(k6.type==="text")y$.enqueue({type:"text-end",id:_6});y$.enqueue({type:"finish",finishReason:B$,usage:A$!=null?A$:{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...(H$!=null||M$!=null)&&{providerMetadata:{xai:{...H$!=null&&{costInUsdTicks:H$},...M$!=null&&{serviceTier:M$}}}}})}})),request:{body:c},response:{headers:r}}}};jM6=p0(()=>d0(q.object({batch_id:q.string(),name:q.string().nullish(),create_time:q.string().nullish(),expire_time:q.string().nullish(),cancel_time:q.string().nullish(),cancel_by_xai_message:q.string().nullish(),state:q.object({num_requests:q.number().nullish(),num_pending:q.number().nullish(),num_success:q.number().nullish(),num_error:q.number().nullish(),num_cancelled:q.number().nullish()}).nullish()}))),Ku0=q.object({code:q.union([q.string(),q.number()]).nullish(),message:q.string().nullish()}),Zu0=q.object({batch_request_id:q.string(),batch_result:q.object({response:q.object({chat_get_completion:q.unknown().nullish()}).nullish(),error:Ku0.nullish()}).nullish(),error_message:q.string().nullish()}),Gu0=p0(()=>d0(q.object({results:q.array(Zu0),pagination_token:q.string().nullish()}))),zu0=class J extends zM6{static[Y4](Y){return zM6[Y4](Y)}static[U4](Y){return new J(Y.modelId,Y.config)}constructor(Y,Z){super(Y,Z);this.batch=new Wu0({config:Z,prepareRequest:async(W)=>{let{args:z,warnings:H}=await this.getArgs(W.options);return{body:z,warnings:H}}})}experimental_doStartBatch(Y){return this.batch.startBatch(Y)}experimental_doGetBatchStatus(Y){return this.batch.getBatchStatus(Y)}experimental_doGetBatchResults(Y){return this.batch.getBatchResults(Y)}};Fu0=q.object({output:q.string().describe("the output of the code execution"),error:q.string().optional().describe("any error that occurred")}),Au0=EX({id:"xai.code_execution",inputSchema:q.object({}).describe("no input parameters"),outputSchema:Fu0}),Lu0=q.object({description:q.string().describe("description of the image"),objects:q.array(q.string()).optional().describe("objects detected in the image")}),Ou0=EX({id:"xai.view_image",inputSchema:q.object({}).describe("no input parameters"),outputSchema:Lu0}),Pu0=q.object({transcript:q.string().optional().describe("transcript of the video"),description:q.string().describe("description of the video content"),duration:q.number().optional().describe("duration in seconds")}),Mu0=EX({id:"xai.view_x_video",inputSchema:q.object({}).describe("no input parameters"),outputSchema:Pu0}),wM6={codeExecution:_M6,fileSearch:hm0,imageGeneration:OM6,mcpServer:PM6,viewImage:TM6,viewXVideo:RM6,webSearch:MM6,xSearch:NM6},Nu0=p0(()=>d0(q.looseObject({teamId:q.string().optional(),filePath:q.string().optional()}))),vv$=q.string().min(1),Eu0=q.enum(["480p","720p","1080p"]),_u0=q.enum(["edit-video","extend-video","reference-to-video"]),Tu0={pollIntervalMs:q.number().positive().nullish(),pollTimeoutMs:q.number().positive().nullish(),resolution:Eu0.nullish()},Ru0=q.looseObject({mode:_u0.optional(),videoUrl:vv$.optional(),referenceImageUrls:q.array(vv$).min(1).max(7).optional(),referenceVoiceIds:q.array(vv$).max(3).optional(),user:q.string().optional(),...Tu0}),wu0=p0(()=>d0(Ru0));Cu0={"1920x1080":"1080p","1280x720":"720p","854x480":"480p","640x480":"480p"};vu0=q.object({request_id:q.string().nullish()}),yM6=q.object({status:q.string().nullish(),video:q.object({url:q.string(),duration:q.number().nullish(),respect_moderation:q.boolean().nullish()}).nullish(),model:q.string().nullish(),usage:q.object({cost_in_usd_ticks:q.number().nullish()}).nullish(),progress:q.number().nullish(),error:q.object({code:q.string().nullish(),message:q.string().nullish()}).nullish()}),hu0=Z9(yM6),gu0=new TextDecoder;cu0=p0(()=>d0(q.object({sampleRate:q.union([q.literal(8000),q.literal(16000),q.literal(22050),q.literal(24000),q.literal(44100),q.literal(48000)]).nullish(),bitRate:q.union([q.literal(32000),q.literal(64000),q.literal(96000),q.literal(128000),q.literal(192000)]).nullish(),optimizeStreamingLatency:q.union([q.literal(0),q.literal(1),q.literal(2)]).nullish(),textNormalization:q.boolean().nullish(),withTimestamps:q.boolean().nullish(),replace:q.record(q.string(),q.string()).nullish()}))),du0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({text:Y,voice:Z="eve",outputFormat:W="mp3",instructions:z,speed:H,language:F="auto",providerOptions:P}){let E=[],w=await dJ({provider:"xai",providerOptions:P,schema:cu0}),S="mp3";if(["mp3","wav","pcm","mulaw","alaw"].includes(W))S=W;else E.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${W}. Using mp3 instead.`});if(z!=null)E.push({type:"unsupported",feature:"instructions",details:"xAI speech models do not support the `instructions` option. Use xAI speech tags in `text` to control delivery."});let v={codec:S};if((w==null?void 0:w.sampleRate)!=null)v.sample_rate=w.sampleRate;if((w==null?void 0:w.bitRate)!=null)if(S==="mp3")v.bit_rate=w.bitRate;else E.push({type:"unsupported",feature:"providerOptions",details:"xAI `bitRate` is supported only for mp3 output. It was ignored."});return{requestBody:{text:Y,voice_id:Z,language:F,output_format:v,speed:H,optimize_streaming_latency:w==null?void 0:w.optimizeStreamingLatency,text_normalization:w==null?void 0:w.textNormalization,with_timestamps:w==null?void 0:w.withTimestamps,replace:w==null?void 0:w.replace},warnings:E,withTimestamps:(w==null?void 0:w.withTimestamps)===!0}}async doGenerate(Y){var Z,W,z;let H=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{requestBody:F,warnings:P,withTimestamps:E}=await this.getArgs(Y),{value:w,responseHeaders:S,rawValue:v}=await W4({url:`${this.config.baseURL}/tts`,headers:TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers),body:F,failedResponseHandler:Jq,successfulResponseHandler:E?Z9(lu0):rR(),abortSignal:Y.abortSignal,fetch:this.config.fetch}),x,c;if(w instanceof Uint8Array)x=w;else c=w,x=c.audio!=null?BK(c.audio):new Uint8Array(0);let r=S==null?void 0:S["x-trace-id"];return{audio:x,warnings:P,request:{body:JSON.stringify(F)},response:{timestamp:H,modelId:this.modelId,headers:S,body:v},providerMetadata:{xai:{...r!=null?{traceId:r}:{},...(c==null?void 0:c.duration)!=null?{duration:c.duration}:{},...(c==null?void 0:c.content_type)!=null?{contentType:c.content_type}:{},...(c==null?void 0:c.audio_timestamps)!=null?{audioTimestamps:{graphChars:c.audio_timestamps.graph_chars,graphTimes:c.audio_timestamps.graph_times}}:{}}}}}},lu0=q.object({audio:q.string().nullish(),content_type:q.string().nullish(),duration:q.number().nullish(),audio_timestamps:q.object({graph_chars:q.array(q.string()),graph_times:q.array(q.tuple([q.number(),q.number()]))}).nullish()}),VM6=p0(()=>d0(q.object({audioFormat:q.enum(["pcm","mulaw","alaw"]).nullish(),sampleRate:q.union([q.literal(8000),q.literal(16000),q.literal(22050),q.literal(24000),q.literal(44100),q.literal(48000)]).nullish(),language:q.string().nullish(),format:q.boolean().nullish(),multichannel:q.boolean().nullish(),channels:q.number().int().min(2).max(8).nullish(),diarize:q.boolean().nullish(),keyterm:q.union([q.string(),q.array(q.string())]).nullish(),fillerWords:q.boolean().nullish(),streaming:q.object({interimResults:q.boolean().optional(),endpointing:q.number().int().min(0).max(5000).optional(),smartTurn:q.number().min(0).max(1).optional(),smartTurnTimeout:q.number().int().min(1).max(5000).optional()}).optional()}))),pu0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({audio:Y,mediaType:Z,providerOptions:W}){let z=[],H=await dJ({provider:"xai",providerOptions:W,schema:VM6}),F=new FormData,P={audio_format:H==null?void 0:H.audioFormat,sample_rate:H==null?void 0:H.sampleRate,language:H==null?void 0:H.language,format:H==null?void 0:H.format,multichannel:H==null?void 0:H.multichannel,channels:H==null?void 0:H.channels,diarize:H==null?void 0:H.diarize,filler_words:H==null?void 0:H.fillerWords};for(let[S,v]of Object.entries(P))if(v!=null)F.append(S,String(v));if((H==null?void 0:H.keyterm)!=null){let S=Array.isArray(H.keyterm)?H.keyterm:[H.keyterm];for(let v of S)F.append("keyterm",v)}let E=Y instanceof Uint8Array?new Blob([Y]):new Blob([BK(Y)]),w=lR(Z);return F.append("file",new File([E],"audio",{type:Z}),`audio.${w}`),{formData:F,warnings:z}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S;let v=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{formData:x,warnings:c}=await this.getArgs(Y),{value:r,responseHeaders:n,rawValue:B$}=await nK({url:`${(H=this.config.baseURL)!=null?H:"https://api.x.ai/v1"}/stt`,headers:TJ((P=(F=this.config).headers)==null?void 0:P.call(F),Y.headers),formData:x,failedResponseHandler:Jq,successfulResponseHandler:Z9(tu0),abortSignal:Y.abortSignal,fetch:this.config.fetch});return{text:r.text,segments:(w=(E=r.words)==null?void 0:E.map((_$)=>({text:_$.text,startSecond:_$.start,endSecond:_$.end})))!=null?w:[],language:r.language||void 0,durationInSeconds:(S=r.duration)!=null?S:void 0,warnings:c,response:{timestamp:v,modelId:this.modelId,headers:n,body:B$}}}async doStream(Y){var Z,W,z,H,F,P,E;let w=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,S=[],v=await dJ({provider:"xai",providerOptions:Y.providerOptions,schema:VM6});if((v==null?void 0:v.multichannel)===!0&&v.channels==null)throw new U7({argument:"providerOptions",message:"providerOptions.xai.channels is required when providerOptions.xai.multichannel is true"});if((v==null?void 0:v.format)!=null)S.push({type:"unsupported",feature:"providerOptions.xai.format",details:"xAI streaming transcription does not support format."});if((v==null?void 0:v.audioFormat)==null&&!su0(Y.inputAudioFormat.type))S.push({type:"other",message:`Unrecognized inputAudioFormat.type "${Y.inputAudioFormat.type}"; falling back to raw PCM encoding. Use audio/pcm, audio/pcmu, or audio/pcma, or set providerOptions.xai.audioFormat explicitly.`});let x=ru0({baseURL:(H=this.config.baseURL)!=null?H:"https://api.x.ai/v1",inputAudioFormat:Y.inputAudioFormat,providerOptions:v}),c=TJ((P=(F=this.config).headers)==null?void 0:P.call(F),Y.headers);return{request:{body:x.toString()},response:{timestamp:w,modelId:this.modelId},stream:iu0({webSocket:this.config.webSocket,url:x,headers:c,warnings:S,language:(E=v==null?void 0:v.language)!=null?E:void 0,expectedDoneCount:(v==null?void 0:v.multichannel)===!0?v.channels:1,audio:Y.audio,abortSignal:Y.abortSignal,includeRawChunks:Y.includeRawChunks})}}};tu0=q.object({text:q.string(),language:q.string().nullish(),duration:q.number().nullish(),words:q.array(q.object({text:q.string(),start:q.number(),end:q.number()})).nullish()});eu0=fM6()});var iM6={};EW(iM6,{perplexity:()=>Uc0,createPerplexity:()=>pM6,VERSION:()=>lM6});function gM6(J){var Y,Z,W;if(J==null)return mZ();let z=(Y=J.prompt_tokens)!=null?Y:0,H=(Z=J.completion_tokens)!=null?Z:0,F=(W=J.reasoning_tokens)!=null?W:0;return{inputTokens:{total:z,noCache:z,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:H+F,text:H,reasoning:F},raw:J}}function Jc0(J){let Y=[];for(let{role:Z,content:W}of J)switch(Z){case"system":{Y.push({role:"system",content:W});break}case"user":case"assistant":{let z=W.some((F)=>F.type==="file"&&C7(F.mediaType)==="image"||F.type==="file"&&C7(F.mediaType)==="application"),H=W.map((F,P)=>{switch(F.type){case"text":return{type:"text",text:F.text};case"file":switch(F.data.type){case"reference":throw new E9({functionality:"file parts with provider references"});case"text":throw new E9({functionality:"text file parts"});case"url":case"data":{let E=C7(F.mediaType);if(E==="application"){let w=hQ({part:F});if(w!=="application/pdf")throw new E9({functionality:`file part media type ${w}`});return F.data.type==="url"?{type:"file_url",file_url:{url:F.data.url.toString()},file_name:F.filename}:{type:"file_url",file_url:{url:typeof F.data.data==="string"?F.data.data:ME(F.data.data)},file_name:F.filename||`document-${P}.pdf`}}else if(E==="image")return F.data.type==="url"?{type:"image_url",image_url:{url:F.data.url.toString()}}:{type:"image_url",image_url:{url:`data:${hQ({part:F})};base64,${typeof F.data.data==="string"?F.data.data:ME(F.data.data)}`}};throw new E9({functionality:`file part media type ${F.mediaType}`})}}}}).filter(Boolean);Y.push({role:Z,content:z?H:H.filter((F)=>F.type==="text").map((F)=>F.text).join("")});break}case"tool":throw new E9({functionality:"Tool messages"});default:throw Error(`Unsupported role: ${Z}`)}return Y}function mM6(J){switch(J){case"stop":case"length":return J;default:return"other"}}function Wc0(J,Y){let Z=BK(J);if(Y==="base64_int8"){let W=new Int8Array(Z.buffer,Z.byteOffset,Z.byteLength);return Array.from(W)}return Array.from(Z)}function pM6(J={}){var Y;let Z=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"PERPLEXITY_API_KEY",description:"Perplexity"})}`,...J.headers},`ai-sdk/perplexity/${lM6}`),W=XW((Y=J.baseURL)!=null?Y:"https://api.perplexity.ai"),z=(P)=>{return new Yc0(P,{baseURL:W,headers:Z,generateId:wY,fetch:J.fetch})},H=(P)=>new Gc0(P,{provider:"perplexity.embedding",baseURL:W,headers:Z,fetch:J.fetch}),F=(P)=>z(P);return F.specificationVersion="v4",F.languageModel=z,F.embedding=H,F.embeddingModel=H,F.textEmbeddingModel=H,F.imageModel=(P)=>{throw new CW({modelId:P,modelType:"imageModel"})},F}var $c0,Xc0,Yc0,Qc0,cM6,dM6,Kc0,Zc0,iv$,uM6=(J)=>{var Y,Z;return(Z=(Y=J.error.message)!=null?Y:J.error.type)!=null?Z:"unknown error"},Gc0,zc0,lM6="4.0.34",Uc0;var rM6=n9(()=>{g4();C1();g4();C1();c8();c8();C1();c8();C1();g4();C1();c8();$c0=q.object({dimensions:q.number().int().positive().optional(),encodingFormat:q.enum(["base64_int8","base64_binary"]).optional()});Xc0=q.looseObject({search_recency_filter:q.enum(["hour","day","week","month","year"]).optional(),search_domain_filter:q.array(q.string()).optional(),search_language_filter:q.array(q.string()).optional(),search_after_date_filter:q.string().optional(),search_before_date_filter:q.string().optional(),last_updated_after_filter:q.string().optional(),last_updated_before_filter:q.string().optional(),search_mode:q.enum(["web","academic","sec"]).optional(),enable_search_classifier:q.boolean().optional(),disable_search:q.boolean().optional(),return_related_questions:q.boolean().optional(),return_images:q.boolean().optional(),image_domain_filter:q.array(q.string()).optional(),image_format_filter:q.array(q.string()).optional(),media_response:q.looseObject({overrides:q.looseObject({return_videos:q.boolean().optional()}).optional()}).optional(),stream_mode:q.enum(["full","concise"]).optional(),reasoning_effort:q.enum(["minimal","low","medium","high"]).optional(),language_preference:q.string().optional(),web_search_options:q.looseObject({search_context_size:q.enum(["low","medium","high"]).optional(),search_type:q.enum(["fast","pro","auto"]).optional(),user_location:q.looseObject({latitude:q.number().optional(),longitude:q.number().optional(),country:q.string().optional(),city:q.string().optional(),region:q.string().optional()}).optional(),image_results_enhanced_relevance:q.boolean().optional()}).optional()}),Yc0=class J{constructor(Y,Z){this.specificationVersion="v4",this.provider="perplexity",this.supportedUrls={},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,reasoning:w,responseFormat:S,seed:v,providerOptions:x}){var c;let r=[],n=(c=await dJ({provider:"perplexity",providerOptions:x,schema:Xc0}))!=null?c:{};if(H!=null)r.push({type:"unsupported",feature:"topK"});if(E!=null)r.push({type:"unsupported",feature:"stopSequences"});if(v!=null)r.push({type:"unsupported",feature:"seed"});if(wZ(w))r.push({type:"unsupported",feature:"reasoning",details:"This provider does not support reasoning configuration."});return{args:{model:this.modelId,frequency_penalty:F,max_tokens:Z,presence_penalty:P,temperature:W,top_k:H,top_p:z,response_format:(S==null?void 0:S.type)==="json"?{type:"json_schema",json_schema:{schema:S.schema}}:void 0,...n,messages:Jc0(Y)},warnings:r}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x,c,r,n;let{args:B$,warnings:_$}=await this.getArgs(Y),{responseHeaders:A$,value:H$,rawValue:M$}=await W4({url:`${this.config.baseURL}/chat/completions`,headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:B$,failedResponseHandler:b2({errorSchema:iv$,errorToMessage:uM6}),successfulResponseHandler:Z9(Kc0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),b$=H$.choices[0],p$=[],o$=b$.message.content;if(o$.length>0)p$.push({type:"text",text:o$});if(H$.citations!=null)for(let T6 of H$.citations)p$.push({type:"source",sourceType:"url",id:this.config.generateId(),url:T6});return{content:p$,finishReason:{unified:mM6(b$.finish_reason),raw:(z=b$.finish_reason)!=null?z:void 0},usage:gM6(H$.usage),request:{body:B$},response:{...RZ(H$),headers:A$,body:M$},warnings:_$,providerMetadata:{perplexity:{images:(F=(H=H$.images)==null?void 0:H.map((T6)=>({imageUrl:T6.image_url,originUrl:T6.origin_url,height:T6.height,width:T6.width})))!=null?F:null,usage:{citationTokens:(E=(P=H$.usage)==null?void 0:P.citation_tokens)!=null?E:null,numSearchQueries:(S=(w=H$.usage)==null?void 0:w.num_search_queries)!=null?S:null},cost:((v=H$.usage)==null?void 0:v.cost)?{inputTokensCost:(x=H$.usage.cost.input_tokens_cost)!=null?x:null,outputTokensCost:(c=H$.usage.cost.output_tokens_cost)!=null?c:null,requestCost:(r=H$.usage.cost.request_cost)!=null?r:null,totalCost:(n=H$.usage.cost.total_cost)!=null?n:null}:null}}}}async doStream(Y){var Z,W;let{args:z,warnings:H}=await this.getArgs(Y),F={...z,stream:!0},{responseHeaders:P,value:E}=await W4({url:`${this.config.baseURL}/chat/completions`,headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:F,failedResponseHandler:b2({errorSchema:iv$,errorToMessage:uM6}),successfulResponseHandler:k2(Zc0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),w={unified:"other",raw:void 0},S=void 0,v={perplexity:{usage:{citationTokens:null,numSearchQueries:null},cost:null,images:null}},x=!0,c=!1,r=this;return{stream:E.pipeThrough(new TransformStream({start(n){n.enqueue({type:"stream-start",warnings:H})},transform(n,B$){var _$,A$,H$,M$,b$,p$,o$;if(Y.includeRawChunks)B$.enqueue({type:"raw",rawValue:n.rawValue});if(!n.success){B$.enqueue({type:"error",error:n.error});return}let T6=n.value;if(x)B$.enqueue({type:"response-metadata",...RZ(T6)}),(_$=T6.citations)==null||_$.forEach((_6)=>{B$.enqueue({type:"source",sourceType:"url",id:r.config.generateId(),url:_6})}),x=!1;if(T6.usage!=null)S=T6.usage,v.perplexity.usage={citationTokens:(A$=T6.usage.citation_tokens)!=null?A$:null,numSearchQueries:(H$=T6.usage.num_search_queries)!=null?H$:null},v.perplexity.cost=T6.usage.cost?{inputTokensCost:(M$=T6.usage.cost.input_tokens_cost)!=null?M$:null,outputTokensCost:(b$=T6.usage.cost.output_tokens_cost)!=null?b$:null,requestCost:(p$=T6.usage.cost.request_cost)!=null?p$:null,totalCost:(o$=T6.usage.cost.total_cost)!=null?o$:null}:null;if(T6.images!=null)v.perplexity.images=T6.images.map((_6)=>({imageUrl:_6.image_url,originUrl:_6.origin_url,height:_6.height,width:_6.width}));let j6=T6.choices[0];if((j6==null?void 0:j6.finish_reason)!=null)w={unified:mM6(j6.finish_reason),raw:j6.finish_reason};if((j6==null?void 0:j6.delta)==null)return;let y$=j6.delta.content;if(y$!=null){if(!c)B$.enqueue({type:"text-start",id:"0"}),c=!0;B$.enqueue({type:"text-delta",id:"0",delta:y$})}},flush(n){if(c)n.enqueue({type:"text-end",id:"0"});n.enqueue({type:"finish",finishReason:w,usage:gM6(S),providerMetadata:v})}})),request:{body:F},response:{headers:P}}}},Qc0=q.object({input_tokens_cost:q.number().nullish(),output_tokens_cost:q.number().nullish(),request_cost:q.number().nullish(),total_cost:q.number().nullish()}),cM6=q.object({prompt_tokens:q.number(),completion_tokens:q.number(),total_tokens:q.number().nullish(),citation_tokens:q.number().nullish(),num_search_queries:q.number().nullish(),reasoning_tokens:q.number().nullish(),cost:Qc0.nullish()}),dM6=q.object({image_url:q.string(),origin_url:q.string(),height:q.number(),width:q.number()}),Kc0=q.object({id:q.string(),created:q.number(),model:q.string(),choices:q.array(q.object({message:q.object({role:q.literal("assistant"),content:q.string()}),finish_reason:q.string().nullish()})),citations:q.array(q.string()).nullish(),images:q.array(dM6).nullish(),usage:cM6.nullish()}),Zc0=q.object({id:q.string(),created:q.number(),model:q.string(),choices:q.array(q.object({delta:q.object({role:q.literal("assistant").optional(),content:q.string().nullish()}),finish_reason:q.string().nullish()})),citations:q.array(q.string()).nullish(),images:q.array(dM6).nullish(),usage:cM6.nullish()}),iv$=q.object({error:q.object({code:q.number(),message:q.string().nullish(),type:q.string().nullish()})}),Gc0=class J{constructor(Y,Z){this.specificationVersion="v4",this.maxEmbeddingsPerCall=512,this.supportsParallelCalls=!0,this.modelId=Y,this.config=Z}get provider(){return this.config.provider}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async doEmbed({values:Y,abortSignal:Z,headers:W,providerOptions:z}){var H,F,P,E,w,S;if(Y.length>this.maxEmbeddingsPerCall)throw new JM({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Y});let v=(H=await dJ({provider:"perplexity",providerOptions:z,schema:$c0}))!=null?H:{},x=(F=v.encodingFormat)!=null?F:"base64_int8",{responseHeaders:c,value:r,rawValue:n}=await W4({url:`${this.config.baseURL}/v1/embeddings`,headers:TJ(this.config.headers(),W),body:{model:this.modelId,input:Y,dimensions:v.dimensions,encoding_format:x},failedResponseHandler:b2({errorSchema:iv$,errorToMessage:(_$)=>{var A$;return(A$=_$.error.message)!=null?A$:"Unknown error"}}),successfulResponseHandler:Z9(zc0),abortSignal:Z,fetch:this.config.fetch}),B$=(P=r.usage)==null?void 0:P.cost;return{embeddings:r.data.map((_$)=>Wc0(_$.embedding,x)),usage:r.usage?{tokens:r.usage.prompt_tokens}:void 0,providerMetadata:B$?{perplexity:{cost:{inputCost:(E=B$.input_cost)!=null?E:null,totalCost:(w=B$.total_cost)!=null?w:null,currency:(S=B$.currency)!=null?S:null}}}:void 0,response:{headers:c,body:n},warnings:[]}}};zc0=q.object({data:q.array(q.object({embedding:q.string()})),usage:q.object({prompt_tokens:q.number(),cost:q.object({input_cost:q.number().nullish(),total_cost:q.number().nullish(),currency:q.string().nullish()}).nullish()}).nullish()});Uc0=pM6()});var tM6={};EW(tM6,{zai:()=>Dc0,createZai:()=>oM6,VERSION:()=>nM6});function Vc0(J){let{doSample:Y,frequency_penalty:Z,presence_penalty:W,requestId:z,seed:H,thinking:F,toolStream:P,user:E,userId:w,verbosity:S,...v}=J;return{...v,...Y!==void 0&&{do_sample:Y},...F!==void 0&&{thinking:{...F.type!==void 0&&{type:F.type},...F.clearThinking!==void 0&&{clear_thinking:F.clearThinking}}},...P!==void 0&&{tool_stream:P},...z!==void 0&&{request_id:z},...w!==void 0&&{user_id:w}}}function aM6(J){switch(J.raw){case"sensitive":return{unified:"content-filter",raw:J.raw};case"model_context_window_exceeded":return{unified:"length",raw:J.raw};case"network_error":return{unified:"error",raw:J.raw};default:return J}}function oM6(J={}){var Y;let Z=(Y=XW(J.baseURL))!=null?Y:"https://api.z.ai/api/paas/v4",W=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"ZAI_API_KEY",description:"Z.AI API key"})}`,...J.headers},`ai-sdk/zai/${nM6}`),z=(F)=>new qc0(F,{provider:"zai.chat",baseURL:Z,headers:W,fetch:J.fetch}),H=(F)=>z(F);return H.specificationVersion="v4",H.languageModel=z,H.chat=z,H.embeddingModel=(F)=>{throw new CW({modelId:F,modelType:"embeddingModel"})},H.textEmbeddingModel=H.embeddingModel,H.imageModel=(F)=>{throw new CW({modelId:F,modelType:"imageModel"})},H}var nM6="3.0.1",jc0,sM6,Bc0,Hc0,qc0,Dc0;var eM6=n9(()=>{g4();C1();KZ$();C1();c8();c8();jc0=q.object({doSample:q.boolean().optional(),thinking:q.object({type:q.enum(["enabled","disabled"]).optional(),clearThinking:q.boolean().optional()}).optional(),reasoningEffort:q.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),toolStream:q.boolean().optional(),requestId:q.string().min(6).max(64).optional(),userId:q.string().min(6).max(128).optional()}),sM6=q.object({code:q.union([q.number(),q.string()]).nullish(),message:q.string()}),Bc0=q.union([sM6,q.object({error:sM6})]),Hc0={errorSchema:Bc0,errorToMessage:(J)=>("error"in J)?J.error.message:J.message};qc0=class J extends Ju{static[Y4](Y){return a4({modelId:Y.modelId,config:Y.zaiConfig})}static[U4](Y){return new J(Y.modelId,Y.config)}constructor(Y,Z){let W=Z.headers;super(Y,{provider:Z.provider,url:({path:z})=>`${Z.baseURL}${z}`,headers:W==null?void 0:()=>typeof W==="function"?W():W,fetch:Z.fetch,errorStructure:Hc0,transformRequestBody:Vc0,supportedUrls:()=>({"image/*":[/^https?:\/\//],"video/*":[/^https?:\/\//]})});this.zaiConfig=Z}async prepareCallOptions(Y){let Z=[],W=await dJ({provider:"zai",providerOptions:Y.providerOptions,schema:jc0});if(Y.frequencyPenalty!=null)Z.push({type:"unsupported",feature:"frequencyPenalty"});if(Y.presencePenalty!=null)Z.push({type:"unsupported",feature:"presencePenalty"});if(Y.seed!=null)Z.push({type:"unsupported",feature:"seed"});let{tools:z,toolChoice:H}=Y;if((H==null?void 0:H.type)==="none")z=void 0,H=void 0;else if(H!=null&&H.type!=="auto")Z.push({type:"unsupported",feature:`toolChoice ${H.type}`,details:"Z.AI currently supports only automatic tool selection."}),H=void 0;return{normalizedOptions:{...Y,frequencyPenalty:void 0,presencePenalty:void 0,seed:void 0,tools:z,toolChoice:H,providerOptions:W==null?Y.providerOptions:{...Y.providerOptions,zai:W}},warnings:Z}}async doGenerate(Y){let{normalizedOptions:Z,warnings:W}=await this.prepareCallOptions(Y),z=await super.doGenerate(Z);return{...z,finishReason:aM6(z.finishReason),warnings:[...z.warnings,...W]}}async doStream(Y){let{normalizedOptions:Z,warnings:W}=await this.prepareCallOptions(Y),z=await super.doStream(Z);return{...z,stream:z.stream.pipeThrough(new TransformStream({transform(H,F){if(H.type==="stream-start"){F.enqueue({...H,warnings:[...H.warnings,...W]});return}if(H.type==="finish"){F.enqueue({...H,finishReason:aM6(H.finishReason)});return}F.enqueue(H)}}))}}};Dc0=oM6()});var MQ$={UNKNOWN:{code:"AX-UNKNOWN-001",title:"Unclassified Error",description:"An error occurred that hasn't been given a proper code yet. This is itself worth fixing \u2014 see the err(cause) call site that produced it.",source:"runtime",severity:"fatal"},PROMPT_NOT_FOUND:{code:"AX-PROMPT-001",title:"Prompt Not Found",description:"The requested prompt could not be resolved \u2014 it is not declared by the agent, or the published package it names ships no prompt by that name.",source:"runtime",severity:"fatal",expected:!0},PROMPT_FILE_NOT_FOUND:{code:"AX-PROMPT-002",title:"Prompt File Missing",description:"The prompt is declared but its source file no longer exists on disk.",source:"runtime",severity:"fatal",expected:!0},PROMPT_RENDER_FAILED:{code:"AX-PROMPT-003",title:"Prompt Render Failed",description:"The prompt's source file failed to compile or render \u2014 likely a malformed SFC (content outside <template>/<script>/<style>) or an error thrown while rendering. See the cause for the underlying parser/render error.",source:"runtime",severity:"fatal"},OUTPUT_INVALID:{code:"AX-OUTPUT-001",title:"Invalid Output Type",description:"The `output` type passed to request() is not valid TypeScript, or references a type that does not exist. Checked before the model is called, so no inference was spent \u2014 fix the type string at the call site.",source:"runtime",severity:"fatal"},OUTPUT_UNSATISFIED:{code:"AX-OUTPUT-002",title:"Output Type Not Satisfied",description:"The model could not produce a response matching the declared `output` type within its retry budget. The accumulated TypeScript diagnostics describe what it got wrong on each attempt.",source:"runtime",severity:"fatal"},OUTPUT_EMPTY:{code:"AX-OUTPUT-003",title:"Model Produced No Output Block",description:"Every reply must wrap its content in a <text> or <script> block \u2014 text outside a block is discarded by the parser. The model replied with none, on every attempt in its retry budget, so there was nothing to render or run. Usually means the model is not following the block protocol rather than that anything is misconfigured: the reply itself is often correct, just unwrapped. Try a different model, or check that the protocol the cognet renders matches the one it parses with.",source:"runtime",severity:"fatal",expected:!0},SCRIPT_NOT_FOUND:{code:"AX-SCRIPT-001",title:"Script Not Found",description:"The requested script was not found in the agent's blueprint. It may not be declared, or the agent needs to be re-prepared.",source:"runtime",severity:"fatal",expected:!0},SCRIPT_FILE_NOT_FOUND:{code:"AX-SCRIPT-002",title:"Script File Missing",description:"The script is declared but its source file no longer exists on disk.",source:"runtime",severity:"fatal",expected:!0},SUBAGENT_LINK_UNSUPPORTED:{code:"AX-SCRIPT-004",title:"Subagent Not Supported Over The Link",description:"An agent asked to spawn a subagent whose child runs as a confined process. `axon.request()` returns a wake's collected entries, while the link's `stimulus` verb returns only admission \u2014 the supervisor needs a verb that collects a wake and answers when it settles. Until that exists this fails rather than returning an admission receipt the caller would read as a result.",source:"runtime",severity:"fatal"},AGENT_BOOT_FAILED:{code:"AX-AGENT-006",title:"Agent Failed To Boot",description:"The agent process exited before it connected to its supervisor. Its own stderr is carried as the detail \u2014 the agent usually knows exactly what went wrong (a missing cognet, a tool that would not compile), and without this that diagnosis died in a pipe while the supervisor reported only a closed socket.",source:"runtime",severity:"fatal"},CAPSULE_NOT_LOCAL:{code:"AX-AGENT-007",title:"No Capsule On This Machine",description:'A console eval was requested against an attached deployment. Its capsule runs wherever the deployment is hosted, so there is nothing here to execute in \u2014 and quietly resolving would read as "it ran and did nothing".',source:"runtime",severity:"fatal",expected:!0},LINK_NO_HANDLER:{code:"AX-LINK-001",title:"No Handler For Link Verb",description:"The peer sent a verb this side does not implement. Both ends speak a versioned contract, so this means they disagree about it \u2014 a wiring fault, not something a user did.",source:"runtime",severity:"fatal"},LINK_PEER_CLOSED:{code:"AX-LINK-002",title:"Agent Disconnected",description:"The agent process closed its side of the link. Every call still in flight is rejected rather than left hanging \u2014 a dead peer must be an error, never a wait that never ends.",source:"runtime",severity:"fatal"},LINK_CLOSED:{code:"AX-LINK-003",title:"Link Closed",description:"The link to the agent was torn down by this side \u2014 a shutdown, a dispose, or a failed boot. Outstanding calls are rejected with this rather than hanging.",source:"runtime",severity:"fatal"},LINK_FRAME_TOO_LARGE:{code:"AX-LINK-004",title:"Link Frame Too Large",description:"A message on the link exceeded the maximum frame size, or a length prefix declared one that did. The prefix is peer-controlled input, so an oversized declaration is refused rather than allocated \u2014 a desynchronised stream cannot be recovered by reading past it.",source:"runtime",severity:"fatal"},LINK_UNKNOWN_PROMPT_ACTION:{code:"AX-LINK-005",title:"Unknown Prompt Action",description:"The prompt verb was called with an action this side does not know. Loud rather than silent: an unrecognised action would otherwise return undefined, which a caller renders as an empty prompt list.",source:"runtime",severity:"fatal"},AGENT_LINK_MISSING:{code:"AX-AGENT-001",title:"Agent Started Without A Supervisor",description:"An agent process was started with no link paths in its environment, which means nothing is supervising it. It cannot guess a socket path \u2014 doing so risks connecting to a different agent's supervisor entirely.",source:"runtime",severity:"fatal"},AGENT_LINK_MALFORMED:{code:"AX-AGENT-002",title:"Malformed Agent Link",description:"The link carrier in the agent's environment is not valid JSON, or does not name both a control and a data socket. Both are required \u2014 an agent with only one connected can accept work it has no way to answer.",source:"runtime",severity:"fatal"},AGENT_BLUEPRINT_MISSING:{code:"AX-AGENT-003",title:"Agent Started Without A Blueprint",description:"An agent process was started with no blueprint path in its environment. The supervisor writes the blueprint beside the sockets before spawning; its absence means the spawn path is broken.",source:"runtime",severity:"fatal"},AGENT_NOT_READY:{code:"AX-AGENT-004",title:"Agent Still Booting",description:"A verb arrived before the agent's runtime finished booting. The link connects first so that boot failures are reportable, which leaves a brief window where the agent can be addressed but cannot answer.",source:"runtime",severity:"fatal"},CLI_AGENT_NOT_LOCAL:{code:"AX-AGENT-005",title:"Command Needs An In-Process Agent",description:"A headless CLI command booted an agent that runs as a separate process, but the command reaches into the runtime directly. This is a wiring fault: the command needs either an in-process agent or a link verb.",source:"runtime",severity:"fatal"},ENGINE_ROLE_UNBOUND_LINK:{code:"AX-ENGINE-010",title:"No Engine For Role",description:"A confined agent asked for inference on a role the supervisor has no engine bound to. Roles are resolved on the supervisor's side before the agent starts, so an unbound one here means resolution and the cognet's declaration disagree.",source:"runtime",severity:"fatal"},ENGINE_KIND_MISMATCH_LINK:{code:"AX-ENGINE-011",title:"Engine Kind Mismatch",description:"A role bound to a transform or session engine was asked to serve a generate call. Resolution already matched the declared type, so reaching here means a provider's create() disagreed with the capability it was handed.",source:"runtime",severity:"fatal"},ENGINE_MISSING:{code:"AX-ENGINE-001",title:"No Engine Configured",description:"The agent's blueprint has no engine \u2014 it cannot dispatch to a model. Set `engine` in axon.config.ts.",source:"runtime",severity:"fatal"},ENGINE_ROLE_UNBOUND:{code:"AX-ENGINE-002",title:"Engine Role Not Bound",description:"The cognet asked for an engine role that resolution did not fill. A required role stops the boot, so reaching this means an OPTIONAL role was used without checking `kernel.engine.has()` first \u2014 or the role was never declared in the cognet's `engines:` block.",source:"runtime",severity:"fatal"},RESOURCES_EXHAUSTED:{code:"AX-RES-001",title:"Not Enough Memory",description:"A local model does not fit in what is left of this machine's video memory. Nothing was evicted: another agent is using it, and taking memory out from under a running agent would slow it down invisibly. Stop an agent that is holding a model, or raise the ceiling in your profile's `resources`.",source:"runtime",severity:"degraded",expected:!0},ENGINE_PIN_UNAVAILABLE:{code:"AX-ENGINE-004",title:"Model Not Available",description:"The agent pins a model no declared provider can supply. The agent still runs \u2014 resolution picked the best available model instead \u2014 but it is NOT the one that was asked for. Declare the provider that supplies it in your profile, or pick a model from a provider you have.",source:"runtime",severity:"degraded",expected:!0},ENGINE_REQUIREMENTS_UNMET:{code:"AX-ENGINE-003",title:"Inference Requirements Unmet",description:"This cognet declares engine roles that nothing among the user's providers can fill. Add a provider that supplies what is missing, or run a cognet whose requirements this machine meets.",source:"runtime",severity:"fatal",expected:!0},INJECT_OUTSIDE_RUNTIME:{code:"AX-RUNTIME-001",title:"Runtime Accessed Before Boot",description:"A runtime global (axon, args) was read before the runtime finished booting.",source:"runtime",severity:"fatal"},BOOT_FAILED:{code:"AX-BOOT-001",title:"Agent Failed To Start",description:"The agent's runtime crashed while starting, before it could accept requests.",source:"runtime",severity:"fatal"},BOOT_SCRIPT_FAILED:{code:"AX-BOOT-002",title:"Boot Script Failed",description:"The agent's boot.vue threw while rendering \u2014 check the script setup block for the error.",source:"runtime",severity:"fatal"},BOOT_SCRIPT_INVALID:{code:"AX-BOOT-003",title:"Boot Script Malformed",description:"The agent's boot.vue has content outside its recognized <script>/<template> blocks, or otherwise failed to parse as a valid SFC.",source:"runtime",severity:"fatal"},COGNET_ACCESSED_BEFORE_LOAD:{code:"AX-COGNET-001",title:"Cognet Accessed Before Load",description:"A cognet global (kernel, phase, system, blueprint) was read before the brain finished loading, or outside the loop body that owns it.",source:"cognet",severity:"fatal"},COGNET_LOOP_ALREADY_DECLARED:{code:"AX-COGNET-002",title:"Loop Already Declared",description:"A cognet's main() called loop() more than once \u2014 the loop is the program's entire main body and can only be declared once.",source:"cognet",severity:"fatal"},COGNET_ALREADY_LOADED:{code:"AX-COGNET-003",title:"Cognet Bound To A Different Kernel",description:"This cognet instance already loaded against a different kernel ABI \u2014 a reload produced a conflicting bind instead of a clean swap.",source:"cognet",severity:"fatal"},COGNET_NO_LOOP:{code:"AX-COGNET-004",title:"Cognet Declared No Loop",description:"The cognet's main() ran (or was woken) without ever declaring loop() \u2014 there is no program to run.",source:"cognet",severity:"fatal"},COGNET_LOAD_FAILED:{code:"AX-COGNET-016",title:"Cognet Failed To Load",description:"The cognet's own main() threw while running at load(). The brain never finished booting, so the agent has nothing to think with. The cause below is the error the cognet's code raised \u2014 it comes from the brain's source, not from Axon.",source:"cognet",severity:"fatal"},COGNET_MAX_TICKS:{code:"AX-COGNET-005",title:"Cognet Exceeded Max Ticks",description:"The cognet's loop ran more ticks in one wake than its configured limit allows \u2014 likely a runaway loop that never calls stop().",source:"cognet",severity:"fatal"},COGNET_ABI_MISMATCH:{code:"AX-COGNET-006",title:"Cognet ABI Mismatch",description:"The compiled cognet targets a kernel ABI version the running kernel doesn't provide \u2014 rebuild the cognet against the current framework version.",source:"cognet",severity:"fatal"},COGNET_MISSING:{code:"AX-COGNET-007",title:"No Compiled Cognet",description:"The blueprint points at a compiled cognet bundle that doesn't exist on disk yet \u2014 run `axon prepare` before booting.",source:"cognet",severity:"fatal"},COGNET_HASH_MISMATCH:{code:"AX-COGNET-008",title:"Cognet Bundle Hash Mismatch",description:"The compiled cognet bundle on disk doesn't match the hash the blueprint expects \u2014 it's stale or was tampered with. Run `axon prepare` again.",source:"cognet",severity:"fatal"},COGNET_INVALID:{code:"AX-COGNET-009",title:"Invalid Cognet Bundle",description:"The compiled cognet's default export isn't a real cognet definition \u2014 the compile step produced something malformed.",source:"cognet",severity:"fatal"},COGNET_IDENTITY_MISMATCH:{code:"AX-COGNET-010",title:"Cognet Identity Mismatch",description:"The compiled cognet artifact's own name doesn't match what the blueprint declared \u2014 the wrong bundle may be at this path.",source:"cognet",severity:"fatal"},COGNET_CONFIG_MISSING:{code:"AX-COGNET-011",title:"Cognet Config Missing",description:"No cognet.config.ts was found in the cognet's source directory \u2014 every cognet needs one to declare its identity.",source:"cognet",severity:"fatal"},COGNET_BUILD_FAILED:{code:"AX-COGNET-012",title:"Cognet Failed To Compile",description:"Bundling the cognet's source into a runnable artifact failed \u2014 check the build log for the underlying syntax or import error.",source:"cognet",severity:"fatal"},COGNET_RUNTIME_UNAVAILABLE:{code:"AX-COGNET-014",title:"Cognet Runtime Temporarily Unavailable",description:"The cognet runtime is declared but not present on disk \u2014 the dependency tree is mid-rewrite. Transient: the reload keeps the previous blueprint and picks the change up on the next watch event.",source:"cognet",severity:"recovered"},COGNET_AMBIGUOUS:{code:"AX-COGNET-015",title:"Two Cognets Declared",description:"The agent both declares `cognet:` in axon.config.ts and holds an inline cognet at `cognet/`. An agent has exactly one brain, and choosing between them silently would either ignore a directory of source or overrule what the author wrote. Keep one.",source:"cognet",severity:"fatal"},COGNET_NOT_FOUND:{code:"AX-COGNET-013",title:"Cognet Not Found",description:"The cognet named by `cognet:` in axon.config.ts could not be located. The detail says where it was looked for \u2014 a registry that answered 404, or a node_modules tree it was missing from. Check the specifier for a typo, and check which registry the CLI is pointed at (AXON_API_BASE).",source:"cognet",severity:"fatal",expected:!0},MODULE_SPECIFIER_INVALID:{code:"AX-PROJECT-005",title:"Invalid Module Specifier",description:"Module names must be scoped as @scope/name. The registry does not accept unscoped packages, so an unscoped specifier can never resolve.",source:"manifest",severity:"fatal"},CONFIG_MODULES_UNPARSEABLE:{code:"AX-PROJECT-006",title:"Could Not Edit axon.config.ts",description:"The install succeeded but the module entry could not be written into the config's modules array automatically \u2014 add or remove it by hand.",source:"manifest",severity:"fatal"},CONFIG_ENGINE_DEPRECATED:{code:"AX-PROJECT-033",title:"`engine:` Is Deprecated And Ignored",description:"This agent's axon.config.ts declares `engine:`, which the runtime no longer reads \u2014 inference is resolving against the profile's providers instead. Use `model: \"codex:gpt-5.6-terra\"` for a cortex pin, and `providers: [...]` for a source the user would not otherwise have.",source:"manifest",severity:"degraded"},MODULE_DEPENDENCY_INSTALL_FAILED:{code:"AX-PROJECT-004",title:"Module Dependencies Failed To Install",description:"The module source was downloaded, but its npm dependencies could not be materialized for the agent. Resolve the package-manager error and run the install again.",source:"manifest",severity:"fatal"},BLUEPRINT_NOT_LOADED:{code:"AX-PROJECT-002",title:"Blueprint Accessed Before Load",description:"Something read the blueprint's current value before load() had ever run.",source:"manifest",severity:"fatal"},AGENT_INVALID:{code:"AX-PROJECT-003",title:"Invalid Agent Directory",description:"The agent root has no package.json \u2014 every agent is a real package, this one isn't.",source:"manifest",severity:"fatal"},CORRUPT_JSON:{code:"AX-PROJECT-016",title:"Corrupt JSON File",description:"A stored JSON file failed to parse \u2014 it may have been hand-edited into an invalid state, or a write was interrupted mid-flight.",source:"manifest",severity:"fatal"},FILE_UNREADABLE:{code:"AX-PROJECT-032",title:"File Could Not Be Read",description:"A file exists but could not be read \u2014 most often a permissions problem, a directory where a file was expected, or a disk error. Distinct from a missing file, which is an ordinary absent-surface state.",source:"manifest",severity:"fatal"},PROVIDER_NOT_CONNECTED:{code:"AX-TUI-011",title:"Provider Not Connected",description:"The selected model routes through a provider (OpenRouter, Codex) that isn't connected yet \u2014 connect it before picking a model on that route.",source:"tui",severity:"fatal",expected:!0},PALETTE_INPUT_REQUIRED:{code:"AX-TUI-012",title:"Required Input Missing",description:"A palette command needs a value for this field before it can run.",source:"tui",severity:"fatal",expected:!0},BENCH_NO_CASES:{code:"AX-TUI-013",title:"Bench Declared No Cases",description:"The bench's test file ran to completion under Bun but never declared a single benchmark case.",source:"tui",severity:"fatal"},TOOL_GLOBAL_COLLISION:{code:"AX-TOOL-409",title:"Tool Global Collides With A Builtin",description:"A flattened tool export has the same name as something that already exists in the agent's global scope, and replacing it would break the code around it. Reach this member through `axon.tools.<namespace>.<member>`, rename the export, or drop `flat` so the module lands under its own namespace instead.",source:"manifest",severity:"fatal",expected:!0},SCRIPT_FAILED:{code:"AX-SCRIPT-500",title:"Script Failed",description:"A script declared by this agent was invoked and threw. The agent's own error follows \u2014 this is the script's failure, not the runtime's.",source:"runtime",severity:"fatal",expected:!0},AGENT_SERVE_NO_PORT:{code:"AX-AGENT-503",title:"No Free Port",description:"The agent tried to bind its HTTP surface and every port in the range it walked was already in use. Free one, or pass a different port with --port.",source:"runtime",severity:"fatal",expected:!0},AGENT_NOT_FOUND:{code:"AX-AGENT-404",title:"Agent Not Found",description:"No local agent goes by this name. Agent references resolve against your local pools only \u2014 watched paths first, then installed agents \u2014 and never fetch from the registry. Install it first with `axon install`.",source:"manifest",severity:"fatal",expected:!0},AGENT_AMBIGUOUS:{code:"AX-AGENT-409",title:"Ambiguous Agent Name",description:"More than one local pool holds an agent with this name, and there is no correct way to guess which was meant \u2014 pass an explicit path, or unwatch one of the roots.",source:"manifest",severity:"fatal",expected:!0},PROJECT_NOT_FOUND:{code:"AX-PROJECT-017",title:"Project Not Found",description:"No axon.config.ts, module.config.ts, cognet.config.ts, bench.config.ts, or prompt.config.ts was found at this path \u2014 it isn't a recognized project directory.",source:"manifest",severity:"fatal",expected:!0},PROJECT_WRONG_KIND:{code:"AX-PROJECT-011",title:"Wrong Project Kind",description:"This command targets one project kind, and the directory holds another \u2014 run the command that matches what is actually here.",source:"manifest",severity:"fatal",expected:!0},PROJECT_EXISTS:{code:"AX-PROJECT-018",title:"Project Already Exists",description:"Scaffolding refused to overwrite a directory that already exists \u2014 remove it or pick a different name first.",source:"manifest",severity:"fatal"},TYPEGEN_NO_BLUEPRINT:{code:"AX-PROJECT-007",title:"Typegen Needs A Loaded Blueprint",description:"Agent-kind typegen was called without a blueprint \u2014 its declared surfaces are the source of the generated types.",source:"manifest",severity:"fatal"},DEPLOY_AGENTS_ONLY:{code:"AX-PROJECT-008",title:"Only Agents Can Deploy",description:"A module was asked to deploy on its own \u2014 modules only run installed inside an agent, deploy the agent instead.",source:"manifest",severity:"fatal"},BUNDLE_IMAGE_FAILED:{code:"AX-PROJECT-039",title:"Image Build Failed",description:"`docker build` did not succeed. Its own output is above \u2014 that is the real diagnostic. Check that a Docker daemon is running, and that the base image can be pulled.",source:"manifest",severity:"fatal",expected:!0},CONFIG_IMPORT_ESCAPES_ROOT:{code:"AX-PROJECT-038",title:"Config Imports Outside The Project",description:"axon.config.ts imports a file from outside this project's directory. A bundle contains the project and nothing above it, so that file is not published with it \u2014 the agent loads locally and then fails at boot in the cloud, after provisioning has already been paid for. Move what it needs inside the project, or publish it and import it by name.",source:"manifest",severity:"fatal",expected:!0},PUBLISH_NAMESPACE_DENIED:{code:"AX-PROJECT-036",title:"That Namespace Is Not Yours",description:"Publishing writes to a scope you own. This package is named for a scope owned by someone else, or by an org you are not a member of \u2014 rename it in package.json to a scope you own, or switch to the account that owns this one.",source:"cloud",severity:"fatal",expected:!0},PUBLISH_USERNAME_REQUIRED:{code:"AX-PROJECT-037",title:"A Username Is Required",description:"A username owns your registry namespace, and nothing can be published until one is set. It is set once, on the account, and every package you publish is scoped under it.",source:"cloud",severity:"fatal",expected:!0},PUBLISH_UNSUPPORTED_KIND:{code:"AX-PROJECT-009",title:"This Project Kind Cannot Publish",description:"The registry accepts agents, modules, cognets, benches and prompts. Extensions are not accepted yet \u2014 the `registry_artifact_kind` enum needs the value first, and publishing before then would register under the wrong kind and claim the name in the shared namespace. A profile is never publishable: it holds one person's credentials, history and agents. See KINDS[kind].publishable.",source:"manifest",severity:"fatal"},MODEL_SPECIFIER_INVALID:{code:"AX-MODEL-001",title:"Malformed Model Specifier",description:"A `models:` entry in cognet.config.ts could not be parsed. The short form is `hf:owner/repo/path/to/file` \u2014 a repo alone is ambiguous, since one repo holds many weights.",source:"manifest",severity:"fatal"},MODEL_FETCH_FAILED:{code:"AX-MODEL-002",title:"Model Weights Could Not Be Fetched",description:"A declared model could not be downloaded. Check the repo, file path and revision, and that the machine can reach the registry. A brain without its weights is broken rather than degraded, so this fails at prepare instead of at first inference.",source:"manifest",severity:"fatal"},MODEL_HASH_MISMATCH:{code:"AX-MODEL-003",title:"Model Weights Failed Verification",description:"Downloaded bytes did not hash to the expected value \u2014 the upstream file changed, or the download was corrupted. Nothing is cached: storing unverified weights would make every later run trust them.",source:"manifest",severity:"fatal"},MODEL_NOT_CACHED:{code:"AX-MODEL-004",title:"Declared Model Is Not Cached",description:"`--frozen` asserts the machine is already provisioned, so it will not fetch. Run `axon prepare` without --frozen to populate the model cache.",source:"manifest",severity:"fatal"},PREPARE_FROZEN_DRIFT:{code:"AX-PROJECT-014",title:"Dependencies Drifted From The Lockfile",description:"`--frozen` asserts that package.json, the lockfile and node_modules already agree. Something did not: a dependency is missing, at a version outside its declared range, or declared but no longer selected. Run `axon prepare` without --frozen to reconcile, and commit the result.",source:"manifest",severity:"fatal"},PUBLISH_VERIFY_FAILED:{code:"AX-PROJECT-013",title:"Artifact Does Not Compile",description:"The package was built, but compiling it the way a consumer would failed \u2014 so publishing it would ship something nobody can install. Usually a file the source imports was left out of the package. Published versions are immutable, so this is caught before upload rather than after.",source:"manifest",severity:"fatal"},DEPLOY_PROVISION_FAILED:{code:"AX-PROJECT-012",title:"Deployment Provisioning Failed",description:"The agent was published, but the cloud control plane could not provision its runtime. The request ID identifies the server-side failure.",source:"manifest",severity:"fatal"},DEPLOY_RUNTIME_FAILED:{code:"AX-PROJECT-035",title:"Agent Failed To Start",description:"Cloud infrastructure was provisioned, but the agent process failed during boot. The reported runtime diagnostic identifies the immediate cause.",source:"runtime",severity:"fatal"},DEPLOY_ENV_RESERVED:{code:"AX-PROJECT-036",title:"Reserved Deployment Variable",description:"The production .env file attempts to override a variable owned by the Axon runtime or Cloud Run.",source:"manifest",severity:"fatal"},DEPLOY_ENV_INVALID:{code:"AX-PROJECT-015",title:"Invalid Deployment Variable",description:"The production .env file contains a key that is not a valid environment variable name.",source:"manifest",severity:"fatal"},BUNDLE_MODULE_COLLISION:{code:"AX-PROJECT-019",title:"Module Name Collision",description:"A hard-imported source module's name collides with an already-installed registry module of the same name.",source:"manifest",severity:"fatal"},BUNDLE_INVALID:{code:"AX-PROJECT-010",title:"Invalid Bundle Source",description:"The directory being bundled has no package.json, or its package.json has no name \u2014 every bundle needs a real package identity.",source:"manifest",severity:"fatal"},BUNDLE_TAR_MISSING:{code:"AX-PROJECT-020",title:"tar Not Found",description:"Bundling shells out to the system's tar binary, which isn't on PATH \u2014 install Git for Windows or use WSL on that platform.",source:"manifest",severity:"fatal"},BUNDLE_TAR_FAILED:{code:"AX-PROJECT-021",title:"tar Failed",description:"The tar subprocess exited non-zero while building a bundle archive.",source:"manifest",severity:"fatal"},BENCH_RUN_NOT_FOUND:{code:"AX-BENCH-001",title:"Bench Run Not Found",description:"No recorded bench run exists with this id.",source:"bench",severity:"fatal",expected:!0},BENCH_NOT_FOUND:{code:"AX-BENCH-002",title:"Bench Not Found",description:"No bench.config.ts was found at this path \u2014 it isn't a recognized bench project.",source:"bench",severity:"fatal",expected:!0},BENCH_TESTS_NOT_FOUND:{code:"AX-BENCH-003",title:"Bench Test Files Not Found",description:"The bench config declares test files that don't exist on disk.",source:"bench",severity:"fatal",expected:!0},BENCH_LOCAL_REF_NOT_FOUND:{code:"AX-BENCH-004",title:"Bench Local Reference Not Found",description:"A factor variable references a local file/directory that doesn't exist.",source:"bench",severity:"fatal",expected:!0},BENCH_CONFIG_INVALID:{code:"AX-BENCH-005",title:"Bench Config Invalid",description:"bench.config.ts failed to evaluate or didn't produce a valid bench definition.",source:"bench",severity:"fatal"},BENCH_PACKAGE_NOT_FOUND:{code:"AX-BENCH-006",title:"Bench Package Not Found",description:"No package.json exists at the bench root \u2014 every bench project needs one for identity.",source:"bench",severity:"fatal",expected:!0},BENCH_PACKAGE_NAME_REQUIRED:{code:"AX-BENCH-007",title:"Bench Package Name Required",description:"The bench's package.json has no name field.",source:"bench",severity:"fatal",expected:!0},BENCH_PACKAGE_VERSION_REQUIRED:{code:"AX-BENCH-008",title:"Bench Package Version Required",description:"The bench's package.json has no version field.",source:"bench",severity:"fatal",expected:!0},BENCH_CONTEXT_MISSING:{code:"AX-BENCH-009",title:"Bench Context Missing",description:"The benchmark preload needs AXON_BENCH_CONTEXT set \u2014 it was run outside the bench harness.",source:"bench",severity:"fatal"},BENCH_NO_ACTIVE_CASE:{code:"AX-BENCH-010",title:"No Active Bench Case",description:"A bench emission (measurement, artifact) happened outside any running Bun test \u2014 these calls must occur inside a test case.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_UNAVAILABLE:{code:"AX-BENCH-011",title:"Bench Workspace Unavailable",description:"The bench's workspace directory hasn't been materialized yet for this run.",source:"bench",severity:"fatal"},BENCH_AGENT_UNRESOLVED:{code:"AX-BENCH-012",title:"Bench Agent Unresolved",description:"The bench's declared subject agent isn't a prepared local agent \u2014 run `axon prepare` on it first.",source:"bench",severity:"fatal"},BENCH_MEASUREMENT_UNKNOWN:{code:"AX-BENCH-013",title:"Unknown Bench Measurement",description:"A measurement was emitted under an id the bench config never declared.",source:"bench",severity:"fatal"},BENCH_MEASUREMENT_TYPE:{code:"AX-BENCH-014",title:"Bench Measurement Type Mismatch",description:"A measurement's emitted value doesn't match the type its bench config declaration expects.",source:"bench",severity:"fatal"},BENCH_MEASUREMENT_DOMAIN:{code:"AX-BENCH-015",title:"Bench Measurement Out Of Domain",description:"A measurement's emitted value falls outside the range or category the bench config declares for it.",source:"bench",severity:"fatal"},BENCH_DIMENSION_UNKNOWN:{code:"AX-BENCH-016",title:"Unknown Bench Dimension",description:"A dimension value was set under an id the bench config never declared.",source:"bench",severity:"fatal"},BENCH_DIMENSION_DOMAIN:{code:"AX-BENCH-017",title:"Bench Dimension Out Of Domain",description:"A dimension's set value isn't one of the categories its bench config declares.",source:"bench",severity:"fatal"},BENCH_AXIS_UNKNOWN:{code:"AX-BENCH-018",title:"Unknown Bench Factor",description:"Something referenced a factor id the running bench's coordinate never assigned a value to.",source:"bench",severity:"fatal"},BENCH_ARTIFACT_UNKNOWN:{code:"AX-BENCH-019",title:"Unknown Bench Artifact",description:"An artifact was emitted under an id the bench config never declared.",source:"bench",severity:"fatal"},BENCH_ARTIFACT_MEDIA_TYPE:{code:"AX-BENCH-020",title:"Bench Artifact Media Type Not Allowed",description:"An artifact was emitted with a media type its bench config declaration doesn't allow.",source:"bench",severity:"fatal"},BENCH_SCHEMA_UNREADABLE:{code:"AX-BENCH-030",title:"Bench Schema Unreadable",description:"bench.config.ts could not be parsed while extracting the measurement schema.",source:"bench",severity:"fatal"},BENCH_SCHEMA_EMPTY:{code:"AX-BENCH-031",title:"Bench Schema Empty",description:"defineBench<Schema> was given a type with no properties \u2014 an empty schema and a failed extraction must never look alike.",source:"bench",severity:"fatal"},BENCH_SCHEMA_UNSUPPORTED_TYPE:{code:"AX-BENCH-032",title:"Bench Measurement Type Unsupported",description:"A measurement is not a boolean, number, union of string literals, or string.",source:"bench",severity:"fatal"},BENCH_SCHEMA_EXTRACTION_FAILED:{code:"AX-BENCH-033",title:"Bench Schema Extraction Failed",description:"The schema worker did not return a schema. Prepare fails rather than continuing with an empty one, which would silently make every measurement undeclared.",source:"bench",severity:"fatal"},BENCH_AXIS_NOT_FOUND:{code:"AX-BENCH-021",title:"Bench Axis Not Found",description:"The bench config's matrix has no axis with this key.",source:"bench",severity:"fatal",expected:!0},BENCH_AXIS_VALUE_NOT_FOUND:{code:"AX-BENCH-022",title:"Bench Axis Value Not Found",description:"The bench config's matrix axis has no declared value with this id.",source:"bench",severity:"fatal",expected:!0},BENCH_WORKSPACE_ESCAPE:{code:"AX-BENCH-023",title:"Bench Workspace Path Escapes Root",description:"A workspace source entry resolved to a path outside the workspace directory \u2014 refused rather than materialized.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_SYMLINK_UNSUPPORTED:{code:"AX-BENCH-024",title:"Bench Workspace Symlinks Unsupported",description:"A workspace source contains a symlink \u2014 not supported when materializing a bench workspace.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_OUTSIDE_ROOT:{code:"AX-BENCH-025",title:"Bench Template Outside Root",description:"A workspace template's declared source path resolves outside the bench project root.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_SOURCE_NOT_FOUND:{code:"AX-BENCH-026",title:"Bench Template Not Found",description:"A workspace template's declared source path isn't a real directory.",source:"bench",severity:"fatal",expected:!0},BENCH_LOG_INVALID:{code:"AX-BENCH-027",title:"Bench Log Invalid",description:"A bench run's event log is missing an entry its projection requires \u2014 the log is incomplete or was written out of order.",source:"bench",severity:"fatal"},TOOL_DECLARE_FAILED:{code:"AX-BLUEPRINT-002",title:"Tool Declaration Failed",description:"Compiling a src/tools/*.ts file's TypeScript declarations failed \u2014 the worker subprocess reported a compile error.",source:"manifest",severity:"fatal"},TOOL_BUNDLE_FAILED:{code:"AX-BLUEPRINT-006",title:"Tool Bundle Failed",description:"Bundling a src/tools/*.ts file to self-contained source failed \u2014 the bundler subprocess reported an error. Tools are bundled so the sandbox loads them without mounting the project; a bundle failure means the tool cannot enter the box.",source:"manifest",severity:"fatal"},ROUTE_LOAD_FAILED:{code:"AX-BLUEPRINT-007",title:"Route Load Failed",description:"A file in server/api/ could not be imported. The agent would serve an endpoint set that is not the declared one \u2014 a caller gets a 404 for a route whose file exists.",source:"manifest",severity:"fatal"},SCRIPT_LOAD_FAILED:{code:"AX-BLUEPRINT-008",title:"Script Load Failed",description:"A file in src/scripts/ could not be processed. `axon run <name>` would report the script as not found while its file sits in the project.",source:"manifest",severity:"fatal"},PLUGIN_LOAD_FAILED:{code:"AX-BLUEPRINT-009",title:"Plugin Load Failed",description:"A plugin could not be imported. Plugins wire server behaviour at boot; one silently missing means the agent runs without behaviour its author declared.",source:"manifest",severity:"fatal"},MIDDLEWARE_LOAD_FAILED:{code:"AX-BLUEPRINT-010",title:"Middleware Load Failed",description:"A middleware file could not be imported. Middleware commonly carries auth and validation, so a silently skipped one is a request path running without the checks its author wrote.",source:"manifest",severity:"fatal"},PROMPT_INTROSPECT_FAILED:{code:"AX-BLUEPRINT-011",title:"Prompt Introspection Failed",description:"A .vue prompt could not be introspected for its props. The prompt would render without the inputs it declares, or not at all.",source:"manifest",severity:"fatal"},CONFIG_NOT_FOUND:{code:"AX-BLUEPRINT-003",title:"Config Not Found",description:"No axon.config.ts exists at this path.",source:"manifest",severity:"fatal",expected:!0},CONFIG_LOAD_FAILED:{code:"AX-BLUEPRINT-004",title:"Config Failed To Load",description:"axon.config.ts threw or failed to evaluate \u2014 check the file for a syntax or runtime error.",source:"manifest",severity:"fatal"},CONFIG_INVALID:{code:"AX-BLUEPRINT-005",title:"Config Invalid",description:"axon.config.ts evaluated but never called defineAgent() \u2014 every agent config must produce one.",source:"manifest",severity:"fatal"},ENGINE_NO_DONE:{code:"AX-KERNEL-001",title:"Engine Stream Ended Without Completing",description:"The model driver's stream ended without ever emitting a completion event \u2014 the engine likely disconnected or crashed mid-response.",source:"kernel",severity:"fatal"},ENGINE_NOT_CONNECTED:{code:"AX-KERNEL-015",title:"Provider Not Connected",description:"This model's route is not connected to your account yet \u2014 run `:provider <name> connect` for the provider named below, or pick a model on a route you are already signed in to.",source:"kernel",severity:"fatal",expected:!0},ENGINE_AUTH_FAILED:{code:"AX-KERNEL-016",title:"Provider Rejected Your Credentials",description:"The provider refused the credential this agent is using \u2014 it has expired, been revoked, or is for a different account. Reconnect the provider, or pick a model on a route you are signed in to.",source:"kernel",severity:"fatal",expected:!0},ENGINE_RATE_LIMITED:{code:"AX-KERNEL-017",title:"Provider Rate Limit Reached",description:"The provider is refusing further calls right now \u2014 either too many requests in a short window, or a subscription whose allowance is spent. Waiting usually clears the first; the second needs a plan change or a different model.",source:"kernel",severity:"fatal",expected:!0},ENGINE_QUOTA_EXHAUSTED:{code:"AX-KERNEL-018",title:"Provider Credits Exhausted",description:"This route has no credit left to spend. Top it up, or switch to a model on a route that does \u2014 the conversation is intact either way.",source:"kernel",severity:"fatal",expected:!0},ENGINE_REQUEST_REJECTED:{code:"AX-KERNEL-019",title:"Provider Rejected The Request",description:"The provider refused this call as malformed or unsupported \u2014 commonly a model id it does not serve, a context window this conversation has outgrown, or a parameter that route does not accept.",source:"kernel",severity:"fatal",expected:!0},ENGINE_UNREACHABLE:{code:"AX-KERNEL-020",title:"Could Not Reach The Provider",description:"The provider could not be reached, or kept failing, across every retry \u2014 usually a network problem on this machine or an outage on their side. Nothing about this agent needs changing; try again.",source:"kernel",severity:"fatal",expected:!0},ENGINE_STREAM_FAILED:{code:"AX-KERNEL-008",title:"Engine Stream Failed",description:"The model driver's stream failed and exhausted its retries (or the failure wasn't retryable) \u2014 see context for the provider's fault code.",source:"kernel",severity:"fatal"},CODEX_NOT_CONNECTED:{code:"AX-KERNEL-012",title:"Codex Subscription Not Connected",description:"This agent uses a Codex model, but your Axon account is not connected to ChatGPT \u2014 run :provider codex connect and try again.",source:"kernel",severity:"fatal",expected:!0},RUN_IN_PROGRESS:{code:"AX-KERNEL-002",title:"A Wake Is Already Running",description:"The kernel only executes one wake at a time \u2014 a new run was requested while the previous one was still active.",source:"kernel",severity:"recovered"},RUN_RESERVATION_EXPIRED:{code:"AX-KERNEL-003",title:"Wake Reservation Expired",description:"The reserved execution slot for this wake is no longer active \u2014 it was released before the run could start.",source:"kernel",severity:"fatal"},NO_COGNET_LOADED:{code:"AX-KERNEL-004",title:"No Cognet Loaded",description:"The kernel tried to execute a wake, but the blueprint carried no cognet definition to run it against.",source:"kernel",severity:"fatal"},SYSCALL_OUTSIDE_RUN:{code:"AX-KERNEL-005",title:"Syscall Outside An Active Run",description:"A kernel syscall (engine.stream and similar) was made with no active wake to attribute it to.",source:"kernel",severity:"fatal"},CAPSULE_ACCESSED_BEFORE_BOOT:{code:"AX-KERNEL-007",title:"Capsule Accessed Before Boot",description:"Something reached for the live capsule instance before boot() had run \u2014 there is no sandbox yet to hand back.",source:"kernel",severity:"fatal"},COGNET_EMIT_FORBIDDEN:{code:"AX-KERNEL-009",title:"Cognet Emit Forbidden",description:"A cognet tried to emit an event outside the cognet:* namespace \u2014 the ABI only lets a cognet narrate its own telemetry, never forge kernel machinery events.",source:"kernel",severity:"fatal"},KNOWLEDGE_NOT_FOUND:{code:"AX-KERNEL-011",title:"Knowledge Entry Not Found",description:"A cognet read a knowledge entry that does not exist. The knowledge store is not a cache \u2014 a brain reading something the catalogue advertised has hit a real inconsistency, so this is loud rather than an empty result.",source:"kernel",severity:"fatal",expected:!0},KNOWLEDGE_READONLY:{code:"AX-KERNEL-013",title:"Knowledge Entry Is Read-Only",description:"A cognet tried to write or remove knowledge contributed by a module. Module material lives inside its own package and the next install would destroy any change \u2014 so this fails loudly rather than succeeding and vanishing later. An agent's own data/knowledge/ is writable.",source:"kernel",severity:"fatal",expected:!0},KNOWLEDGE_RECORD_FAILED:{code:"AX-KERNEL-014",title:"Knowledge Mutation Went Unrecorded",description:"A knowledge write or remove succeeded on disk, but the session record of it could not be committed. The mutation is real and already visible to the agent; only its audit trail is missing, so this is reported rather than thrown \u2014 the caller cannot undo a completed write. It matters because 'the agent rewrote its own memory' is the fact you want weeks later when behaviour drifts, and here the ledger and the filesystem disagree.",source:"kernel",severity:"degraded"},KNOWLEDGE_ESCAPE:{code:"AX-KERNEL-021",title:"Knowledge Path Escapes Store",description:"A knowledge name resolved outside the store root. Names are identifiers, not paths \u2014 traversal is refused at the boundary rather than trusted not to happen.",source:"kernel",severity:"fatal"},SCHEDULER_MODE_MISMATCH:{code:"AX-KERNEL-010",title:"Scheduler Mode Mismatch",description:"A caller used the wrong wake verb for the cognet's mode: continuous cognets advance via tick(), driven by the body's clock; invocation cognets wake on a stimulus via request()/stream().",source:"kernel",severity:"fatal"},THREAD_UNKNOWN_PARENT:{code:"AX-SESSION-001",title:"Thread Branched From Unknown Parent",description:"A thread's recorded lineage points at a parent thread id that isn't registered in this session \u2014 the session index is inconsistent.",source:"thread",severity:"fatal"},THREAD_NOT_FOUND:{code:"AX-SESSION-002",title:"Thread Not Found",description:"The requested thread id isn't registered in this session.",source:"thread",severity:"fatal",expected:!0},THREAD_BRANCH_UNKNOWN:{code:"AX-SESSION-003",title:"Cannot Branch Unknown Thread",description:"A branch was requested from a parent thread id that isn't registered in this session.",source:"thread",severity:"fatal"},SENSORY_WRITE_FAILED:{code:"AX-SESSION-004",title:"Sensory Ring Write Failed",description:"A dense sense entry (audio or visual) could not be written to the session's sensory ring \u2014 usually a full or read-only data directory. Delivery to the cognet is unaffected; the debug window for this session will have a gap.",source:"runtime",severity:"degraded"},NO_COGNET:{code:"AX-BLUEPRINT-001",title:"No Cognet Declared",description:"The blueprint carries no cognet definition \u2014 an agent cannot run without a brain. The CLI or test harness must construct and pass one.",source:"runtime",severity:"fatal"},CONTROL_PATH_NOT_FOUND:{code:"AX-CONTROL-001",title:"Control Path Not Found",description:"A control-channel call named a method the peer does not expose. The two ends disagree about the surface \u2014 usually a TUI and an extension built from different versions.",source:"server",severity:"fatal",expected:!0},CONTROL_PATH_NOT_CALLABLE:{code:"AX-CONTROL-002",title:"Control Path Not Callable",description:"A control-channel call resolved to a value on the peer's handle that is not a function.",source:"server",severity:"fatal"},CONTROL_CALL_FAILED:{code:"AX-CONTROL-003",title:"Control Call Failed",description:"The peer served a control-channel call and it threw. The remote message is carried here \u2014 the failure surfaces at the local call site rather than being returned as a falsy value.",source:"server",severity:"fatal"},CONTROL_CLOSED:{code:"AX-CONTROL-004",title:"Control Channel Closed",description:"A control-channel call was made, or was still in flight, when the channel closed. In-flight calls reject on close rather than hanging forever on an answer that is no longer coming.",source:"server",severity:"fatal"},CONTROL_UNAUTHORIZED:{code:"AX-CONTROL-005",title:"Control Handshake Rejected",description:"A connection to the control socket presented a missing or incorrect token. The token lives in the instance record, which is readable only by the owning user \u2014 a mismatch means the caller is not the local Fleet extension.",source:"server",severity:"fatal"},PLUGIN_BOOT_FAILED:{code:"AX-SERVER-001",title:"Plugin Failed During Boot",description:"A server plugin threw while running at boot \u2014 plugins are the one place in server startup where a failure must abort the boot rather than being warned and skipped.",source:"server",severity:"fatal"},HANDLE_SHUTDOWN_FAILED:{code:"AX-RUNTIME-002",title:"Handle Failed To Shut Down",description:"One of the runtime's owned handles (kernel, etc.) threw during shutdown \u2014 teardown is error-isolated, so the others still ran, but this one didn't close cleanly.",source:"runtime",severity:"fatal"},BUS_HANDLER_FAILED:{code:"AX-RUNTIME-004",title:"Bus Handler Failed",description:"A handler subscribed to a runtime bus event threw. Handler failures are non-fatal by design \u2014 the remaining handlers still run \u2014 but they are recorded rather than swallowed, since plugins and modules register handlers and a silently-broken one is invisible rot.",source:"runtime",severity:"degraded"},TOOL_CALL_FAILED:{code:"AX-RUNTIME-003",title:"Tool Call Failed",description:"An axon.tools.<namespace>.<fn>() call from script-land completed with a non-ok result from the capsule \u2014 unwrapped here into a normal throw, since script-land expects the ordinary call/throw contract, not the kernel's own stable-result shape.",source:"runtime",severity:"fatal"},CAPSULE_TOOL_TIMEOUT:{code:"AX-CAPSULE-001",title:"Tool Load Timed Out",description:"The sandbox never confirmed loading a declared tool within the timeout \u2014 it may be stuck on a slow import or the subprocess is unresponsive.",source:"capsule",severity:"fatal"},CAPSULE_TOOL_SCOPE_MISMATCH:{code:"AX-CAPSULE-002",title:"Tool Scope Mismatch",description:"A tool's declared exports don't match what it actually exported once loaded in the sandbox \u2014 the bundled source and its declaration have drifted apart.",source:"capsule",severity:"fatal"},CAPSULE_TOOL_FAILED:{code:"AX-CAPSULE-003",title:"Tool Failed To Load",description:"A declared tool failed to load into the sandbox \u2014 its source may be malformed, too large to import, or the subprocess exited before confirming.",source:"capsule",severity:"fatal"},AGENT_ENV_RESERVED:{code:"AX-CAPSULE-012",title:"Reserved Environment Variable",description:"An agent's .env sets a framework-owned variable the runtime controls (AGENT_ID, AXON_API_BASE and similar). These identify the agent to the platform, so overriding one locally would make the agent report itself as something it is not. The deploy path has always refused this; the local path now refuses it identically.",source:"capsule",severity:"fatal"},CAPSULE_NET_UNRESOLVED:{code:"AX-CAPSULE-010",title:"Network Policy Did Not Resolve",description:"A `net.allow` entry names a hostname that did not resolve to any address. Egress rules are installed as addresses, so an unresolvable name becomes no rule at all \u2014 a grant you believe you made and did not. The box refuses to boot rather than run with an allowlist quietly smaller than the one you wrote. Check the hostname, or use a literal address if the name is resolvable only from inside the box.",source:"capsule",severity:"fatal"},CAPSULE_NET_UNAVAILABLE:{code:"AX-CAPSULE-011",title:"Network Confinement Unavailable",description:"The policy declares a `net` allowlist, which needs a userspace network stack (slirp4netns) and nftables inside the box's namespace. One of them is missing on this host. Install slirp4netns and nftables, or drop the `net` block to run with no network at all \u2014 the box will not fall back to unfiltered egress.",source:"capsule",severity:"fatal"},CAPSULE_CONFINE_UNAVAILABLE:{code:"AX-CAPSULE-004",title:"OS Confinement Unavailable",description:"The policy requested OS confinement (isolation: auto) but the host is missing a required primitive (bubblewrap, systemd, nft, or the axon-agent user). Run `axon install`, or set isolation: none to opt out explicitly. The capsule refuses to boot rather than silently run unconfined.",source:"capsule",severity:"fatal"},CAPSULE_CONFINE_USER_UNRESOLVED:{code:"AX-CAPSULE-005",title:"Confinement User Unresolved",description:"The confinement user exists but its numeric uid/gid could not be read \u2014 the box cannot drop privileges without them. The host user database may be inconsistent.",source:"capsule",severity:"fatal"},CAPSULE_BOOT_FAILED:{code:"AX-CAPSULE-006",title:"Capsule Failed To Boot",description:"The sandbox subprocess exited or reported failure before completing the boot handshake. The captured stderr in the error context is the real cause \u2014 most often a confinement mount that could not be satisfied (a declared fs path that does not exist) or a runtime that could not start.",source:"capsule",severity:"fatal"},CAPSULE_BOOT_TIMEOUT:{code:"AX-CAPSULE-007",title:"Capsule Boot Timed Out",description:"The sandbox subprocess did not report ready within the boot timeout. Its captured stderr is in the error context; if empty, the subprocess may be hung rather than crashed.",source:"capsule",severity:"fatal"},CAPSULE_SPAWN_FAILED:{code:"AX-CAPSULE-008",title:"Capsule Spawn Failed",description:"The capsule subprocess command could not be spawned at all \u2014 the interpreter or confinement wrapper was not found, or PATH is unset. Check that bun (and, under confinement, bwrap/systemd-run) are on PATH.",source:"capsule",severity:"fatal"},CAPSULE_WIRE_CLOSED:{code:"AX-CAPSULE-009",title:"Capsule Wire Closed",description:"A command was sent to the sandbox after its stdin pipe was gone \u2014 the subprocess has exited or is mid-teardown. The caller is racing the capsule lifecycle.",source:"capsule",severity:"fatal"},CAPSULE_DOWN:{code:"AX-CAPSULE-010",title:"No Live Capsule",description:"An operation needed a running sandbox subprocess, but none is live \u2014 it is booting, restarting after a crash, or has been declared dead.",source:"capsule",severity:"fatal"},CAPSULE_ALREADY_BOOTED:{code:"AX-CAPSULE-011",title:"Capsule Already Booted",description:"boot() was called on a capsule that already has a live subprocess. Boot is once per lifetime; use update()/reload() to replace a running incarnation.",source:"capsule",severity:"fatal"},CAPSULE_INSTALL_FAILED:{code:"AX-CAPSULE-013",title:"Confinement Install Failed",description:"Provisioning the host for the hardened confinement tier failed \u2014 most often because creating the dedicated system user needs root. Re-run `axon install` with sufficient privilege.",source:"capsule",severity:"fatal"},CAPSULE_HOST_UNAVAILABLE:{code:"AX-CAPSULE-014",title:"Host Bridge Unavailable",description:"Sandboxed code called a host service, but this capsule was built with no host provider. Host calls require a wired host bridge on the manager side.",source:"capsule",severity:"fatal"},CAPSULE_CRASHED:{code:"AX-CAPSULE-015",title:"Capsule Crashed",description:"An unhandled error escaped inside the sandbox subprocess. The capsule reports it on the wire and exits immediately \u2014 after an unhandled throw the sandbox's state is unknown, and a capsule that keeps serving is worse than one that dies loudly.",source:"capsule",severity:"fatal"},CAPSULE_DEAD:{code:"AX-CAPSULE-016",title:"Capsule Dead",description:"The capsule subprocess is gone and supervision gave up restarting it. Every subsequent execution request fails until a new capsule is booted.",source:"capsule",severity:"fatal"},CAPSULE_PARSE_ERROR:{code:"AX-CAPSULE-017",title:"Capsule Wire Parse Error",description:"A line arriving from the sandbox was not a valid protocol event. The sandbox is speaking garbage \u2014 a protocol mismatch or corrupted output \u2014 and the line is dropped rather than acted on, never silently.",source:"capsule",severity:"degraded"},CAPSULE_CMD_FAILED:{code:"AX-CAPSULE-018",title:"Capsule Command Failed",description:"Code executed in the sandbox threw. This is the ordinary failure path for an agent-emitted block or a script-land run() \u2014 the error is the sandboxed code's own, surfaced verbatim.",source:"capsule",severity:"degraded"},CAPSULE_FN_FAILED:{code:"AX-CAPSULE-019",title:"Tool Call Threw",description:"A mediated tool function threw inside the sandbox. The failure is the tool's own; it propagates to the calling code unchanged and is recorded as the closing half of the call's span.",source:"capsule",severity:"degraded"},CAPSULE_PROC_DENIED:{code:"AX-CAPSULE-020",title:"Process Spawn Denied",description:"A process the sandbox tried to start was refused \u2014 denied by policy, killed before it could spawn, or the spawn itself failed. No process was created.",source:"capsule",severity:"degraded"},CAPSULE_PROC_FAILED:{code:"AX-CAPSULE-022",title:"Managed Process Failed",description:"A spawned child process errored without ever producing an exit code \u2014 an exec failure or a broken IPC channel. Distinct from a non-zero exit, which is the process running correctly and reporting a result.",source:"capsule",severity:"degraded"},CAPSULE_PROC_STDIN_FAILED:{code:"AX-CAPSULE-021",title:"Process Stdin Write Failed",description:"Writing to a managed child process's stdin failed \u2014 the process is no longer running, or its stdin has already closed.",source:"capsule",severity:"degraded"},NOT_BOOTED:{code:"AX-TUI-001",title:"No Agent Running",description:"A message was sent, or an action requiring a live agent was taken, before any agent finished booting.",source:"tui",severity:"fatal"},NOT_AUTHENTICATED:{code:"AX-TUI-002",title:"Not Logged In",description:"The action needs an active profile, but none is logged in yet.",source:"tui",severity:"fatal",expected:!0},PROFILE_NOT_AUTHENTICATED:{code:"AX-TUI-003",title:"Profile Has No Session",description:"The target profile exists but has no stored session \u2014 it has never logged in, or its session was cleared.",source:"tui",severity:"fatal",expected:!0},BACKEND_UNREACHABLE:{code:"AX-TUI-044",title:"Backend Unreachable",description:"A stored credential could not be verified because the backend could not be reached. The credential is NOT discarded \u2014 it may be perfectly valid \u2014 but it cannot be trusted until it is checked, so the action is refused rather than proceeding unverified.",source:"tui",severity:"fatal",expected:!0},PROFILE_UNKNOWN:{code:"AX-TUI-004",title:"Unknown Profile",description:"The requested profile id isn't one of the profiles stored on this machine.",source:"tui",severity:"fatal",expected:!0},SESSION_NOT_FOUND:{code:"AX-SESSION-005",title:"Session Not Found",description:"No session log exists at that path. A session is a .jsonl file under the agent's frame (`.agent/data/sessions/`); it may have been deleted, or belong to an agent that has since been removed.",source:"runtime",severity:"fatal",expected:!0},SESSION_UNREADABLE:{code:"AX-SESSION-006",title:"Session Log Unreadable",description:"The session log does not begin with a `session:header` line, so it cannot be forked or renamed. Either the file is truncated, or it was written by a version predating the header \u2014 an older log can still be read and resumed, just not copied.",source:"runtime",severity:"fatal",expected:!0},SESSION_ALREADY_RUNNING:{code:"AX-TUI-005",title:"Session Is Already Running",description:"spawn() was asked to resume a session that already has a live instance. Focus the running instance instead of booting a second runtime over the same log.",source:"tui",severity:"fatal",expected:!0},SESSION_NOT_RUNNING:{code:"AX-TUI-016",title:"Session Is Not Running",description:"focus() was pointed at a sessionId with no live instance behind it. Spawn (or resume) it first \u2014 focus is pure selection over running instances.",source:"tui",severity:"fatal",expected:!0},NO_ACTIVE_AGENT:{code:"AX-TUI-045",title:"No Active Agent",description:"The action needs a running agent, but none is active \u2014 start one first.",source:"tui",severity:"fatal",expected:!0},NO_LOCAL_PROJECT:{code:"AX-TUI-050",title:"No Local Project",description:"This agent has no project directory on this machine \u2014 it was attached over the network, so its source lives wherever it is running. Opening its config, or any other file verb, has to happen there. Focus a local agent instead.",source:"tui",severity:"fatal",expected:!0},NO_FOCUSED_INSTANCE:{code:"AX-TUI-017",title:"No Focused Agent Instance",description:"A module install/uninstall was requested with no running agent instance focused \u2014 spawn or focus one first.",source:"tui",severity:"fatal",expected:!0},MODEL_UNAVAILABLE:{code:"AX-TUI-051",title:"Model Not Available From Any Declared Provider",description:"The picked model was saved to the agent's config, but no provider this profile declares can supply it \u2014 so the running agent still uses its previous model. Connect the provider that serves it, or pick a model from the offered list.",source:"tui",severity:"fatal",expected:!0},MODEL_IMMUTABLE_DEPLOYED:{code:"AX-TUI-006",title:"Cannot Change A Deployment's Model",description:"A deployed agent's config lives in the cloud, not on this machine \u2014 its model is fixed at deploy time. Change it in the local project and deploy again.",source:"tui",severity:"fatal",expected:!0},MODULE_INSTALL_FAILED:{code:"AX-TUI-018",title:"Module Install Failed",description:"The registry installer returned an error for this module specifier \u2014 check the specifier and registry connectivity.",source:"tui",severity:"fatal"},NO_MODULES_INSTALLED:{code:"AX-TUI-019",title:"No Modules Installed",description:"The `:module uninstall` command was opened with no modules resolved into the focused instance's blueprint.",source:"tui",severity:"fatal"},SETTINGS_NOT_WRITABLE:{code:"AX-EXT-027",title:"Settings Cannot Be Written",description:"A settings change was requested on a store with no profile config behind it \u2014 nobody is logged in, or this Store was built without one (tests). Settings live in `profile.config.ts`, so there is nowhere to write them; the change was refused rather than saved somewhere nothing reads back.",source:"tui",severity:"fatal",expected:!0},REGISTRY_EMPTY:{code:"AX-TUI-047",title:"Nothing To Install",description:"The install palette was opened with no rows to show \u2014 the catalogue is still loading, the registry could not be reached, or everything published for that kind is already installed. The row itself says which.",source:"tui",severity:"fatal",expected:!0},NO_EXTENSIONS_INSTALLED:{code:"AX-TUI-046",title:"No Extensions Installed",description:"The `:ext uninstall` command was opened with no extensions declared in the active profile's profile.config.ts.",source:"tui",severity:"fatal",expected:!0},ATTACH_URL_REQUIRED:{code:"AX-TUI-048",title:"Attach URL Required",description:"`:attach` needs the address of a running agent \u2014 e.g. `:attach http://localhost:3010`. The agent must already be serving; attach binds to it and never boots anything.",source:"tui",severity:"fatal"},AGENT_NAME_REQUIRED:{code:"AX-CLI-001",title:"A Name Is Required",description:"Scaffolding a project needs a name \u2014 it becomes the directory and the package name.",source:"cli",severity:"fatal",expected:!0},MODULE_SPECIFIER_REQUIRED:{code:"AX-CLI-002",title:"A Module Name Is Required",description:"The command needs at least one module to act on, named as a scoped registry package.",source:"cli",severity:"fatal",expected:!0},FLAG_VALUE_REQUIRED:{code:"AX-CLI-007",title:"A Flag Is Missing Its Value",description:"The flag takes a value and none followed it. Quote the value if it contains spaces, and check it was not consumed as another flag.",source:"cli",severity:"fatal",expected:!0},RUN_INSTRUCTION_REQUIRED:{code:"AX-CLI-006",title:"Nothing To Run",description:"The agent was named but not told what to do. A reference on its own opens the terminal on that agent; giving it work needs an instruction, a declared prompt, or a script.",source:"cli",severity:"fatal",expected:!0},BENCH_RUN_ID_REQUIRED:{code:"AX-CLI-003",title:"A Run Id Is Required",description:"Reading a benchmark result needs the id of the run to read.",source:"cli",severity:"fatal",expected:!0},PROFILE_INCOMPLETE:{code:"AX-CLI-004",title:"Profile Is Missing Its Identity",description:"Credentials are stored for this profile but no identity is, so there is nothing to report. Logging out and back in rewrites both.",source:"cli",severity:"fatal",expected:!0},BUNDLE_KIND_MISMATCH:{code:"AX-CLI-005",title:"Wrong Bundle Kind",description:"The bundler produced an artifact of a different kind than the command expected. This is a wiring fault in our own code, not something a project can cause.",source:"cli",severity:"fatal"},ATTACH_UNREACHABLE:{code:"AX-TUI-045",title:"Agent Not Reachable",description:"Nothing answered at that address. The agent may not be running, may be on a different port, or may be behind something that refused the connection. `axon dev` prints the address it bound to.",source:"tui",severity:"fatal",expected:!0},ATTACH_URL_INVALID:{code:"AX-TUI-049",title:"Attach URL Invalid",description:"The address is not a usable agent URL. An agent is reached over http or https and the scheme is required \u2014 `localhost:3010` is a path, `http://localhost:3010` is an address. Checked before anything connects, so a typo fails immediately rather than as a transport error.",source:"tui",severity:"fatal"},DEPLOYMENT_NOT_CONNECTABLE:{code:"AX-TUI-028",title:"Deployment Not Connectable",description:"The deployment is not in the connectable list \u2014 it may have stopped, errored, or never finished provisioning. Refresh the deployment list and try again.",source:"tui",severity:"fatal"},SUBAGENT_REMOTE_PARENT:{code:"AX-TUI-027",title:"Cannot Spawn A Subagent From A Deployment",description:"A subagent is forked from its parent's local project, and an attached deployment has no local project here \u2014 the deployed agent runs its own subagents inside its own capsule.",source:"tui",severity:"fatal"},BASE_MODEL_INSTANCE_CONFLICT:{code:"AX-TUI-026",title:"Managed Model Instance Already Running",description:"A managed base instance is already running on a different engine. The base workspace holds one shared config, so spawning a second naked model would rewrite it underneath the live instance \u2014 close the running one first.",source:"tui",severity:"fatal"},NOT_WIRED:{code:"AX-TUI-008",title:"Not Wired Yet",description:"This surface is a declared stub \u2014 the real implementation hasn't been built yet.",source:"tui",severity:"fatal"},MIC_ALREADY_CAPTURING:{code:"AX-TUI-009",title:"Mic Already Capturing",description:"capture.start() was called while a capture was already in progress \u2014 stop the current one first.",source:"tui",severity:"fatal"},MIC_CAPTURE_UNAVAILABLE:{code:"AX-TUI-010",title:"No Audio Capture Tool Found",description:"Voice input needs one of arecord, sox, or ffmpeg installed and on PATH.",source:"tui",severity:"fatal"},MIC_FFT_SIZE_MISMATCH:{code:"AX-TUI-014",title:"FFT Sample Size Mismatch",description:"computeBuckets() was called with a sample buffer that isn't exactly config.fftSize long \u2014 an internal invariant, callers must pad/trim first.",source:"tui",severity:"fatal"},MIC_CAPTURE_FAILED:{code:"AX-TUI-015",title:"Mic Capture Failed",description:"The audio capture subprocess produced no output or exited immediately \u2014 check that a microphone is available.",source:"tui",severity:"fatal"},WATCH_PATH_REQUIRED:{code:"AX-TUI-021",title:"Watch Path Required",description:"`axon watch`/`axon unwatch` need a directory argument.",source:"tui",severity:"fatal",expected:!0},WATCH_PATH_NOT_FOUND:{code:"AX-TUI-022",title:"Watch Path Not Found",description:"`axon watch` was given a directory that doesn't exist on disk.",source:"tui",severity:"fatal",expected:!0},EDITOR_NOT_SET:{code:"AX-TUI-023",title:"No Editor Configured",description:"`axon settings` needs the $EDITOR environment variable set to know which editor to open.",source:"tui",severity:"fatal"},EDITOR_LAUNCH_FAILED:{code:"AX-TUI-024",title:"Editor Failed To Launch",description:"The command in $EDITOR could not be spawned \u2014 check that it's installed and on PATH.",source:"tui",severity:"fatal"},WATCH_AND_INIT_ARGS_REQUIRED:{code:"AX-TUI-025",title:"Directory And Name Required",description:`The init palette's "watch a new directory" entry needs both a directory path and an agent name, space-separated.`,source:"tui",severity:"fatal",expected:!0},MODULE_CONFIG_LOAD_FAILED:{code:"AX-MODULE-001",title:"Module Config Failed To Load",description:"The runtime could not import a module's module.config.ts at boot \u2014 the file is missing at its resolved path, or importing it threw. A module that cannot load contributes nothing, so boot fails rather than run a partially-wired agent.",source:"runtime",severity:"fatal"},MODULE_SOURCE_DECLARED:{code:"AX-MODULE-008",title:"Module Declared As Source",description:"Uninstall was asked to remove a module that axon.config.ts declares as an IMPORT rather than by registry name. The import statement is the author's own code, so uninstall does not rewrite it \u2014 and removing the dependency alone would leave the config importing a package that is no longer declared, with the agent still loading it. Nothing was changed: delete the import and its entry in modules: [...] by hand.",source:"cli",severity:"fatal"},MODULE_NOT_INSTALLED:{code:"AX-MODULE-003",title:"Module Not Installed",description:"A plugin asked for the options of a module this agent does not have installed \u2014 almost always a name mismatch between the plugin and the module that ships it. Reported rather than defaulted: handing back an empty options bag would let a hardware module open the wrong device and never say so.",source:"runtime",severity:"fatal"},MODULE_OPTIONS_INVALID:{code:"AX-MODULE-002",title:"Invalid Module Options",description:"The options declared for a module under modules.<name> in axon.config.ts do not satisfy the module's options schema \u2014 a required option is missing or a value has the wrong type.",source:"runtime",severity:"fatal"},MODULE_SETUP_FAILED:{code:"AX-MODULE-007",title:"Module Setup Failed",description:"A module's setup() threw during agent boot. Setup runs sequentially in blueprint order and a failure is total \u2014 no later module is wired, and the agent does not boot half-configured.",source:"runtime",severity:"fatal"},MODULE_SERVER_NOT_WIRED:{code:"AX-MODULE-004",title:"Module Server API Not Wired",description:"A module's setup() called ctx.server.addRoute/addMiddleware or ctx.tools.get, but that surface is not implemented yet. Declare routes as server/api/ files in the module instead.",source:"runtime",severity:"fatal"},MODULE_ENV_REQUIRED:{code:"AX-MODULE-005",title:"Module Env Var Missing",description:"A module's setup() called ctx.env.require() for a variable the agent's resolved environment does not provide. The module declares required env in module.config.ts; the agent must supply it (e.g. in .env).",source:"runtime",severity:"fatal",expected:!0},MODULE_POLICY_IMMUTABLE:{code:"AX-MODULE-006",title:"Module Policy Is Immutable At Boot",description:"A module's setup() called ctx.policy.update(). The resolved agent policy is authoritative and cannot be mutated at boot \u2014 declare policy needs statically in module.config.ts so the CLI reconciles them at install.",source:"runtime",severity:"fatal",expected:!0},CLONE_REF_REQUIRED:{code:"AX-PROJECT-022",title:"No Artifact Named",description:"`axon clone` was run without an artifact to clone. Name one, for example: axon clone @axon/arxiv",source:"cli",severity:"fatal",expected:!0},FORK_REF_REQUIRED:{code:"AX-PROJECT-023",title:"No Artifact Named",description:"`axon fork` was run without an artifact to fork. Name one, for example: axon fork @axon/arxiv --as @you/arxiv",source:"cli",severity:"fatal"},FORK_NAME_REQUIRED:{code:"AX-PROJECT-024",title:"Fork Needs A New Name",description:"A fork is published under your own namespace, so it needs a name: pass --as <package-name>, for example: axon fork @axon/arxiv --as @you/arxiv",source:"cli",severity:"fatal"},CLONE_TARGET_EXISTS:{code:"AX-PROJECT-025",title:"Clone Target Not Empty",description:"The directory the artifact would be cloned into already has files in it. Clone into a new directory, or clear this one first.",source:"cli",severity:"fatal"},ARTIFACT_DOWNLOAD_FAILED:{code:"AX-PROJECT-026",title:"Artifact Download Failed",description:"The registry did not serve the artifact's source archive. The version may have been unpublished, or the network request failed.",source:"cli",severity:"fatal"},ARTIFACT_EXTRACT_FAILED:{code:"AX-PROJECT-027",title:"Artifact Extract Failed",description:"The downloaded archive could not be unpacked. It may be truncated, or `tar` is unavailable on this machine.",source:"cli",severity:"fatal"},VERSION_INVALID:{code:"AX-PROJECT-028",title:"Invalid Version",description:"The project's package.json version is not valid semver, so the next version cannot be derived from it. Fix the version field by hand.",source:"cli",severity:"fatal"},FRAMEWORK_NOT_INSTALLED:{code:"AX-PROJECT-029",title:"Framework Packages Not Installed",description:"The generated type frame references @arcforge/types, @arcforge/engines and h3, none of which resolve from this project. Run `bun install` before `axon prepare`.",source:"cli",severity:"fatal"},FRAME_MIGRATION_CONFLICT:{code:"AX-PROJECT-034",title:"Frame Migration Cannot Proceed Safely",description:"Runtime output exists in BOTH the old location and the new one, so migrating would have to merge or overwrite two sets of session history. Nothing was moved. Inspect both directories and remove or merge them by hand.",source:"cli",severity:"fatal"},CONFIG_EVALUATION_ESCAPED:{code:"AX-PROJECT-030",title:"defineAgent() Called Outside Config Evaluation",description:"defineAgent() ran outside the loader that evaluates axon.config.ts \u2014 it is a declaration helper, not a runtime function, and cannot be called from application code.",source:"cli",severity:"fatal"},PROMPT_NOT_INSTALLABLE:{code:"AX-PROJECT-037",title:"Prompts Are Not Installed Into Agents",description:"A prompt is content, not a capability: it resolves from the global cache and renders on demand, so every agent can already use it without declaring anything. Installing one into an agent would put content through the code path \u2014 an ABI check, a node_modules link, an agent reload \u2014 for something that needs none of it.",source:"manifest",severity:"fatal"},ASSET_TYPE_REFUSED:{code:"AX-PROJECT-038",title:"Unsupported Asset Type",description:"A file in assets/ is not a type the registry serves. Images (png, jpg, jpeg, webp, gif) and video (mp4, webm, mov) are accepted. SVG is deliberately refused: it is an executable document that would be served from our own storage origin, so a published SVG is a script-injection surface for every visitor reading that README.",source:"manifest",severity:"fatal",expected:!0},ASSET_TOO_LARGE:{code:"AX-PROJECT-039",title:"Asset Exceeds Size Limit",description:"A single file in assets/ is over the per-asset limit. Assets exist to illustrate a README, not to distribute media \u2014 compress the file or link to it externally.",source:"manifest",severity:"fatal",expected:!0},ASSETS_BUDGET_EXCEEDED:{code:"AX-PROJECT-040",title:"Assets Exceed Total Budget",description:"The assets/ folder as a whole is over budget for one published version. Every version stores its own copy of every asset, so the total is what determines how much a package costs to host forever.",source:"manifest",severity:"fatal",expected:!0},ASSET_PATH_INVALID:{code:"AX-PROJECT-041",title:"Unsafe Asset Path",description:"An entry under assets/ is a symlink, or its name escapes the assets directory. Both are refused: a published asset must be a real file that lands where its name says it does, or extraction on the server could write outside the target directory.",source:"manifest",severity:"fatal",expected:!0},ASSET_UNREADABLE:{code:"AX-PROJECT-042",title:"Asset Could Not Be Processed",description:"A file in assets/ has an image extension but could not be decoded, so it is either corrupt or not the format its name claims. Publishing it would ship a broken image into a README.",source:"manifest",severity:"fatal",expected:!0},PORT_UNAVAILABLE:{code:"AX-PROJECT-031",title:"No Free Port",description:"Every port in the range the agent scanned is already in use. Stop whatever is holding them, or start the agent on a different port.",source:"cli",severity:"fatal"},PARENT_INSTANCE_NOT_RUNNING:{code:"AX-RUNTIME-005",title:"Parent Agent Not Running",description:"A subagent was requested against a parent session that is no longer live \u2014 the parent shut down, crashed, or was never booted by this process.",source:"runtime",severity:"fatal"},SUBAGENT_DEPTH_EXCEEDED:{code:"AX-RUNTIME-006",title:"Subagent Depth Limit Reached",description:"An agent tried to spawn a subagent beyond the maximum nesting depth. The limit exists so a recursive delegation cannot spawn processes without bound.",source:"runtime",severity:"fatal"},SUBAGENT_CHILD_LIMIT_EXCEEDED:{code:"AX-RUNTIME-007",title:"Subagent Child Limit Reached",description:"One agent tried to hold more live children than the limit allows. Existing children must finish before more can be spawned.",source:"runtime",severity:"fatal"},SUBAGENT_DESCENDANT_LIMIT_EXCEEDED:{code:"AX-RUNTIME-008",title:"Subagent Descendant Limit Reached",description:"The whole subagent tree beneath one root exceeded its live-descendant budget. The limit bounds total concurrent processes, not just direct children.",source:"runtime",severity:"fatal"},SUBAGENT_REQUEST_INVALID:{code:"AX-RUNTIME-009",title:"Malformed Subagent Request",description:"A subagent request did not carry a usable prompt. It must be an object with `prompt` as a string or an array of strings.",source:"runtime",severity:"fatal"},INSTANCE_NOT_LOCAL:{code:"AX-RUNTIME-010",title:"Agent Instance Is Not Local",description:"An operation that only works against a locally booted agent was given a remote one. Subagent spawning and the managed base workspace both require a local process.",source:"runtime",severity:"fatal"},HOST_METHOD_UNKNOWN:{code:"AX-RUNTIME-011",title:"Unknown Host Method",description:"A booted agent called a host method this platform does not implement. The agent's framework version is likely newer than the CLI running it.",source:"runtime",severity:"fatal"},UPDATE_CURRENT_VERSION_INVALID:{code:"AX-TUI-029",title:"Running Version Is Not Semver",description:"The version this app reports for itself is not valid semver, so it cannot be compared against the latest release.",source:"cli",severity:"fatal"},UPDATE_RELEASE_INVALID:{code:"AX-TUI-030",title:"Malformed Release Record",description:"The backend's release record did not describe a valid @arcforge/axon `latest` version, so there is nothing safe to update to.",source:"cli",severity:"fatal"},UPDATE_UNAVAILABLE_IN_DEVELOPMENT:{code:"AX-TUI-031",title:"Update Not Available Here",description:"Self-update needs the packaged update helper and a supervisor request path, neither of which exists in a source checkout. Update the installed app instead.",source:"cli",severity:"fatal"},UPDATE_SUPERVISOR_UNAVAILABLE:{code:"AX-TUI-032",title:"Update Supervisor Unavailable",description:"The running app has no supervisor request path, so it cannot hand an update off to be applied after exit.",source:"cli",severity:"fatal"},UPDATE_HELPER_ARGS_INVALID:{code:"AX-TUI-033",title:"Malformed Update Helper Arguments",description:"The update helper was invoked without the --from/--to/--bun/--axon/--state arguments it requires. It is spawned by the app, not run by hand.",source:"cli",severity:"fatal"},UPDATE_HELPER_VERSION_INVALID:{code:"AX-TUI-034",title:"Update Helper Given Bad Versions",description:"The update helper received a --from or --to value that is not valid semver, so it refused to install anything.",source:"cli",severity:"fatal"},TEST_FILES_NOT_FOUND:{code:"AX-TUI-035",title:"No Test Files Matched",description:"No files matched the requested test patterns, so there was nothing to run. Check the pattern, or the directory it was resolved against.",source:"cli",severity:"fatal"},OLLAMA_UNAVAILABLE:{code:"AX-TUI-037",title:"Ollama Is Not Running",description:"No Ollama daemon answered on this machine. Start it with `ollama serve`, or install Ollama from https://ollama.com to run models locally.",source:"cli",severity:"fatal"},OLLAMA_REQUEST_FAILED:{code:"AX-TUI-038",title:"Ollama Request Failed",description:"The local Ollama daemon is running but refused a request \u2014 most often an unknown model name. The daemon's own message is included.",source:"cli",severity:"fatal"},OLLAMA_REGISTRY_UNREACHABLE:{code:"AX-TUI-039",title:"Ollama Registry Unreachable",description:"Could not reach the Ollama model registry to look a model up. Downloading needs a network connection; models already on disk still work offline.",source:"cli",severity:"fatal"},NO_EDITOR_ATTACHED:{code:"AX-TUI-042",title:"No Editor Attached",description:"Opening a pane hands it to a connected editor, and none is listening. Open this project in an editor running the Axon Fleet extension \u2014 it dials each running TUI itself, so the connection appears on its own once the window is up.",source:"tui",severity:"fatal"},NO_SESSION_TO_OPEN:{code:"AX-TUI-043",title:"No Session To Open",description:"A runtime pane is a view of one conversation, and no agent is focused yet \u2014 so there is nothing to point it at. Start or focus an agent first.",source:"tui",severity:"fatal"},CLEAR_IMMUTABLE_DEPLOYED:{code:"AX-TUI-041",title:"Cannot Clear A Deployment's Conversation",description:"A deployed agent owns its own session in the cloud \u2014 the TUI attaches to whatever session it is already running, so there is no fresh one to start from here. Use `:close` to detach, or clear it on a local instance of the same agent.",source:"tui",severity:"fatal"},OLLAMA_PULL_FAILED:{code:"AX-TUI-040",title:"Model Download Failed",description:"Ollama could not finish downloading the model. The name may not exist in the registry, or the transfer was interrupted \u2014 a retry resumes from whatever was already fetched.",source:"cli",severity:"fatal"},TEST_PRELOAD_MISSING:{code:"AX-TUI-036",title:"Test API Loaded Without Its Preload",description:"The instrumented test API was imported without the preload that installs it. Tests must run through `axon test`, which wires the preload.",source:"cli",severity:"fatal"},PROFILE_CONFIG_INVALID:{code:"AX-EXT-001",title:"profile.config.ts Did Not Call defineProfile()",description:"A profile's config must default-export defineProfile({ ... }). Without it there is no extension list to read, so nothing can be installed, enabled or disabled. The rest of the profile \u2014 main.ts and plugins/ \u2014 still loads.",source:"tui",severity:"fatal",expected:!0},PROFILE_CONFIG_FAILED:{code:"AX-EXT-002",title:"profile.config.ts Failed to Load",description:"The file threw while being evaluated, so its extension list could not be read and no extensions were loaded. The profile's own main.ts and plugins/ are unaffected \u2014 a typo in an extension list must not cost you the config you already had working.",source:"tui",severity:"degraded",expected:!0},EXTENSION_ENTRY_INVALID:{code:"AX-EXT-003",title:"Malformed Extension Entry",description:'An entry in profile.config.ts\'s `extensions` array is neither a string nor an object with a `source`. Accepted forms are "@scope/name" for a registry extension and "./extensions/name" for a local one.',source:"tui",severity:"degraded",expected:!0},EXTENSION_NOT_FOUND:{code:"AX-EXT-004",title:"Extension Not Found",description:"An extension listed in profile.config.ts is not on disk. A local path may have moved or been deleted; a registry name may never have been installed. Everything else in the list still loads.",source:"tui",severity:"degraded",expected:!0},EXTENSION_INSTALL_FAILED:{code:"AX-EXT-005",title:"Extension Install Failed",description:"A registry extension could not be fetched or prepared \u2014 most often no network, or a name that does not exist in the registry. It is skipped for this session and retried on the next launch.",source:"tui",severity:"degraded",expected:!0},EXTENSION_UNINSTALL_FAILED:{code:"AX-EXT-028",title:"Extension Uninstall Failed",description:"An extension could not be removed from profile.config.ts \u2014 most often the file is unreadable or has been edited into a shape the editor cannot find the extensions list in. The extension is still declared and will load on the next launch.",source:"tui",severity:"degraded",expected:!0},EXTENSION_NOT_AN_EXTENSION:{code:"AX-EXT-006",title:"Not an Extension",description:"The directory has no extension.config.ts, which is the file that marks a directory as an extension. A path pointing at an agent, a module, or an ordinary folder is not loadable as one.",source:"tui",severity:"degraded",expected:!0},EXTENSION_LOAD_FAILED:{code:"AX-EXT-007",title:"Extension Failed to Load",description:"An extension's main.ts threw while it was being loaded, so whatever it had not yet registered is missing. Its commands, keys and palettes are removed and the rest of your config loads normally.",source:"tui",severity:"degraded",expected:!0},PROFILE_MAIN_FAILED:{code:"AX-EXT-008",title:"main.ts Failed to Load",description:"Your profile's main.ts threw while being evaluated. Anything it registered before the error survives; everything after it did not run. Plugins and extensions still load.",source:"tui",severity:"degraded",expected:!0},AGENT_NO_SUPERVISOR:{code:"AX-AGENT-030",title:"No Supervisor to Boot This Agent",description:"Something asked a platform to spawn an agent, but that platform was built without a supervisor. Supervision holds the provider credential and the session log, so it lives in the daemon rather than in whichever process happened to ask \u2014 a platform used only to read the store or publish a project does not need one, and this is where the difference surfaces.",source:"runtime",severity:"fatal",expected:!0},MODEL_RUNTIME_MISSING:{code:"AX-MODEL-031",title:"That Runtime Is Not Installed",description:"An adapter recognised the model and the library that executes it is not on this machine. Local inference runtimes are optional because they are large \u2014 ONNX Runtime alone is around 300MB of native binaries \u2014 so they are installed when first wanted rather than shipped with the CLI.",source:"daemon",severity:"fatal",expected:!0},MODEL_LOAD_FAILED:{code:"AX-MODEL-032",title:"The Model Could Not Be Loaded",description:"A runtime recognised the file and failed to read it. Distinct from an unsupported format: this weight is one this machine can execute in principle, so the file itself is the problem \u2014 truncated, corrupt, or not the model its name claims.",source:"daemon",severity:"fatal"},MODEL_WILL_NOT_FIT:{code:"AX-MODEL-033",title:"Not Enough Memory for This Model",description:"The weight loaded and did not fit within this machine's ceiling, so it was unloaded again. The refusal names what is holding the memory \u2014 a model already resident, or another process entirely, since the check measures the whole card rather than Axon's share. Nothing is evicted automatically: a silent eviction is another agent mysteriously slowing down.",source:"daemon",severity:"degraded",expected:!0},MODEL_NOT_RESIDENT:{code:"AX-MODEL-034",title:"That Model Is Not Loaded",description:"Inference was asked of a weight that is not in memory. Loading is never implicit: it is a claim on the machine's memory, and taking one a caller did not ask for would make admission invisible at the moment it matters.",source:"daemon",severity:"degraded",expected:!0},MODEL_NOT_CACHED:{code:"AX-MODEL-035",title:"That Model Is Not On This Machine",description:"A weight was asked for that has not been fetched. The daemon caches models content-addressed and machine-wide, so one download serves every agent \u2014 but it only serves what has actually been downloaded.",source:"daemon",severity:"degraded",expected:!0},MODEL_NO_SINGLE_WEIGHT:{code:"AX-MODEL-036",title:"That Repository Has No Single Weight",description:"A repository was asked for by name and publishes several weights with no obvious one to take \u2014 an encoder-decoder export ships both halves and needs both, and a quantised set is a choice about quality rather than a default. Name the file to fetch. Guessing would download half a model that fails at load with something obscure.",source:"daemon",severity:"degraded",expected:!0},MODEL_NO_RUNTIME:{code:"AX-MODEL-030",title:"No Runtime Can Execute This Model",description:"The weight is on this machine and no adapter claims it. Runtimes are registered per format \u2014 ONNX, llama.cpp \u2014 and a file none of them recognises can be fetched and cached but not loaded. Either the format needs an adapter, or the file is not the model it appears to be.",source:"daemon",severity:"fatal",expected:!0},DAEMON_NOT_RUNNING:{code:"AX-DAEMON-001",title:"The Axon Daemon Is Not Running",description:"Something asked axond for machine-wide state \u2014 what is loaded on the GPU, which agents are running \u2014 and no daemon is listening. Start it with `axon daemon up`. Local work that does not need shared state is unaffected.",source:"daemon",severity:"degraded",expected:!0},DAEMON_ALREADY_RUNNING:{code:"AX-DAEMON-002",title:"A Daemon Is Already Running",description:"A second axond was asked to start while one is already listening on this socket. One daemon per user per machine is the whole point \u2014 two would each believe they owned the GPU. Nothing was started; the existing one is untouched.",source:"daemon",severity:"degraded",expected:!0},DAEMON_SOCKET_UNAVAILABLE:{code:"AX-DAEMON-003",title:"Could Not Bind the Daemon Socket",description:"axond could not listen on its unix socket. Usually a stale socket file left by a process killed with -9, which the daemon removes on start; if it persists, the path may be unwritable or on a filesystem that does not support unix sockets.",source:"daemon",severity:"fatal"},DAEMON_START_FAILED:{code:"AX-DAEMON-004",title:"The Daemon Failed to Start",description:"axond was spawned but never reported itself ready. Its output is in the daemon log named by the detail; the usual causes are a port or socket conflict and a broken profile config.",source:"daemon",severity:"fatal"},DAEMON_NOT_WIRED:{code:"AX-DAEMON-005",title:"That Part of the Daemon Is Not Built Yet",description:"A domain the daemon declares exists but is not implemented. It throws rather than answering, because a stub returning an empty list is indistinguishable from a real answer and gets built on top of.",source:"daemon",severity:"degraded",expected:!0},EXTENSION_LOAD_TIMEOUT:{code:"AX-EXT-034",title:"Extension Took Too Long to Load",description:"A config file did not finish evaluating within the load budget \u2014 usually a blocking loop or a synchronous wait at module scope. Loading continued without it, so its commands, keys and palettes are missing; everything else in your config still loaded. The file itself keeps running until it finishes, because there is no safe way to interrupt code mid-execution.",source:"tui",severity:"degraded",expected:!0},PLUGIN_FAILED:{code:"AX-EXT-009",title:"Plugin Failed to Load",description:"A file in plugins/ threw while being imported, so its hooks were not registered. Other plugins in the same folder are unaffected \u2014 each file is loaded independently.",source:"tui",severity:"degraded",expected:!0},HOOK_FAILED:{code:"AX-EXT-010",title:"Lifecycle Hook Failed",description:"A tui.hook() handler threw while the event it listens for was firing. For a notification hook nothing else is affected; for a gating hook (tui:boot, tui:shutdown) the operation continues anyway rather than leaving the terminal stuck.",source:"tui",severity:"degraded",expected:!0},HOOK_TIMED_OUT:{code:"AX-EXT-011",title:"Hook Blocked Too Long",description:"A gating hook (tui:boot or tui:shutdown) did not finish within its budget, so the TUI continued without waiting. A config must never be able to hang the terminal silently \u2014 whatever the handler was doing may not have completed.",source:"tui",severity:"degraded",expected:!0},COMMAND_NOT_FOUND:{code:"AX-EXT-012",title:"No Such Command",description:"commands.run() was given a path that resolves to nothing in the command tree. The path must name a leaf, spelled exactly as it appears in the `:` palette.",source:"tui",severity:"fatal",expected:!0},PALETTE_NOT_FOUND:{code:"AX-EXT-013",title:"No Such Palette",description:"palette.open() was given a name no palette was registered under. Palettes are created with palette.create(name, ...) \u2014 a name is only openable once its registration has run.",source:"tui",severity:"fatal",expected:!0},PALETTE_NAME_TAKEN:{code:"AX-EXT-014",title:"Palette Name Already Registered",description:"Two palettes tried to claim the same name. Names are how palette.open() addresses one, so they have to be unique \u2014 silently replacing the first would make whichever loaded last win, invisibly.",source:"tui",severity:"degraded",expected:!0},PALETTE_ALREADY_OPEN:{code:"AX-EXT-015",title:"A Palette Is Already Open",description:"Something tried to open a palette, or ask a question, while the user was already navigating one. Stealing it mid-navigation would drop whatever they were doing, so the call fails instead \u2014 check palette.isOpen first.",source:"tui",severity:"degraded",expected:!0},KEY_CHORD_UNBOUND:{code:"AX-EXT-022",title:"No Such Key Binding",description:"keys.send() was given a chord nothing is bound to \u2014 neither a mode key nor a registered binding. Sending it would do nothing at all, which is indistinguishable from a binding that ran and had no effect.",source:"tui",severity:"fatal",expected:!0},AGENT_SPAWN_NO_INSTANCE:{code:"AX-EXT-023",title:"Agent Started but No Instance Appeared",description:"A spawn reported success without producing a focused instance, so there is no id to hand back. This is a fault in Axon rather than in your config \u2014 the agent may or may not be running.",source:"tui",severity:"fatal"},PROFILE_CONFIG_MISSING:{code:"AX-EXT-025",title:"No profile.config.ts",description:"The profile has no config file to record the extension in. It is normally created on first launch \u2014 starting Axon once will scaffold it.",source:"tui",severity:"fatal",expected:!0},PROFILE_CONFIG_UNEDITABLE:{code:"AX-EXT-026",title:"profile.config.ts Could Not Be Edited",description:"The `defineProfile({ ... })` call could not be located, or editing it would have produced invalid TypeScript. Nothing was written \u2014 this file is yours, and a botched edit costs your whole TUI config. Add or remove the entry by hand.",source:"tui",severity:"fatal",expected:!0},COMMAND_INVALID:{code:"AX-EXT-029",title:"Command Is Not Registerable",description:"A command was registered with no path, or with no `run` to call. Both are caught here rather than when someone presses Enter on it \u2014 a command that registers cleanly and then does nothing reads as a broken terminal instead of a config mistake, and gives no clue which file to open. Use `commands.register(path, fn)` or `commands.register(path, { run })`.",source:"tui",severity:"degraded",expected:!0},COMPONENT_NAME_TAKEN:{code:"AX-EXT-030",title:"Component Already Registered",description:"Two sources registered the same line component name. The first one loaded keeps it \u2014 your own config beats any extension. A silently shadowed component would render someone else's value under your name, so the second registration fails instead. Component names are `provider:name`; pick a prefix of your own.",source:"tui",severity:"degraded",expected:!0},COMPONENT_UNKNOWN:{code:"AX-EXT-031",title:"No Such Component",description:"A line named a component that is not registered. Caught when the line is created rather than when it paints, because a missing component renders as an empty gap \u2014 which reads as a layout bug instead of a typo, and gives no clue which name was wrong. components.list() returns everything available.",source:"tui",severity:"degraded",expected:!0},LINE_NAME_TAKEN:{code:"AX-EXT-032",title:"Line Already Registered",description:"Two sources registered the same line name. The first one loaded keeps it, the same rule commands and key chords follow.",source:"tui",severity:"degraded",expected:!0},LINE_UNKNOWN:{code:"AX-EXT-033",title:"No Such Line",description:"lines.set(), move(), show(), hide() or toggle() named a line that is not registered. Doing nothing would be indistinguishable from a line that registered and then rendered empty, so this fails instead. lines.list() returns what exists.",source:"tui",severity:"degraded",expected:!0},COMMAND_PATH_TAKEN:{code:"AX-EXT-020",title:"Command Already Registered",description:"Two sources registered the same command path. The first one loaded keeps it \u2014 your own config beats any extension, and between extensions the one listed earlier in profile.config.ts wins. Rename one of them.",source:"tui",severity:"degraded",expected:!0},KEY_CHORD_TAKEN:{code:"AX-EXT-021",title:"Key Chord Already Bound",description:"Two sources bound the same key chord. The first one loaded keeps it. A silently shadowed binding is unbearable to debug in someone else's config, so the second registration fails instead of replacing it.",source:"tui",severity:"degraded",expected:!0},MODE_KEY_TAKEN:{code:"AX-EXT-016",title:"Mode Key Already Bound",description:"A palette asked for a mode key that is already in use \u2014 either by a built-in mode or by another extension. A silently shadowed key is unbearable to debug in someone else's config, so the registration fails loudly instead.",source:"tui",severity:"degraded",expected:!0},MODE_UNKNOWN:{code:"AX-EXT-017",title:"No Such Mode",description:"mode.set() was given a name that is neither a built-in mode nor a registered palette. Doing nothing would look identical to a mode that simply does not render, so this fails instead.",source:"tui",severity:"fatal",expected:!0},NO_FOCUSED_AGENT:{code:"AX-EXT-018",title:"No Agent Focused",description:"A verb that acts on the focused agent \u2014 send, stop, reboot \u2014 was called while nothing was running. Start one with agents.spawn(name) or tui.nav(name) first.",source:"tui",severity:"fatal",expected:!0},INSTANCE_NOT_RUNNING:{code:"AX-EXT-019",title:"Instance Not Running",description:"An instance id was given for a conversation that is not live \u2014 it may already have been stopped, or it belongs to an earlier session. agents.list() returns what is currently running.",source:"tui",severity:"fatal",expected:!0},CONNECT_REJECTED:{code:"AX-EXT-020",title:"Connector Credential Rejected",description:"The platform refused the credential pasted during `:connect`. Verification runs before the value is written, so nothing was stored \u2014 the detail carries the platform's own reason, and the most common cause is copying the wrong secret from the developer portal.",source:"tui",severity:"fatal",expected:!0}};import{readFileSync as R40}from"fs";var w40=/at\s+(.*?)\s+\((.*?):(\d+):(\d+)\)/,S40=/at\s+(.*?):(\d+):(\d+)/,C40=["node_modules","native:","internal","bun:"],G76=2;function eE$(J=1){let Y=Error().stack;if(!Y)return[];return Y.split(`
726
+ `);for(let c of x.warnings)z.push({requestId:v.id,warning:c})}let H="batch.jsonl",F=new Blob(W,{type:"application/jsonl"});W.length=0;let P=new FormData;P.append("file",F,H);let E=TJ((Z=(Y=this.options.config).headers)==null?void 0:Z.call(Y),J.headers),{value:w}=await nK({url:this.getUrl("/files"),headers:E,formData:P,failedResponseHandler:Jq,successfulResponseHandler:Z9(LM6),abortSignal:J.abortSignal,fetch:this.options.config.fetch}),{value:S}=await W4({url:this.getUrl("/batches"),headers:E,body:{name:Yu0,input_file_id:w.id},failedResponseHandler:Jq,successfulResponseHandler:Z9(jM6),abortSignal:J.abortSignal,fetch:this.options.config.fetch});return{batchId:S.batch_id,...fv$(S),warnings:z}}async getBatchStatus(J){return fv$(await this.retrieveBatch(J))}async getBatchResults(J){let Y=await this.retrieveBatch(J);if(fv$(Y).status==="pending")throw new U7({argument:"batchId",message:`xAI batch "${J.batchId}" is not complete.`});return PE(this.iterateBatchResults(J))}async retrieveBatch(J){var Y,Z;let{value:W}=await aK({url:this.getUrl(`/batches/${encodeURIComponent(J.batchId)}`),headers:TJ((Z=(Y=this.options.config).headers)==null?void 0:Z.call(Y),J.headers),failedResponseHandler:Jq,successfulResponseHandler:Z9(jM6),abortSignal:J.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return W}async*iterateBatchResults(J){var Y,Z,W;let z;do{let H=new URLSearchParams({limit:String(Qu0)});if(z!=null)H.set("pagination_token",z);let{value:F}=await aK({url:this.getUrl(`/batches/${encodeURIComponent(J.batchId)}/results?${H}`),headers:TJ((Z=(Y=this.options.config).headers)==null?void 0:Z.call(Y),J.headers),failedResponseHandler:Jq,successfulResponseHandler:Z9(Gu0),abortSignal:J.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});for(let P of F.results)yield await this.convertBatchResult(P);z=(W=F.pagination_token)!=null?W:void 0}while(z!=null)}async convertBatchResult(J){var Y,Z,W,z,H,F;let P=(Y=J.batch_result)==null?void 0:Y.error;if(((W=(Z=J.error_message)==null?void 0:Z.length)!=null?W:0)>0||(P==null?void 0:P.code)!=null&&P.code!==0&&P.code!=="0"||(P==null?void 0:P.code)==null&&((H=(z=P==null?void 0:P.message)==null?void 0:z.length)!=null?H:0)>0){let w=ju0(J);return{id:J.batch_request_id,status:Bu0(P==null?void 0:P.code)?"cancelled":"failed",error:w}}let E=(F=J.batch_result)==null?void 0:F.response;if((E==null?void 0:E.chat_get_completion)!=null){let w=await uD({value:E.chat_get_completion,schema:AM6});if(!w.success)return BM6(J.batch_request_id);let S=Hu0(w.value);return S.success?{id:J.batch_request_id,status:"succeeded",result:S.result}:{id:J.batch_request_id,status:"failed",error:S.error}}return BM6(J.batch_request_id)}getUrl(J){var Y;return`${(Y=this.options.config.baseURL)!=null?Y:"https://api.x.ai/v1"}${J}`}},zu0,EM6=class{constructor(J,Y){this.specificationVersion="v4",this.modelId=J,this.provider=Y.provider,this.config=Y}async doCreateClientSecret(J){var Y;let Z=(Y=this.config.fetch)!=null?Y:fetch,W=`${this.config.baseURL}/realtime/client_secrets`,z={};if(J.expiresAfterSeconds!=null)z.expires_after={seconds:J.expiresAfterSeconds};let H=await Z(W,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify(z)});if(!H.ok){let P=await H.text();throw Error(`xAI realtime client secret request failed: ${H.status} ${P}`)}let F=await H.json();return{token:F.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:F.expires_at}}getWebSocketConfig(J){return{url:J.url,protocols:[`xai-client-secret.${J.token}`]}}parseServerEvent(J){return qu0(J)}serializeClientEvent(J){return Du0(J)}buildSessionConfig(J){return IM6(J)}},Fu0,Au0,_M6=(J={})=>Au0(J),Lu0,Ou0,TM6=(J={})=>Ou0(J),Pu0,Mu0,RM6=(J={})=>Mu0(J),wM6,SM6="4.0.48",Nu0,Iu0=class{constructor(J){this.config=J,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:J,mediaType:Y,filename:Z,providerOptions:W}){var z,H;let F=await dJ({provider:"xai",providerOptions:W,schema:Nu0}),P=eV(J),E=new Blob([P],{type:Y}),w=new FormData;if(Z!=null)w.append("file",E,Z);else w.append("file",E);if((F==null?void 0:F.teamId)!=null)w.append("team_id",F.teamId);let{value:S}=await nK({url:`${this.config.baseURL}/files`,headers:TJ(this.config.headers()),formData:w,failedResponseHandler:Jq,successfulResponseHandler:Z9(LM6),fetch:this.config.fetch});return{warnings:[],providerReference:{xai:S.id},...((z=S.filename)!=null?z:Z)?{filename:(H=S.filename)!=null?H:Z}:{},...Y!=null?{mediaType:Y}:{},providerMetadata:{xai:{...S.filename!=null?{filename:S.filename}:{},...S.bytes!=null?{bytes:S.bytes}:{},...S.created_at!=null?{createdAt:S.created_at}:{}}}}}},vv$,Eu0,_u0,Tu0,Ru0,wu0,Cu0,pv$=(J)=>J.mediaType!=null&&C7(J.mediaType)==="video",bM6=(J)=>J.mediaType==null||C7(J.mediaType)==="image",fu0=class{constructor(J,Y){this.modelId=J,this.config=Y,this.specificationVersion="v4",this.maxVideosPerCall=1}get provider(){return this.config.provider}async buildRequestBody(J){let Y=[],Z=await dJ({provider:"xai",providerOptions:J.providerOptions,schema:wu0}),W=yu0(J,Z),z=W==="edit-video",H=W==="extend-video",F=W==="reference-to-video";if(J.fps!=null)Y.push({type:"unsupported",feature:"fps",details:"xAI video models do not support custom FPS."});if(J.seed!=null)Y.push({type:"unsupported",feature:"seed",details:"xAI video models do not support seed."});if(J.n!=null&&J.n>1)Y.push({type:"unsupported",feature:"n",details:"xAI video models do not support generating multiple videos per call. Only 1 video will be generated."});if(z&&J.duration!=null)Y.push({type:"unsupported",feature:"duration",details:"xAI video editing does not support custom duration."});if(z&&J.aspectRatio!=null)Y.push({type:"unsupported",feature:"aspectRatio",details:"xAI video editing does not support custom aspect ratio."});if(z&&((Z==null?void 0:Z.resolution)!=null||J.resolution!=null))Y.push({type:"unsupported",feature:"resolution",details:"xAI video editing does not support custom resolution."});if(H&&J.aspectRatio!=null)Y.push({type:"unsupported",feature:"aspectRatio",details:"xAI video extension does not support custom aspect ratio."});if(H&&((Z==null?void 0:Z.resolution)!=null||J.resolution!=null))Y.push({type:"unsupported",feature:"resolution",details:"xAI video extension does not support custom resolution."});let P={model:this.modelId,prompt:J.prompt},E=!z,w=!z&&!H,S=!z&&!H;if(E&&J.duration!=null)P.duration=J.duration;if(w&&J.aspectRatio!=null)P.aspect_ratio=J.aspectRatio;if(S&&(Z==null?void 0:Z.resolution)!=null)P.resolution=Z.resolution;else if(S&&J.resolution!=null){let c=Cu0[J.resolution];if(c!=null)P.resolution=c;else Y.push({type:"unsupported",feature:"resolution",details:`Unrecognized resolution "${J.resolution}". Use providerOptions.xai.resolution with "480p", "720p", or "1080p" instead.`})}if(z)P.video={url:Z.videoUrl};if(H)P.video={url:Z.videoUrl};let v=ku0(J);if(v!=null)if(pv$(v)){let c=CM6(J)!=null;Y.push({type:"unsupported",feature:c?"frameImages":"image",details:'xAI does not accept a video as a start/frame image. The video was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.'})}else P.image={url:kM6(v)};let x=bu0(J);if(x!=null)Y.push({type:"unsupported",feature:"frameImages",details:pv$(x)?'xAI does not accept a video as a start/frame image. The video last frame was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.':`xAI video models do not support last_frame. Use providerOptions.xai.mode "extend-video" to continue from a video's last frame. The last frame image was ignored.`});if(F){let c=xu0(J,Z,Y);if(c!=null)P.reference_images=c;else Y.push({type:"unsupported",feature:"referenceImages",details:"xAI reference-to-video requires at least one image reference. The video will be generated without reference images."});let r=Z==null?void 0:Z.referenceVoiceIds;if(r!=null&&r.length>0)P.reference_audios=r.map((n)=>({voice_id:n}));if(P.resolution==="1080p")Y.push({type:"unsupported",feature:"resolution",details:"xAI reference-to-video is limited to 720p. The request was downgraded from 1080p to 720p."}),P.resolution="720p"}if(P.resolution==="1080p"&&this.modelId==="grok-imagine-video")Y.push({type:"unsupported",feature:"resolution",details:'xAI model "grok-imagine-video" does not support 1080p. Use "grok-imagine-video-1.5" for 1080p, or a lower resolution. The request was sent with 1080p.'});if(J.inputReferences!=null&&J.inputReferences.length>0&&!F)Y.push({type:"unsupported",feature:"inputReferences",details:xM6(J)?"xAI only supports inputReferences for reference-to-video generation. The reference images were ignored.":"xAI reference-to-video requires at least one image reference. The references were ignored."});if((Z==null?void 0:Z.referenceVoiceIds)!=null&&Z.referenceVoiceIds.length>0&&!F)Y.push({type:"unsupported",feature:"referenceVoiceIds",details:"xAI only supports reference voices for reference-to-video generation. The reference voices were ignored."});if(!H&&(Z==null?void 0:Z.user)!==void 0)P.user=Z.user;if(Z!=null){for(let[c,r]of Object.entries(Z))if(!["mode","pollIntervalMs","pollTimeoutMs","resolution","videoUrl","referenceImageUrls","referenceVoiceIds","user"].includes(c))P[c]=r}return{body:P,warnings:Y,xaiOptions:Z,isEdit:z,isExtension:H,hasReferenceImages:F,effectiveMode:W}}async doStart(J){var Y,Z,W,z;let H=(W=(Z=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:Z.call(Y))!=null?W:new Date,{body:F,warnings:P,isEdit:E,isExtension:w}=await this.buildRequestBody(J),S=(z=this.config.baseURL)!=null?z:"https://api.x.ai/v1",v;if(E)v=`${S}/videos/edits`;else if(w)v=`${S}/videos/extensions`;else v=`${S}/videos/generations`;let{value:x,responseHeaders:c}=await W4({url:v,headers:TJ(this.config.headers(),J.headers),body:F,failedResponseHandler:Jq,successfulResponseHandler:Z9(vu0),abortSignal:J.abortSignal,fetch:this.config.fetch}),r=x.request_id;if(!r)throw new UQ({name:"XAI_VIDEO_GENERATION_ERROR",message:"No request_id returned from xAI API."});return{operation:{requestId:r},warnings:P,response:{timestamp:H,modelId:this.modelId,headers:c}}}async doStatus(J){var Y,Z,W,z,H,F,P,E,w,S,v;let x=(W=(Z=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:Z.call(Y))!=null?W:new Date,{requestId:c}=J.operation,r=(z=this.config.baseURL)!=null?z:"https://api.x.ai/v1",{value:n,responseHeaders:B$}=await aK({url:`${r}/videos/${Su0(c)}`,validateUrl:!1,headers:TJ(this.config.headers(),J.headers),successfulResponseHandler:uu0,failedResponseHandler:Jq,abortSignal:J.abortSignal,fetch:this.config.fetch});if(n.status==="expired")return{status:"error",error:"Video generation request expired.",response:{timestamp:x,modelId:this.modelId,headers:B$}};if(n.status==="failed"){let _$=(P=(H=n.error)==null?void 0:H.message)!=null?P:(F=n.error)==null?void 0:F.code;return{status:"error",error:_$!=null?`Video generation failed: ${_$}`:"Video generation failed.",response:{timestamp:x,modelId:this.modelId,headers:B$}}}if(n.status==="done"||n.status==null&&((E=n.video)==null?void 0:E.url)){if(((w=n.video)==null?void 0:w.respect_moderation)===!1)return{status:"error",error:"Video generation was blocked due to a content policy violation.",response:{timestamp:x,modelId:this.modelId,headers:B$}};if(!((S=n.video)==null?void 0:S.url))return{status:"error",error:"Video generation completed but no video URL was returned.",response:{timestamp:x,modelId:this.modelId,headers:B$}};return{status:"completed",videos:[{type:"url",url:n.video.url,mediaType:"video/mp4"}],warnings:[],response:{timestamp:x,modelId:this.modelId,headers:B$},providerMetadata:{xai:{requestId:c,videoUrl:n.video.url,...n.video.duration!=null?{duration:n.video.duration}:{},...((v=n.usage)==null?void 0:v.cost_in_usd_ticks)!=null?{costInUsdTicks:n.usage.cost_in_usd_ticks}:{},...n.progress!=null?{progress:n.progress}:{}}}}}return{status:"pending",response:{timestamp:x,modelId:this.modelId,headers:B$}}}},vu0,yM6,hu0,HM6=1048576,gu0,uu0=async(J)=>{if(J.response.status===202){let Y=mD(J.response),Z=await mu0(J);if(Z.trim().length===0)return{responseHeaders:Y,value:{status:"pending"}};let W=await Zz({text:Z,schema:yM6});return{responseHeaders:Y,value:W.success?W.value:{status:"pending"}}}return hu0(J)},cu0,du0,lu0,VM6,pu0,tu0,eu0;var hM6=n9(()=>{g4();C1();g4();C1();c8();g4();C1();c8();C1();c8();C1();c8();g4();C1();c8();c8();g4();C1();c8();C1();c8();C1();g4();C1();c8();c8();g4();C1();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();c8();C1();C1();c8();g4();C1();c8();C1();c8();C1();c8();C1();c8();g4();C1();c8();C1();c8();qM6=q.object({imageDetail:q.enum(["low","high","auto"]).optional()});jm0=/^grok-4\.20(-\d{4})?-(non-)?reasoning$/;Bm0=q.object({type:q.literal("web"),country:q.string().length(2).optional(),excludedWebsites:q.array(q.string()).max(5).optional(),allowedWebsites:q.array(q.string()).max(5).optional(),safeSearch:q.boolean().optional()}),Hm0=q.object({type:q.literal("x"),excludedXHandles:q.array(q.string()).optional(),includedXHandles:q.array(q.string()).optional(),postFavoriteCount:q.number().int().optional(),postViewCount:q.number().int().optional(),xHandles:q.array(q.string()).optional()}),Vm0=q.object({type:q.literal("news"),country:q.string().length(2).optional(),excludedWebsites:q.array(q.string()).max(5).optional(),safeSearch:q.boolean().optional()}),qm0=q.object({type:q.literal("rss"),links:q.array(q.string().url()).max(1)}),Dm0=q.discriminatedUnion("type",[Bm0,Hm0,Vm0,qm0]),Fm0=q.object({reasoningEffort:q.enum(["none","low","medium","high","xhigh"]).optional(),logprobs:q.boolean().optional(),topLogprobs:q.number().int().min(0).max(8).optional(),serviceTier:q.enum(["default","priority"]).optional(),parallel_function_calling:q.boolean().optional(),searchParameters:q.object({mode:q.enum(["off","auto","on"]),returnCitations:q.boolean().optional(),fromDate:q.string().optional(),toDate:q.string().optional(),maxSearchResults:q.number().min(1).max(50).optional(),sources:q.array(Dm0).optional()}).optional()}),Am0=q.object({error:q.object({message:q.string(),type:q.string().nullish(),param:q.any().nullish(),code:q.union([q.string(),q.number()]).nullish()})}),Lm0=q.object({code:q.string(),error:q.string()}),Om0=q.object({error:q.string()}),Pm0=q.union([Am0,Lm0,Om0]),Jq=b2({errorSchema:Pm0,errorToMessage:(J)=>{if(typeof J.error==="string")return"code"in J?`${J.code}: ${J.error}`:J.error;return J.error.message}});Nm0=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,seed:w,reasoning:S,responseFormat:v,providerOptions:x,tools:c,toolChoice:r}){var n,B$,_$;let A$=[],H$=(n=await dJ({provider:"xai",providerOptions:x,schema:Fm0}))!=null?n:{};if(H!=null)A$.push({type:"unsupported",feature:"topK"});if(F!=null)A$.push({type:"unsupported",feature:"frequencyPenalty"});if(P!=null)A$.push({type:"unsupported",feature:"presencePenalty"});if(E!=null)A$.push({type:"unsupported",feature:"stopSequences"});let{messages:M$,warnings:b$}=await Um0(Y);A$.push(...b$);let{tools:p$,toolChoice:o$,toolWarnings:T6}=Mm0({tools:c,toolChoice:r});A$.push(...T6);let j6=H$.reasoningEffort;if(j6==null&&wZ(S))if(!DM6(this.modelId))A$.push({type:"unsupported",feature:"reasoning",details:`reasoning "${S}" is not supported by this model.`});else if(S==="none")j6="none";else j6=$q({reasoning:S,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:this.modelId==="grok-4.6"?"xhigh":"high"},warnings:A$});return{args:{model:this.modelId,logprobs:H$.logprobs===!0||H$.topLogprobs!=null?!0:void 0,top_logprobs:H$.topLogprobs,max_completion_tokens:Z,temperature:W,top_p:z,seed:w,reasoning_effort:j6,service_tier:H$.serviceTier,parallel_function_calling:H$.parallel_function_calling,response_format:(v==null?void 0:v.type)==="json"?v.schema!=null?{type:"json_schema",json_schema:{name:(B$=v.name)!=null?B$:"response",schema:v.schema,strict:!0}}:{type:"json_object"}:void 0,search_parameters:H$.searchParameters?{mode:H$.searchParameters.mode,return_citations:H$.searchParameters.returnCitations,from_date:H$.searchParameters.fromDate,to_date:H$.searchParameters.toDate,max_search_results:H$.searchParameters.maxSearchResults,sources:(_$=H$.searchParameters.sources)==null?void 0:_$.map((y$)=>{var _6;return{type:y$.type,...y$.type==="web"&&{country:y$.country,excluded_websites:y$.excludedWebsites,allowed_websites:y$.allowedWebsites,safe_search:y$.safeSearch},...y$.type==="x"&&{excluded_x_handles:y$.excludedXHandles,included_x_handles:(_6=y$.includedXHandles)!=null?_6:y$.xHandles,post_favorite_count:y$.postFavoriteCount,post_view_count:y$.postViewCount},...y$.type==="news"&&{country:y$.country,excluded_websites:y$.excludedWebsites,safe_search:y$.safeSearch},...y$.type==="rss"&&{links:y$.links}}})}:void 0,messages:M$,tools:p$,tool_choice:o$},warnings:A$}}async doGenerate(Y){var Z,W,z,H;let{args:F,warnings:P}=await this.getArgs(Y),E=`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/chat/completions`,{responseHeaders:w,value:S,rawValue:v}=await W4({url:E,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:F,failedResponseHandler:Jq,successfulResponseHandler:Z9(AM6),abortSignal:Y.abortSignal,fetch:this.config.fetch});if(S.error!=null)throw new Z5({message:S.error,url:E,requestBodyValues:F,statusCode:200,responseHeaders:w,responseBody:JSON.stringify(v),isRetryable:S.code==="The service is currently unavailable"});let x=S.choices[0],c=[];if(x.message.content!=null&&x.message.content.length>0){let r=x.message.content,n=F.messages[F.messages.length-1];if((n==null?void 0:n.role)==="assistant"&&r===n.content)r="";if(r.length>0)c.push({type:"text",text:r})}if(x.message.reasoning_content!=null&&x.message.reasoning_content.length>0)c.push({type:"reasoning",text:x.message.reasoning_content});if(x.message.tool_calls!=null)for(let r of x.message.tool_calls)c.push({type:"tool-call",toolCallId:r.id,toolName:r.function.name,input:r.function.arguments});if(S.citations!=null)for(let r of S.citations)c.push({type:"source",sourceType:"url",id:this.config.generateId(),url:r});return{content:c,finishReason:{unified:gv$(x.finish_reason),raw:(H=x.finish_reason)!=null?H:void 0},usage:S.usage?hv$(S.usage):{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...S.service_tier!=null&&{providerMetadata:{xai:{serviceTier:S.service_tier}}},request:{body:F},response:{...ao(S),headers:w,body:v},warnings:P}}async doStream(Y){var Z,W,z;let{args:H,warnings:F}=await this.getArgs(Y),P={...H,stream:!0,stream_options:{include_usage:!0}},E=`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/chat/completions`,{responseHeaders:w,value:S}=await W4({url:E,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:P,failedResponseHandler:Jq,successfulResponseHandler:async({response:H$})=>{let M$=mD(H$),b$=H$.headers.get("content-type");if(b$==null?void 0:b$.includes("application/json")){let p$=await H$.text(),o$=await Zz({text:p$,schema:Em0});if(o$.success)throw new Z5({message:o$.value.error,url:E,requestBodyValues:P,statusCode:200,responseHeaders:M$,responseBody:p$,isRetryable:o$.value.code==="The service is currently unavailable"});throw new Z5({message:"Invalid JSON response",url:E,requestBodyValues:P,statusCode:200,responseHeaders:M$,responseBody:p$})}return k2(Im0)({response:H$,url:E,requestBodyValues:P})},abortSignal:Y.abortSignal,fetch:this.config.fetch}),v={unified:"other",raw:void 0},x=void 0,c=void 0,r=!0,n={},B$={},_$=void 0,A$=this;return{stream:S.pipeThrough(new TransformStream({start(H$){H$.enqueue({type:"stream-start",warnings:F})},transform(H$,M$){if(Y.includeRawChunks)M$.enqueue({type:"raw",rawValue:H$.rawValue});if(!H$.success){M$.enqueue({type:"error",error:H$.error});return}let b$=H$.value;if(r)M$.enqueue({type:"response-metadata",...ao(b$)}),r=!1;if(b$.citations!=null)for(let j6 of b$.citations)M$.enqueue({type:"source",sourceType:"url",id:A$.config.generateId(),url:j6});if(b$.usage!=null)x=hv$(b$.usage);if(b$.service_tier!=null)c=b$.service_tier;let p$=b$.choices[0];if((p$==null?void 0:p$.finish_reason)!=null)v={unified:gv$(p$.finish_reason),raw:p$.finish_reason};if((p$==null?void 0:p$.delta)==null)return;let{delta:o$,index:T6}=p$;if(o$.content!=null&&o$.content.length>0){let j6=o$.content;if(_$!=null&&!n[_$].ended)M$.enqueue({type:"reasoning-end",id:_$}),n[_$].ended=!0,_$=void 0;let Y6=P.messages[P.messages.length-1];if((Y6==null?void 0:Y6.role)==="assistant"&&j6===Y6.content)return;let y$=`text-${b$.id||T6}`;if(n[y$]==null)n[y$]={type:"text",ended:!1},M$.enqueue({type:"text-start",id:y$});M$.enqueue({type:"text-delta",id:y$,delta:j6})}if(o$.reasoning_content!=null&&o$.reasoning_content.length>0){let j6=`reasoning-${b$.id||T6}`;if(B$[j6]===o$.reasoning_content)return;if(B$[j6]=o$.reasoning_content,n[j6]==null)n[j6]={type:"reasoning",ended:!1},_$=j6,M$.enqueue({type:"reasoning-start",id:j6});M$.enqueue({type:"reasoning-delta",id:j6,delta:o$.reasoning_content})}if(o$.tool_calls!=null){if(_$!=null&&!n[_$].ended)M$.enqueue({type:"reasoning-end",id:_$}),n[_$].ended=!0,_$=void 0;for(let j6 of o$.tool_calls){let Y6=j6.id;M$.enqueue({type:"tool-input-start",id:Y6,toolName:j6.function.name}),M$.enqueue({type:"tool-input-delta",id:Y6,delta:j6.function.arguments}),M$.enqueue({type:"tool-input-end",id:Y6}),M$.enqueue({type:"tool-call",toolCallId:Y6,toolName:j6.function.name,input:j6.function.arguments})}}},flush(H$){for(let[M$,b$]of Object.entries(n))if(!b$.ended)H$.enqueue({type:b$.type==="text"?"text-end":"reasoning-end",id:M$});H$.enqueue({type:"finish",finishReason:v,usage:x!=null?x:{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...c!=null&&{providerMetadata:{xai:{serviceTier:c}}}})}})),request:{body:P},response:{headers:w}}}},FM6=q.object({prompt_tokens:q.number(),completion_tokens:q.number(),total_tokens:q.number(),cost_in_usd_ticks:q.number().nullish(),prompt_tokens_details:q.object({text_tokens:q.number().nullish(),audio_tokens:q.number().nullish(),image_tokens:q.number().nullish(),cached_tokens:q.number().nullish()}).catchall(q.json()).nullish(),completion_tokens_details:q.object({reasoning_tokens:q.number().nullish(),audio_tokens:q.number().nullish(),accepted_prediction_tokens:q.number().nullish(),rejected_prediction_tokens:q.number().nullish()}).catchall(q.json()).nullish()}).catchall(q.json()),AM6=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({message:q.object({role:q.literal("assistant"),content:q.string().nullish(),reasoning_content:q.string().nullish(),tool_calls:q.array(q.object({id:q.string(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),index:q.number(),finish_reason:q.string().nullish()})).nullish(),object:q.literal("chat.completion").nullish(),usage:FM6.nullish(),citations:q.array(q.string().url()).nullish(),service_tier:q.string().nullish(),code:q.string().nullish(),error:q.string().nullish()}),Im0=q.object({id:q.string().nullish(),created:q.number().nullish(),model:q.string().nullish(),choices:q.array(q.object({delta:q.object({role:q.enum(["assistant"]).optional(),content:q.string().nullish(),reasoning_content:q.string().nullish(),tool_calls:q.array(q.object({id:q.string(),type:q.literal("function"),function:q.object({name:q.string(),arguments:q.string()})})).nullish()}),finish_reason:q.string().nullish(),index:q.number()})),usage:FM6.nullish(),citations:q.array(q.string().url()).nullish(),service_tier:q.string().nullish()}),Em0=q.object({code:q.string(),error:q.string()}),_m0=q.object({aspect_ratio:q.string().optional(),output_format:q.string().optional(),sync_mode:q.boolean().optional(),resolution:q.enum(["1k","2k"]).optional(),quality:q.enum(["low","medium","high"]).optional(),user:q.string().optional()}),Tm0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4",this.maxImagesPerCall=3}get provider(){return this.config.provider}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async doGenerate({prompt:Y,n:Z,size:W,aspectRatio:z,seed:H,providerOptions:F,headers:P,abortSignal:E,files:w,mask:S}){var v,x,c,r,n,B$,_$;let A$=[];if(W!=null)A$.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});if(H!=null)A$.push({type:"unsupported",feature:"seed"});if(S!=null)A$.push({type:"unsupported",feature:"mask"});let H$=await dJ({provider:"xai",providerOptions:F,schema:_m0}),M$=w!=null&&w.length>0,b$=M$?w.map((x$)=>qA6(x$)):[],p$=M$?"/images/edits":"/images/generations",o$={model:this.modelId,prompt:Y,n:Z,response_format:"b64_json"};if(z!=null)o$.aspect_ratio=z;if((H$==null?void 0:H$.output_format)!=null)o$.output_format=H$.output_format;if((H$==null?void 0:H$.sync_mode)!=null)o$.sync_mode=H$.sync_mode;if((H$==null?void 0:H$.aspect_ratio)!=null&&z==null)o$.aspect_ratio=H$.aspect_ratio;if((H$==null?void 0:H$.resolution)!=null)o$.resolution=H$.resolution;if((H$==null?void 0:H$.quality)!=null)o$.quality=H$.quality;if((H$==null?void 0:H$.user)!=null)o$.user=H$.user;if(b$.length===1)o$.image={url:b$[0],type:"image_url"};else if(b$.length>1)o$.images=b$.map((x$)=>({url:x$,type:"image_url"}));let T6=(v=this.config.baseURL)!=null?v:"https://api.x.ai/v1",j6=(r=(c=(x=this.config._internal)==null?void 0:x.currentDate)==null?void 0:c.call(x))!=null?r:new Date,{value:Y6,responseHeaders:y$}=await W4({url:`${T6}${p$}`,headers:TJ((B$=(n=this.config).headers)==null?void 0:B$.call(n),P),body:o$,failedResponseHandler:Jq,successfulResponseHandler:Z9(Rm0),abortSignal:E,fetch:this.config.fetch});if(Y6.data.some((x$)=>x$.respect_moderation===!1))throw Error("Image generation was blocked due to a content policy violation.");return{images:Y6.data.every((x$)=>x$.b64_json!=null)?Y6.data.map((x$)=>x$.b64_json):await Promise.all(Y6.data.map((x$)=>this.downloadImage(x$.url,E))),warnings:A$,response:{timestamp:j6,modelId:this.modelId,headers:y$},providerMetadata:{xai:{images:Y6.data.map((x$)=>({...x$.revised_prompt?{revisedPrompt:x$.revised_prompt}:{}})),...((_$=Y6.usage)==null?void 0:_$.cost_in_usd_ticks)!=null?{costInUsdTicks:Y6.usage.cost_in_usd_ticks}:{}}}}}async downloadImage(Y,Z){let{value:W}=await aK({url:Y,validateUrl:!0,trustedOrigin:this.config.baseURL,abortSignal:Z,failedResponseHandler:hA6(),successfulResponseHandler:rR(),fetch:this.config.fetch});return W}},Rm0=q.object({data:q.array(q.object({url:q.string().nullish(),b64_json:q.string().nullish(),revised_prompt:q.string().nullish(),respect_moderation:q.boolean().nullish()})),usage:q.object({cost_in_usd_ticks:q.number().nullish()}).nullish()}),LM6=p0(()=>d0(q.object({id:q.string(),object:q.string().nullish(),bytes:q.number().nullish(),created_at:q.number().nullish(),filename:q.string().nullish(),purpose:q.string().nullish(),status:q.string().nullish()})));mv$=q.union([q.object({type:q.literal("url_citation"),url:q.string(),title:q.string().optional()}),q.object({type:q.string()})]),uv$=q.object({type:q.string(),text:q.string().optional(),logprobs:q.array(q.any()).optional(),annotations:q.array(mv$).optional()}),cv$=q.object({type:q.string(),text:q.string()}),tk=q.object({name:q.string().optional(),arguments:q.string().optional(),input:q.string().optional(),call_id:q.string().optional(),id:q.string(),status:q.string(),action:q.any().optional()}),Sm0=q.object({type:q.literal("url"),url:q.string()}),Cm0=q.discriminatedUnion("type",[q.object({type:q.literal("search"),query:q.string().nullish(),queries:q.array(q.string()).nullish(),sources:q.array(q.unknown()).nullish()}),q.object({type:q.literal("open_page"),url:q.string().nullish(),sources:q.array(q.unknown()).nullish()}),q.object({type:q.literal("find_in_page"),url:q.string().nullish(),pattern:q.string().nullish(),sources:q.array(q.unknown()).nullish()})]),bm0=q.object({name:q.string().optional(),arguments:q.string().optional(),output:q.string().optional(),error:q.string().optional(),id:q.string(),status:q.string(),server_label:q.string().optional()}),dv$=q.discriminatedUnion("type",[q.object({type:q.literal("web_search_call"),...tk.shape}),q.object({type:q.literal("x_search_call"),...tk.shape}),q.object({type:q.literal("code_interpreter_call"),...tk.shape}),q.object({type:q.literal("code_execution_call"),...tk.shape}),q.object({type:q.literal("view_image_call"),...tk.shape}),q.object({type:q.literal("view_x_video_call"),...tk.shape}),q.object({type:q.literal("file_search_call"),id:q.string(),status:q.string(),queries:q.array(q.string()).optional(),results:q.array(q.object({file_id:q.string(),filename:q.string(),score:q.number(),text:q.string()})).nullish()}),q.object({type:q.literal("image_generation_call"),id:q.string(),status:q.string(),prompt:q.string().nullish(),result:q.string().nullish()}),q.object({type:q.literal("custom_tool_call"),...tk.shape}),q.object({type:q.literal("mcp_call"),...bm0.shape}),q.object({type:q.literal("message"),role:q.string(),content:q.array(uv$),id:q.string(),status:q.string()}),q.object({type:q.literal("function_call"),name:q.string(),arguments:q.string(),call_id:q.string(),id:q.string()}),q.object({type:q.literal("reasoning"),id:q.string(),summary:q.array(cv$),content:q.array(q.object({type:q.string(),text:q.string()})).nullish(),status:q.string(),encrypted_content:q.string().nullish()})]),lv$=q.object({input_tokens:q.number(),output_tokens:q.number(),total_tokens:q.number().optional(),input_tokens_details:q.object({cached_tokens:q.number().optional()}).catchall(q.json()).optional(),output_tokens_details:q.object({reasoning_tokens:q.number().optional()}).catchall(q.json()).optional(),num_sources_used:q.number().optional(),num_server_side_tools_used:q.number().optional(),cost_in_usd_ticks:q.number().nullish()}).catchall(q.json()),so=q.object({id:q.string().nullish(),created_at:q.number().nullish(),model:q.string().nullish(),object:q.literal("response"),output:q.array(dv$),usage:lv$.nullish(),status:q.string(),service_tier:q.string().nullish()}),km0=q.union([q.object({type:q.literal("response.created"),response:so.partial({usage:!0,status:!0})}),q.object({type:q.literal("response.in_progress"),response:so.partial({usage:!0,status:!0})}),q.object({type:q.literal("response.output_item.added"),item:dv$,output_index:q.number()}),q.object({type:q.literal("response.output_item.done"),item:dv$,output_index:q.number()}),q.object({type:q.literal("response.content_part.added"),item_id:q.string(),output_index:q.number(),content_index:q.number(),part:uv$}),q.object({type:q.literal("response.content_part.done"),item_id:q.string(),output_index:q.number(),content_index:q.number(),part:uv$}),q.object({type:q.literal("response.output_text.delta"),item_id:q.string(),output_index:q.number(),content_index:q.number(),delta:q.string(),logprobs:q.array(q.any()).optional()}),q.object({type:q.literal("response.output_text.done"),item_id:q.string(),output_index:q.number(),content_index:q.number(),text:q.string(),logprobs:q.array(q.any()).optional(),annotations:q.array(mv$).optional()}),q.object({type:q.literal("response.output_text.annotation.added"),item_id:q.string(),output_index:q.number(),content_index:q.number(),annotation_index:q.number(),annotation:mv$}),q.object({type:q.literal("response.reasoning_summary_part.added"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),part:cv$}),q.object({type:q.literal("response.reasoning_summary_part.done"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),part:cv$}),q.object({type:q.literal("response.reasoning_summary_text.delta"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.reasoning_summary_text.done"),item_id:q.string(),output_index:q.number(),summary_index:q.number(),text:q.string()}),q.object({type:q.literal("response.reasoning_text.delta"),item_id:q.string(),output_index:q.number(),content_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.reasoning_text.done"),item_id:q.string(),output_index:q.number(),content_index:q.number(),text:q.string()}),q.object({type:q.literal("response.web_search_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.web_search_call.searching"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.web_search_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.x_search_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.x_search_call.searching"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.x_search_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.file_search_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.file_search_call.searching"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.file_search_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.image_generation_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.image_generation_call.generating"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.image_generation_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_execution_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_execution_call.executing"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_execution_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.executing"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.interpreting"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.code_interpreter_call_code.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.code_interpreter_call_code.done"),item_id:q.string(),output_index:q.number(),code:q.string()}),q.object({type:q.literal("response.custom_tool_call_input.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.custom_tool_call_input.done"),item_id:q.string(),output_index:q.number(),input:q.string()}),q.object({type:q.literal("response.function_call_arguments.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.function_call_arguments.done"),item_id:q.string(),output_index:q.number(),arguments:q.string()}),q.object({type:q.literal("response.mcp_call.in_progress"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call.executing"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call.completed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call.failed"),item_id:q.string(),output_index:q.number()}),q.object({type:q.literal("response.mcp_call_arguments.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.mcp_call_arguments.done"),item_id:q.string(),output_index:q.number(),arguments:q.string().optional()}),q.object({type:q.literal("response.mcp_call_output.delta"),item_id:q.string(),output_index:q.number(),delta:q.string()}),q.object({type:q.literal("response.mcp_call_output.done"),item_id:q.string(),output_index:q.number(),output:q.string().optional()}),q.object({type:q.literal("response.incomplete"),response:q.object({incomplete_details:q.object({reason:q.string()}).nullish(),usage:lv$.nullish(),service_tier:q.string().nullish()})}),q.object({type:q.literal("response.failed"),response:q.object({error:q.object({code:q.string().nullish(),message:q.string()}).nullish(),incomplete_details:q.object({reason:q.string()}).nullish(),usage:lv$.nullish()})}),q.object({type:q.literal("error"),code:q.string().nullish(),message:q.string(),param:q.string().nullish()}),q.object({type:q.literal("response.done"),response:so}),q.object({type:q.literal("response.completed"),response:so})]),xm0=q.object({reasoningEffort:q.enum(["none","low","medium","high","xhigh"]).optional(),reasoningSummary:q.enum(["auto","concise","detailed"]).optional(),logprobs:q.boolean().optional(),topLogprobs:q.number().int().min(0).max(8).optional(),serviceTier:q.enum(["default","priority"]).optional(),store:q.boolean().optional(),previousResponseId:q.string().optional(),include:q.array(q.enum(["file_search_call.results"])).nullish()}),ym0=p0(()=>d0(q.object({vectorStoreIds:q.array(q.string()),maxNumResults:q.number().optional()}))),fm0=p0(()=>d0(q.object({queries:q.array(q.string()),results:q.array(q.object({fileId:q.string(),filename:q.string(),score:q.number().min(0).max(1),text:q.string()})).nullable()}))),vm0=EX({id:"xai.file_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:fm0}),gm0=p0(()=>d0(q.object({action:q.enum(["auto","generate","edit"]).optional()}))),mm0=p0(()=>d0(q.object({}))),um0=p0(()=>d0(q.object({result:q.string(),prompt:q.string().optional()}))),cm0=EX({id:"xai.image_generation",inputSchema:mm0,outputSchema:um0}),dm0=p0(()=>d0(q.object({serverUrl:q.string().describe("The URL of the MCP server"),serverLabel:q.string().optional().describe("A label for the MCP server"),serverDescription:q.string().optional().describe("Description of the MCP server"),allowedTools:q.array(q.string()).optional().describe("List of allowed tool names"),headers:q.record(q.string(),q.string()).optional().describe("Custom headers to send"),authorization:q.string().optional().describe("Authorization header value")}))),lm0=p0(()=>d0(q.object({name:q.string(),arguments:q.string(),result:q.unknown()}))),pm0=EX({id:"xai.mcp",inputSchema:p0(()=>d0(q.object({}))),outputSchema:lm0}),im0=p0(()=>d0(q.object({allowedDomains:q.array(q.string()).max(5).optional(),excludedDomains:q.array(q.string()).max(5).optional(),enableImageSearch:q.boolean().optional(),enableImageUnderstanding:q.boolean().optional()}))),rm0=p0(()=>d0(q.object({action:q.discriminatedUnion("type",[q.object({type:q.literal("search"),query:q.string().optional(),queries:q.array(q.string()).optional()}),q.object({type:q.literal("openPage"),url:q.string().nullish()}),q.object({type:q.literal("findInPage"),url:q.string().nullish(),pattern:q.string().nullish()})]).optional(),sources:q.array(q.object({type:q.literal("url"),url:q.string()})).optional()}))),sm0=EX({id:"xai.web_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:rm0}),am0=p0(()=>d0(q.object({allowedXHandles:q.array(q.string()).max(10).optional(),excludedXHandles:q.array(q.string()).max(10).optional(),fromDate:q.string().optional(),toDate:q.string().optional(),enableImageUnderstanding:q.boolean().optional(),enableVideoUnderstanding:q.boolean().optional()}))),nm0=p0(()=>d0(q.object({query:q.string(),posts:q.array(q.object({author:q.string(),text:q.string(),url:q.string(),likes:q.number()}))}))),om0=EX({id:"xai.x_search",inputSchema:p0(()=>d0(q.object({}))),outputSchema:nm0});zM6=class J{constructor(Y,Z){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/],"text/*":[/^https?:\/\/.*$/]},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,seed:w,responseFormat:S,providerOptions:v,tools:x,toolChoice:c,reasoning:r}){var n,B$,_$,A$,H$,M$,b$,p$,o$;let T6=[],j6=(n=await dJ({provider:"xai",providerOptions:v,schema:xm0}))!=null?n:{};if(H!=null)T6.push({type:"unsupported",feature:"topK"});if(F!=null)T6.push({type:"unsupported",feature:"frequencyPenalty"});if(P!=null)T6.push({type:"unsupported",feature:"presencePenalty"});if(E!=null)T6.push({type:"unsupported",feature:"stopSequences"});let Y6=(B$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.web_search"))==null?void 0:B$.name,y$=(_$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.x_search"))==null?void 0:_$.name,_6=(A$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.code_execution"))==null?void 0:A$.name,k6=(H$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.mcp"))==null?void 0:H$.name,x$=(M$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.file_search"))==null?void 0:M$.name,r0=(b$=x==null?void 0:x.find((u0)=>u0.type==="provider"&&u0.id==="xai.image_generation"))==null?void 0:b$.name,{input:m0,inputWarnings:b6}=await wm0({prompt:Y,store:(p$=j6.store)!=null?p$:!0});T6.push(...b6);let{tools:W0,toolChoice:J1,toolWarnings:D1}=await tm0({tools:x,toolChoice:c});T6.push(...D1);let Z0=j6.include?[...j6.include]:void 0;if(j6.store===!1)if(Z0==null)Z0=["reasoning.encrypted_content"];else Z0=[...Z0,"reasoning.encrypted_content"];let B1=j6.reasoningEffort;if(B1==null&&wZ(r))if(!DM6(this.modelId))T6.push({type:"unsupported",feature:"reasoning",details:`reasoning "${r}" is not supported by this model.`});else if(r==="none")B1="none";else B1=$q({reasoning:r,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:this.modelId==="grok-4.6"?"xhigh":"high"},warnings:T6});let x0={model:this.modelId,input:m0,logprobs:j6.logprobs===!0||j6.topLogprobs!=null?!0:void 0,top_logprobs:j6.topLogprobs,max_output_tokens:Z,temperature:W,top_p:z,seed:w,...(S==null?void 0:S.type)==="json"&&{text:{format:S.schema!=null?{type:"json_schema",strict:!0,name:(o$=S.name)!=null?o$:"response",description:S.description,schema:S.schema}:{type:"json_object"}}},...(B1!=null||j6.reasoningSummary!=null)&&{reasoning:{...B1!=null&&{effort:B1},...j6.reasoningSummary!=null&&{summary:j6.reasoningSummary}}},...j6.store===!1&&{store:j6.store},...Z0!=null&&{include:Z0},...j6.previousResponseId!=null&&{previous_response_id:j6.previousResponseId},...j6.serviceTier!=null&&{service_tier:j6.serviceTier}};if(W0&&W0.length>0)x0.tools=W0;if(J1!=null)x0.tool_choice=J1;return{args:x0,warnings:T6,webSearchToolName:Y6,xSearchToolName:y$,codeExecutionToolName:_6,mcpToolName:k6,fileSearchToolName:x$,imageGenerationToolName:r0}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x,c,r,n,B$,_$,A$,H$;let{args:M$,warnings:b$,webSearchToolName:p$,xSearchToolName:o$,codeExecutionToolName:T6,mcpToolName:j6,fileSearchToolName:Y6,imageGenerationToolName:y$}=await this.getArgs(Y),{responseHeaders:_6,value:k6,rawValue:x$}=await W4({url:`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/responses`,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:M$,failedResponseHandler:Jq,successfulResponseHandler:Z9(so),abortSignal:Y.abortSignal,fetch:this.config.fetch}),r0=[],m0=!1,b6=["web_search","web_search_with_snippets","browse_page"],W0=["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"];for(let J1 of k6.output){if(J1.type==="file_search_call"){let D1=Y6!=null?Y6:"file_search";r0.push({type:"tool-call",toolCallId:J1.id,toolName:D1,input:"",providerExecuted:!0}),r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,result:{queries:(H=J1.queries)!=null?H:[],results:(P=(F=J1.results)==null?void 0:F.map((Z0)=>({fileId:Z0.file_id,filename:Z0.filename,score:Z0.score,text:Z0.text})))!=null?P:null}});continue}if(J1.type==="image_generation_call"){let D1=y$!=null?y$:"image_generation";if(r0.push({type:"tool-call",toolCallId:J1.id,toolName:D1,input:"{}",providerExecuted:!0}),J1.result!=null)r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,result:{result:J1.result,...J1.prompt!=null&&{prompt:J1.prompt}}});else r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,isError:!0,result:`Image generation failed (status: ${J1.status}).`});continue}if(J1.type==="web_search_call"||J1.type==="x_search_call"||J1.type==="code_interpreter_call"||J1.type==="code_execution_call"||J1.type==="view_image_call"||J1.type==="view_x_video_call"||J1.type==="custom_tool_call"||J1.type==="mcp_call"){let D1=(E=J1.name)!=null?E:"";if(b6.includes((w=J1.name)!=null?w:"")||J1.type==="web_search_call")D1=p$!=null?p$:"web_search";else if(W0.includes((S=J1.name)!=null?S:"")||J1.type==="x_search_call")D1=o$!=null?o$:"x_search";else if(J1.name==="code_execution"||J1.type==="code_interpreter_call"||J1.type==="code_execution_call")D1=T6!=null?T6:"code_execution";else if(J1.type==="mcp_call")D1=(v=j6!=null?j6:J1.name)!=null?v:"mcp";let Z0=J1.type==="custom_tool_call"?(x=J1.input)!=null?x:"":J1.type==="mcp_call"?(c=J1.arguments)!=null?c:"":(r=J1.arguments)!=null?r:"";if(r0.push({type:"tool-call",toolCallId:J1.id,toolName:D1,input:Z0,providerExecuted:!0}),J1.type==="web_search_call")r0.push({type:"tool-result",toolCallId:J1.id,toolName:D1,result:UM6(J1.action)});continue}switch(J1.type){case"message":{for(let D1 of J1.content){if(D1.text)r0.push({type:"text",text:D1.text});if(D1.annotations){for(let Z0 of D1.annotations)if(Z0.type==="url_citation"&&"url"in Z0)r0.push({type:"source",sourceType:"url",id:this.config.generateId(),url:Z0.url,title:(n=Z0.title)!=null?n:Z0.url})}}break}case"function_call":{m0=!0,r0.push({type:"tool-call",toolCallId:J1.call_id,toolName:J1.name,input:J1.arguments});break}case"reasoning":{let Z0=(J1.summary.length>0?J1.summary.map((B1)=>B1.text):((B$=J1.content)!=null?B$:[]).map((B1)=>B1.text)).filter((B1)=>B1&&B1.length>0).join("");if(Z0||J1.encrypted_content){let B1=J1.encrypted_content||J1.id;r0.push({type:"reasoning",text:Z0,...B1&&{providerMetadata:{xai:{...J1.encrypted_content&&{reasoningEncryptedContent:J1.encrypted_content},...J1.id&&{itemId:J1.id}}}}})}break}default:break}}return{content:r0,finishReason:{unified:m0?"tool-calls":DZ$(k6.status),raw:(_$=k6.status)!=null?_$:void 0},usage:k6.usage?yv$(k6.usage):{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...(((A$=k6.usage)==null?void 0:A$.cost_in_usd_ticks)!=null||k6.service_tier!=null)&&{providerMetadata:{xai:{...((H$=k6.usage)==null?void 0:H$.cost_in_usd_ticks)!=null&&{costInUsdTicks:k6.usage.cost_in_usd_ticks},...k6.service_tier!=null&&{serviceTier:k6.service_tier}}}},request:{body:M$},response:{...ao(k6),headers:_6,body:x$},warnings:b$}}async doStream(Y){var Z,W,z;let{args:H,warnings:F,webSearchToolName:P,xSearchToolName:E,codeExecutionToolName:w,mcpToolName:S,fileSearchToolName:v,imageGenerationToolName:x}=await this.getArgs(Y),c={...H,stream:!0},{responseHeaders:r,value:n}=await W4({url:`${(Z=this.config.baseURL)!=null?Z:"https://api.x.ai/v1"}/responses`,headers:TJ((z=(W=this.config).headers)==null?void 0:z.call(W),Y.headers),body:c,failedResponseHandler:Jq,successfulResponseHandler:k2(km0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),B$={unified:"other",raw:void 0},_$=!1,A$=void 0,H$=void 0,M$=void 0,b$=!0,p$={},o$=new Set,T6={},j6={},Y6=this;return{stream:n.pipeThrough(new TransformStream({start(y$){y$.enqueue({type:"stream-start",warnings:F})},transform(y$,_6){var k6,x$,r0,m0,b6,W0,J1,D1,Z0,B1,x0,u0,G9,f1,l9,WJ,l8;if(Y.includeRawChunks)_6.enqueue({type:"raw",rawValue:y$.rawValue});if(!y$.success){_6.enqueue({type:"error",error:y$.error});return}let L1=y$.value;if(L1.type==="response.created"||L1.type==="response.in_progress"){if(b$)_6.enqueue({type:"response-metadata",...ao(L1.response)}),b$=!1;return}if(L1.type==="response.reasoning_summary_part.added"){let Q1=`reasoning-${L1.item_id}`;if(j6[L1.item_id]==null)j6[L1.item_id]={},_6.enqueue({type:"reasoning-start",id:Q1,providerMetadata:{xai:{itemId:L1.item_id}}})}if(L1.type==="response.reasoning_summary_text.delta"){let Q1=`reasoning-${L1.item_id}`;_6.enqueue({type:"reasoning-delta",id:Q1,delta:L1.delta,providerMetadata:{xai:{itemId:L1.item_id}}});return}if(L1.type==="response.reasoning_summary_text.done")return;if(L1.type==="response.reasoning_text.delta"){let Q1=`reasoning-${L1.item_id}`;if(j6[L1.item_id]==null)j6[L1.item_id]={},_6.enqueue({type:"reasoning-start",id:Q1,providerMetadata:{xai:{itemId:L1.item_id}}});_6.enqueue({type:"reasoning-delta",id:Q1,delta:L1.delta,providerMetadata:{xai:{itemId:L1.item_id}}});return}if(L1.type==="response.reasoning_text.done")return;if(L1.type==="response.output_text.delta"){let Q1=`text-${L1.item_id}`;if(p$[Q1]==null)p$[Q1]={type:"text"},_6.enqueue({type:"text-start",id:Q1});_6.enqueue({type:"text-delta",id:Q1,delta:L1.delta});return}if(L1.type==="response.output_text.done"){if(L1.annotations){for(let Q1 of L1.annotations)if(Q1.type==="url_citation"&&"url"in Q1)_6.enqueue({type:"source",sourceType:"url",id:Y6.config.generateId(),url:Q1.url,title:(k6=Q1.title)!=null?k6:Q1.url})}return}if(L1.type==="response.output_text.annotation.added"){let Q1=L1.annotation;if(Q1.type==="url_citation"&&"url"in Q1)_6.enqueue({type:"source",sourceType:"url",id:Y6.config.generateId(),url:Q1.url,title:(x$=Q1.title)!=null?x$:Q1.url});return}if(L1.type==="response.done"||L1.type==="response.completed"||L1.type==="response.incomplete"){let Q1=L1.response;if(Q1.usage)A$=yv$(Q1.usage),H$=(r0=Q1.usage.cost_in_usd_ticks)!=null?r0:void 0;if(M$=(m0=Q1.service_tier)!=null?m0:void 0,L1.type==="response.incomplete"){let SJ="incomplete_details"in Q1?(b6=Q1.incomplete_details)==null?void 0:b6.reason:void 0;B$={unified:SJ?DZ$(SJ):"other",raw:SJ!=null?SJ:"incomplete"}}else if("status"in Q1&&Q1.status)B$={unified:_$?"tool-calls":DZ$(Q1.status),raw:Q1.status};return}if(L1.type==="response.failed"){let Q1=(W0=L1.response.incomplete_details)==null?void 0:W0.reason;if(B$={unified:Q1?DZ$(Q1):"error",raw:Q1!=null?Q1:"error"},L1.response.usage)A$=yv$(L1.response.usage);if(L1.response.error!=null)_6.enqueue({type:"error",error:WM6({message:L1.response.error.message,code:L1.response.error.code,eventType:L1.type,data:L1})});return}if(L1.type==="error"){_6.enqueue({type:"error",error:WM6({message:L1.message,code:L1.code,eventType:L1.type,data:L1})});return}if(L1.type==="response.custom_tool_call_input.delta"||L1.type==="response.custom_tool_call_input.done")return;if(L1.type==="response.function_call_arguments.delta"){let Q1=T6[L1.output_index];if(Q1!=null)_6.enqueue({type:"tool-input-delta",id:Q1.toolCallId,delta:L1.delta});return}if(L1.type==="response.function_call_arguments.done")return;if(L1.type==="response.image_generation_call.in_progress"||L1.type==="response.image_generation_call.generating"||L1.type==="response.image_generation_call.completed"){if(!o$.has(L1.item_id)){o$.add(L1.item_id);let Q1=x!=null?x:"image_generation";_6.enqueue({type:"tool-input-start",id:L1.item_id,toolName:Q1}),_6.enqueue({type:"tool-input-delta",id:L1.item_id,delta:"{}"}),_6.enqueue({type:"tool-input-end",id:L1.item_id}),_6.enqueue({type:"tool-call",toolCallId:L1.item_id,toolName:Q1,input:"{}",providerExecuted:!0})}return}if(L1.type==="response.output_item.added"||L1.type==="response.output_item.done"){let Q1=L1.item;if(Q1.type==="reasoning"){if(L1.type==="response.output_item.done"){let SJ=`reasoning-${Q1.id}`;if(!(Q1.id in j6))j6[Q1.id]={},_6.enqueue({type:"reasoning-start",id:SJ,providerMetadata:{xai:{...Q1.id&&{itemId:Q1.id}}}});_6.enqueue({type:"reasoning-end",id:SJ,providerMetadata:{xai:{...Q1.encrypted_content&&{reasoningEncryptedContent:Q1.encrypted_content},...Q1.id&&{itemId:Q1.id}}}}),delete j6[Q1.id]}return}if(Q1.type==="file_search_call"){let SJ=v!=null?v:"file_search";if(!o$.has(Q1.id))o$.add(Q1.id),_6.enqueue({type:"tool-input-start",id:Q1.id,toolName:SJ}),_6.enqueue({type:"tool-input-delta",id:Q1.id,delta:""}),_6.enqueue({type:"tool-input-end",id:Q1.id}),_6.enqueue({type:"tool-call",toolCallId:Q1.id,toolName:SJ,input:"",providerExecuted:!0});if(L1.type==="response.output_item.done")_6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:SJ,result:{queries:(J1=Q1.queries)!=null?J1:[],results:(Z0=(D1=Q1.results)==null?void 0:D1.map((L6)=>({fileId:L6.file_id,filename:L6.filename,score:L6.score,text:L6.text})))!=null?Z0:null}});return}if(Q1.type==="image_generation_call"){let SJ=x!=null?x:"image_generation";if(!o$.has(Q1.id))o$.add(Q1.id),_6.enqueue({type:"tool-input-start",id:Q1.id,toolName:SJ}),_6.enqueue({type:"tool-input-delta",id:Q1.id,delta:"{}"}),_6.enqueue({type:"tool-input-end",id:Q1.id}),_6.enqueue({type:"tool-call",toolCallId:Q1.id,toolName:SJ,input:"{}",providerExecuted:!0});if(L1.type==="response.output_item.done")if(Q1.result!=null)_6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:SJ,result:{result:Q1.result,...Q1.prompt!=null&&{prompt:Q1.prompt}}});else _6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:SJ,isError:!0,result:`Image generation failed (status: ${Q1.status}).`});return}if(Q1.type==="web_search_call"||Q1.type==="x_search_call"||Q1.type==="code_interpreter_call"||Q1.type==="code_execution_call"||Q1.type==="view_image_call"||Q1.type==="view_x_video_call"||Q1.type==="custom_tool_call"||Q1.type==="mcp_call"){let SJ=["web_search","web_search_with_snippets","browse_page"],L6=["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"],s6=(B1=Q1.name)!=null?B1:"";if(SJ.includes((x0=Q1.name)!=null?x0:"")||Q1.type==="web_search_call")s6=P!=null?P:"web_search";else if(L6.includes((u0=Q1.name)!=null?u0:"")||Q1.type==="x_search_call")s6=E!=null?E:"x_search";else if(Q1.name==="code_execution"||Q1.type==="code_interpreter_call"||Q1.type==="code_execution_call")s6=w!=null?w:"code_execution";else if(Q1.type==="mcp_call")s6=(G9=S!=null?S:Q1.name)!=null?G9:"mcp";let u6=Q1.type==="custom_tool_call"?(f1=Q1.input)!=null?f1:"":Q1.type==="mcp_call"?(l9=Q1.arguments)!=null?l9:"":(WJ=Q1.arguments)!=null?WJ:"";if((Q1.type==="custom_tool_call"?L1.type==="response.output_item.done":!o$.has(Q1.id))&&!o$.has(Q1.id))o$.add(Q1.id),_6.enqueue({type:"tool-input-start",id:Q1.id,toolName:s6}),_6.enqueue({type:"tool-input-delta",id:Q1.id,delta:u6}),_6.enqueue({type:"tool-input-end",id:Q1.id}),_6.enqueue({type:"tool-call",toolCallId:Q1.id,toolName:s6,input:u6,providerExecuted:!0});if(L1.type==="response.output_item.done")_6.enqueue({type:"tool-result",toolCallId:Q1.id,toolName:s6,result:Q1.type==="web_search_call"?UM6(Q1.action):{}});return}if(Q1.type==="message")for(let SJ of Q1.content){if(SJ.text&&SJ.text.length>0){let L6=`text-${Q1.id}`;if(p$[L6]==null)p$[L6]={type:"text"},_6.enqueue({type:"text-start",id:L6}),_6.enqueue({type:"text-delta",id:L6,delta:SJ.text})}if(SJ.annotations){for(let L6 of SJ.annotations)if(L6.type==="url_citation"&&"url"in L6)_6.enqueue({type:"source",sourceType:"url",id:Y6.config.generateId(),url:L6.url,title:(l8=L6.title)!=null?l8:L6.url})}}else if(Q1.type==="function_call"){if(L1.type==="response.output_item.added")T6[L1.output_index]={toolName:Q1.name,toolCallId:Q1.call_id},_6.enqueue({type:"tool-input-start",id:Q1.call_id,toolName:Q1.name});else if(L1.type==="response.output_item.done")_$=!0,T6[L1.output_index]=void 0,_6.enqueue({type:"tool-input-end",id:Q1.call_id}),_6.enqueue({type:"tool-call",toolCallId:Q1.call_id,toolName:Q1.name,input:Q1.arguments})}}},flush(y$){for(let[_6,k6]of Object.entries(p$))if(k6.type==="text")y$.enqueue({type:"text-end",id:_6});y$.enqueue({type:"finish",finishReason:B$,usage:A$!=null?A$:{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...(H$!=null||M$!=null)&&{providerMetadata:{xai:{...H$!=null&&{costInUsdTicks:H$},...M$!=null&&{serviceTier:M$}}}}})}})),request:{body:c},response:{headers:r}}}};jM6=p0(()=>d0(q.object({batch_id:q.string(),name:q.string().nullish(),create_time:q.string().nullish(),expire_time:q.string().nullish(),cancel_time:q.string().nullish(),cancel_by_xai_message:q.string().nullish(),state:q.object({num_requests:q.number().nullish(),num_pending:q.number().nullish(),num_success:q.number().nullish(),num_error:q.number().nullish(),num_cancelled:q.number().nullish()}).nullish()}))),Ku0=q.object({code:q.union([q.string(),q.number()]).nullish(),message:q.string().nullish()}),Zu0=q.object({batch_request_id:q.string(),batch_result:q.object({response:q.object({chat_get_completion:q.unknown().nullish()}).nullish(),error:Ku0.nullish()}).nullish(),error_message:q.string().nullish()}),Gu0=p0(()=>d0(q.object({results:q.array(Zu0),pagination_token:q.string().nullish()}))),zu0=class J extends zM6{static[Y4](Y){return zM6[Y4](Y)}static[U4](Y){return new J(Y.modelId,Y.config)}constructor(Y,Z){super(Y,Z);this.batch=new Wu0({config:Z,prepareRequest:async(W)=>{let{args:z,warnings:H}=await this.getArgs(W.options);return{body:z,warnings:H}}})}experimental_doStartBatch(Y){return this.batch.startBatch(Y)}experimental_doGetBatchStatus(Y){return this.batch.getBatchStatus(Y)}experimental_doGetBatchResults(Y){return this.batch.getBatchResults(Y)}};Fu0=q.object({output:q.string().describe("the output of the code execution"),error:q.string().optional().describe("any error that occurred")}),Au0=EX({id:"xai.code_execution",inputSchema:q.object({}).describe("no input parameters"),outputSchema:Fu0}),Lu0=q.object({description:q.string().describe("description of the image"),objects:q.array(q.string()).optional().describe("objects detected in the image")}),Ou0=EX({id:"xai.view_image",inputSchema:q.object({}).describe("no input parameters"),outputSchema:Lu0}),Pu0=q.object({transcript:q.string().optional().describe("transcript of the video"),description:q.string().describe("description of the video content"),duration:q.number().optional().describe("duration in seconds")}),Mu0=EX({id:"xai.view_x_video",inputSchema:q.object({}).describe("no input parameters"),outputSchema:Pu0}),wM6={codeExecution:_M6,fileSearch:hm0,imageGeneration:OM6,mcpServer:PM6,viewImage:TM6,viewXVideo:RM6,webSearch:MM6,xSearch:NM6},Nu0=p0(()=>d0(q.looseObject({teamId:q.string().optional(),filePath:q.string().optional()}))),vv$=q.string().min(1),Eu0=q.enum(["480p","720p","1080p"]),_u0=q.enum(["edit-video","extend-video","reference-to-video"]),Tu0={pollIntervalMs:q.number().positive().nullish(),pollTimeoutMs:q.number().positive().nullish(),resolution:Eu0.nullish()},Ru0=q.looseObject({mode:_u0.optional(),videoUrl:vv$.optional(),referenceImageUrls:q.array(vv$).min(1).max(7).optional(),referenceVoiceIds:q.array(vv$).max(3).optional(),user:q.string().optional(),...Tu0}),wu0=p0(()=>d0(Ru0));Cu0={"1920x1080":"1080p","1280x720":"720p","854x480":"480p","640x480":"480p"};vu0=q.object({request_id:q.string().nullish()}),yM6=q.object({status:q.string().nullish(),video:q.object({url:q.string(),duration:q.number().nullish(),respect_moderation:q.boolean().nullish()}).nullish(),model:q.string().nullish(),usage:q.object({cost_in_usd_ticks:q.number().nullish()}).nullish(),progress:q.number().nullish(),error:q.object({code:q.string().nullish(),message:q.string().nullish()}).nullish()}),hu0=Z9(yM6),gu0=new TextDecoder;cu0=p0(()=>d0(q.object({sampleRate:q.union([q.literal(8000),q.literal(16000),q.literal(22050),q.literal(24000),q.literal(44100),q.literal(48000)]).nullish(),bitRate:q.union([q.literal(32000),q.literal(64000),q.literal(96000),q.literal(128000),q.literal(192000)]).nullish(),optimizeStreamingLatency:q.union([q.literal(0),q.literal(1),q.literal(2)]).nullish(),textNormalization:q.boolean().nullish(),withTimestamps:q.boolean().nullish(),replace:q.record(q.string(),q.string()).nullish()}))),du0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({text:Y,voice:Z="eve",outputFormat:W="mp3",instructions:z,speed:H,language:F="auto",providerOptions:P}){let E=[],w=await dJ({provider:"xai",providerOptions:P,schema:cu0}),S="mp3";if(["mp3","wav","pcm","mulaw","alaw"].includes(W))S=W;else E.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${W}. Using mp3 instead.`});if(z!=null)E.push({type:"unsupported",feature:"instructions",details:"xAI speech models do not support the `instructions` option. Use xAI speech tags in `text` to control delivery."});let v={codec:S};if((w==null?void 0:w.sampleRate)!=null)v.sample_rate=w.sampleRate;if((w==null?void 0:w.bitRate)!=null)if(S==="mp3")v.bit_rate=w.bitRate;else E.push({type:"unsupported",feature:"providerOptions",details:"xAI `bitRate` is supported only for mp3 output. It was ignored."});return{requestBody:{text:Y,voice_id:Z,language:F,output_format:v,speed:H,optimize_streaming_latency:w==null?void 0:w.optimizeStreamingLatency,text_normalization:w==null?void 0:w.textNormalization,with_timestamps:w==null?void 0:w.withTimestamps,replace:w==null?void 0:w.replace},warnings:E,withTimestamps:(w==null?void 0:w.withTimestamps)===!0}}async doGenerate(Y){var Z,W,z;let H=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{requestBody:F,warnings:P,withTimestamps:E}=await this.getArgs(Y),{value:w,responseHeaders:S,rawValue:v}=await W4({url:`${this.config.baseURL}/tts`,headers:TJ(this.config.headers?await HK(this.config.headers):void 0,Y.headers),body:F,failedResponseHandler:Jq,successfulResponseHandler:E?Z9(lu0):rR(),abortSignal:Y.abortSignal,fetch:this.config.fetch}),x,c;if(w instanceof Uint8Array)x=w;else c=w,x=c.audio!=null?BK(c.audio):new Uint8Array(0);let r=S==null?void 0:S["x-trace-id"];return{audio:x,warnings:P,request:{body:JSON.stringify(F)},response:{timestamp:H,modelId:this.modelId,headers:S,body:v},providerMetadata:{xai:{...r!=null?{traceId:r}:{},...(c==null?void 0:c.duration)!=null?{duration:c.duration}:{},...(c==null?void 0:c.content_type)!=null?{contentType:c.content_type}:{},...(c==null?void 0:c.audio_timestamps)!=null?{audioTimestamps:{graphChars:c.audio_timestamps.graph_chars,graphTimes:c.audio_timestamps.graph_times}}:{}}}}}},lu0=q.object({audio:q.string().nullish(),content_type:q.string().nullish(),duration:q.number().nullish(),audio_timestamps:q.object({graph_chars:q.array(q.string()),graph_times:q.array(q.tuple([q.number(),q.number()]))}).nullish()}),VM6=p0(()=>d0(q.object({audioFormat:q.enum(["pcm","mulaw","alaw"]).nullish(),sampleRate:q.union([q.literal(8000),q.literal(16000),q.literal(22050),q.literal(24000),q.literal(44100),q.literal(48000)]).nullish(),language:q.string().nullish(),format:q.boolean().nullish(),multichannel:q.boolean().nullish(),channels:q.number().int().min(2).max(8).nullish(),diarize:q.boolean().nullish(),keyterm:q.union([q.string(),q.array(q.string())]).nullish(),fillerWords:q.boolean().nullish(),streaming:q.object({interimResults:q.boolean().optional(),endpointing:q.number().int().min(0).max(5000).optional(),smartTurn:q.number().min(0).max(1).optional(),smartTurnTimeout:q.number().int().min(1).max(5000).optional()}).optional()}))),pu0=class J{constructor(Y,Z){this.modelId=Y,this.config=Z,this.specificationVersion="v4"}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}get provider(){return this.config.provider}async getArgs({audio:Y,mediaType:Z,providerOptions:W}){let z=[],H=await dJ({provider:"xai",providerOptions:W,schema:VM6}),F=new FormData,P={audio_format:H==null?void 0:H.audioFormat,sample_rate:H==null?void 0:H.sampleRate,language:H==null?void 0:H.language,format:H==null?void 0:H.format,multichannel:H==null?void 0:H.multichannel,channels:H==null?void 0:H.channels,diarize:H==null?void 0:H.diarize,filler_words:H==null?void 0:H.fillerWords};for(let[S,v]of Object.entries(P))if(v!=null)F.append(S,String(v));if((H==null?void 0:H.keyterm)!=null){let S=Array.isArray(H.keyterm)?H.keyterm:[H.keyterm];for(let v of S)F.append("keyterm",v)}let E=Y instanceof Uint8Array?new Blob([Y]):new Blob([BK(Y)]),w=lR(Z);return F.append("file",new File([E],"audio",{type:Z}),`audio.${w}`),{formData:F,warnings:z}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S;let v=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,{formData:x,warnings:c}=await this.getArgs(Y),{value:r,responseHeaders:n,rawValue:B$}=await nK({url:`${(H=this.config.baseURL)!=null?H:"https://api.x.ai/v1"}/stt`,headers:TJ((P=(F=this.config).headers)==null?void 0:P.call(F),Y.headers),formData:x,failedResponseHandler:Jq,successfulResponseHandler:Z9(tu0),abortSignal:Y.abortSignal,fetch:this.config.fetch});return{text:r.text,segments:(w=(E=r.words)==null?void 0:E.map((_$)=>({text:_$.text,startSecond:_$.start,endSecond:_$.end})))!=null?w:[],language:r.language||void 0,durationInSeconds:(S=r.duration)!=null?S:void 0,warnings:c,response:{timestamp:v,modelId:this.modelId,headers:n,body:B$}}}async doStream(Y){var Z,W,z,H,F,P,E;let w=(z=(W=(Z=this.config._internal)==null?void 0:Z.currentDate)==null?void 0:W.call(Z))!=null?z:new Date,S=[],v=await dJ({provider:"xai",providerOptions:Y.providerOptions,schema:VM6});if((v==null?void 0:v.multichannel)===!0&&v.channels==null)throw new U7({argument:"providerOptions",message:"providerOptions.xai.channels is required when providerOptions.xai.multichannel is true"});if((v==null?void 0:v.format)!=null)S.push({type:"unsupported",feature:"providerOptions.xai.format",details:"xAI streaming transcription does not support format."});if((v==null?void 0:v.audioFormat)==null&&!su0(Y.inputAudioFormat.type))S.push({type:"other",message:`Unrecognized inputAudioFormat.type "${Y.inputAudioFormat.type}"; falling back to raw PCM encoding. Use audio/pcm, audio/pcmu, or audio/pcma, or set providerOptions.xai.audioFormat explicitly.`});let x=ru0({baseURL:(H=this.config.baseURL)!=null?H:"https://api.x.ai/v1",inputAudioFormat:Y.inputAudioFormat,providerOptions:v}),c=TJ((P=(F=this.config).headers)==null?void 0:P.call(F),Y.headers);return{request:{body:x.toString()},response:{timestamp:w,modelId:this.modelId},stream:iu0({webSocket:this.config.webSocket,url:x,headers:c,warnings:S,language:(E=v==null?void 0:v.language)!=null?E:void 0,expectedDoneCount:(v==null?void 0:v.multichannel)===!0?v.channels:1,audio:Y.audio,abortSignal:Y.abortSignal,includeRawChunks:Y.includeRawChunks})}}};tu0=q.object({text:q.string(),language:q.string().nullish(),duration:q.number().nullish(),words:q.array(q.object({text:q.string(),start:q.number(),end:q.number()})).nullish()});eu0=fM6()});var iM6={};EW(iM6,{perplexity:()=>Uc0,createPerplexity:()=>pM6,VERSION:()=>lM6});function gM6(J){var Y,Z,W;if(J==null)return mZ();let z=(Y=J.prompt_tokens)!=null?Y:0,H=(Z=J.completion_tokens)!=null?Z:0,F=(W=J.reasoning_tokens)!=null?W:0;return{inputTokens:{total:z,noCache:z,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:H+F,text:H,reasoning:F},raw:J}}function Jc0(J){let Y=[];for(let{role:Z,content:W}of J)switch(Z){case"system":{Y.push({role:"system",content:W});break}case"user":case"assistant":{let z=W.some((F)=>F.type==="file"&&C7(F.mediaType)==="image"||F.type==="file"&&C7(F.mediaType)==="application"),H=W.map((F,P)=>{switch(F.type){case"text":return{type:"text",text:F.text};case"file":switch(F.data.type){case"reference":throw new E9({functionality:"file parts with provider references"});case"text":throw new E9({functionality:"text file parts"});case"url":case"data":{let E=C7(F.mediaType);if(E==="application"){let w=hQ({part:F});if(w!=="application/pdf")throw new E9({functionality:`file part media type ${w}`});return F.data.type==="url"?{type:"file_url",file_url:{url:F.data.url.toString()},file_name:F.filename}:{type:"file_url",file_url:{url:typeof F.data.data==="string"?F.data.data:ME(F.data.data)},file_name:F.filename||`document-${P}.pdf`}}else if(E==="image")return F.data.type==="url"?{type:"image_url",image_url:{url:F.data.url.toString()}}:{type:"image_url",image_url:{url:`data:${hQ({part:F})};base64,${typeof F.data.data==="string"?F.data.data:ME(F.data.data)}`}};throw new E9({functionality:`file part media type ${F.mediaType}`})}}}}).filter(Boolean);Y.push({role:Z,content:z?H:H.filter((F)=>F.type==="text").map((F)=>F.text).join("")});break}case"tool":throw new E9({functionality:"Tool messages"});default:throw Error(`Unsupported role: ${Z}`)}return Y}function mM6(J){switch(J){case"stop":case"length":return J;default:return"other"}}function Wc0(J,Y){let Z=BK(J);if(Y==="base64_int8"){let W=new Int8Array(Z.buffer,Z.byteOffset,Z.byteLength);return Array.from(W)}return Array.from(Z)}function pM6(J={}){var Y;let Z=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"PERPLEXITY_API_KEY",description:"Perplexity"})}`,...J.headers},`ai-sdk/perplexity/${lM6}`),W=XW((Y=J.baseURL)!=null?Y:"https://api.perplexity.ai"),z=(P)=>{return new Yc0(P,{baseURL:W,headers:Z,generateId:wY,fetch:J.fetch})},H=(P)=>new Gc0(P,{provider:"perplexity.embedding",baseURL:W,headers:Z,fetch:J.fetch}),F=(P)=>z(P);return F.specificationVersion="v4",F.languageModel=z,F.embedding=H,F.embeddingModel=H,F.textEmbeddingModel=H,F.imageModel=(P)=>{throw new CW({modelId:P,modelType:"imageModel"})},F}var $c0,Xc0,Yc0,Qc0,cM6,dM6,Kc0,Zc0,iv$,uM6=(J)=>{var Y,Z;return(Z=(Y=J.error.message)!=null?Y:J.error.type)!=null?Z:"unknown error"},Gc0,zc0,lM6="4.0.34",Uc0;var rM6=n9(()=>{g4();C1();g4();C1();c8();c8();C1();c8();C1();g4();C1();c8();$c0=q.object({dimensions:q.number().int().positive().optional(),encodingFormat:q.enum(["base64_int8","base64_binary"]).optional()});Xc0=q.looseObject({search_recency_filter:q.enum(["hour","day","week","month","year"]).optional(),search_domain_filter:q.array(q.string()).optional(),search_language_filter:q.array(q.string()).optional(),search_after_date_filter:q.string().optional(),search_before_date_filter:q.string().optional(),last_updated_after_filter:q.string().optional(),last_updated_before_filter:q.string().optional(),search_mode:q.enum(["web","academic","sec"]).optional(),enable_search_classifier:q.boolean().optional(),disable_search:q.boolean().optional(),return_related_questions:q.boolean().optional(),return_images:q.boolean().optional(),image_domain_filter:q.array(q.string()).optional(),image_format_filter:q.array(q.string()).optional(),media_response:q.looseObject({overrides:q.looseObject({return_videos:q.boolean().optional()}).optional()}).optional(),stream_mode:q.enum(["full","concise"]).optional(),reasoning_effort:q.enum(["minimal","low","medium","high"]).optional(),language_preference:q.string().optional(),web_search_options:q.looseObject({search_context_size:q.enum(["low","medium","high"]).optional(),search_type:q.enum(["fast","pro","auto"]).optional(),user_location:q.looseObject({latitude:q.number().optional(),longitude:q.number().optional(),country:q.string().optional(),city:q.string().optional(),region:q.string().optional()}).optional(),image_results_enhanced_relevance:q.boolean().optional()}).optional()}),Yc0=class J{constructor(Y,Z){this.specificationVersion="v4",this.provider="perplexity",this.supportedUrls={},this.modelId=Y,this.config=Z}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async getArgs({prompt:Y,maxOutputTokens:Z,temperature:W,topP:z,topK:H,frequencyPenalty:F,presencePenalty:P,stopSequences:E,reasoning:w,responseFormat:S,seed:v,providerOptions:x}){var c;let r=[],n=(c=await dJ({provider:"perplexity",providerOptions:x,schema:Xc0}))!=null?c:{};if(H!=null)r.push({type:"unsupported",feature:"topK"});if(E!=null)r.push({type:"unsupported",feature:"stopSequences"});if(v!=null)r.push({type:"unsupported",feature:"seed"});if(wZ(w))r.push({type:"unsupported",feature:"reasoning",details:"This provider does not support reasoning configuration."});return{args:{model:this.modelId,frequency_penalty:F,max_tokens:Z,presence_penalty:P,temperature:W,top_k:H,top_p:z,response_format:(S==null?void 0:S.type)==="json"?{type:"json_schema",json_schema:{schema:S.schema}}:void 0,...n,messages:Jc0(Y)},warnings:r}}async doGenerate(Y){var Z,W,z,H,F,P,E,w,S,v,x,c,r,n;let{args:B$,warnings:_$}=await this.getArgs(Y),{responseHeaders:A$,value:H$,rawValue:M$}=await W4({url:`${this.config.baseURL}/chat/completions`,headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:B$,failedResponseHandler:b2({errorSchema:iv$,errorToMessage:uM6}),successfulResponseHandler:Z9(Kc0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),b$=H$.choices[0],p$=[],o$=b$.message.content;if(o$.length>0)p$.push({type:"text",text:o$});if(H$.citations!=null)for(let T6 of H$.citations)p$.push({type:"source",sourceType:"url",id:this.config.generateId(),url:T6});return{content:p$,finishReason:{unified:mM6(b$.finish_reason),raw:(z=b$.finish_reason)!=null?z:void 0},usage:gM6(H$.usage),request:{body:B$},response:{...RZ(H$),headers:A$,body:M$},warnings:_$,providerMetadata:{perplexity:{images:(F=(H=H$.images)==null?void 0:H.map((T6)=>({imageUrl:T6.image_url,originUrl:T6.origin_url,height:T6.height,width:T6.width})))!=null?F:null,usage:{citationTokens:(E=(P=H$.usage)==null?void 0:P.citation_tokens)!=null?E:null,numSearchQueries:(S=(w=H$.usage)==null?void 0:w.num_search_queries)!=null?S:null},cost:((v=H$.usage)==null?void 0:v.cost)?{inputTokensCost:(x=H$.usage.cost.input_tokens_cost)!=null?x:null,outputTokensCost:(c=H$.usage.cost.output_tokens_cost)!=null?c:null,requestCost:(r=H$.usage.cost.request_cost)!=null?r:null,totalCost:(n=H$.usage.cost.total_cost)!=null?n:null}:null}}}}async doStream(Y){var Z,W;let{args:z,warnings:H}=await this.getArgs(Y),F={...z,stream:!0},{responseHeaders:P,value:E}=await W4({url:`${this.config.baseURL}/chat/completions`,headers:TJ((W=(Z=this.config).headers)==null?void 0:W.call(Z),Y.headers),body:F,failedResponseHandler:b2({errorSchema:iv$,errorToMessage:uM6}),successfulResponseHandler:k2(Zc0),abortSignal:Y.abortSignal,fetch:this.config.fetch}),w={unified:"other",raw:void 0},S=void 0,v={perplexity:{usage:{citationTokens:null,numSearchQueries:null},cost:null,images:null}},x=!0,c=!1,r=this;return{stream:E.pipeThrough(new TransformStream({start(n){n.enqueue({type:"stream-start",warnings:H})},transform(n,B$){var _$,A$,H$,M$,b$,p$,o$;if(Y.includeRawChunks)B$.enqueue({type:"raw",rawValue:n.rawValue});if(!n.success){B$.enqueue({type:"error",error:n.error});return}let T6=n.value;if(x)B$.enqueue({type:"response-metadata",...RZ(T6)}),(_$=T6.citations)==null||_$.forEach((_6)=>{B$.enqueue({type:"source",sourceType:"url",id:r.config.generateId(),url:_6})}),x=!1;if(T6.usage!=null)S=T6.usage,v.perplexity.usage={citationTokens:(A$=T6.usage.citation_tokens)!=null?A$:null,numSearchQueries:(H$=T6.usage.num_search_queries)!=null?H$:null},v.perplexity.cost=T6.usage.cost?{inputTokensCost:(M$=T6.usage.cost.input_tokens_cost)!=null?M$:null,outputTokensCost:(b$=T6.usage.cost.output_tokens_cost)!=null?b$:null,requestCost:(p$=T6.usage.cost.request_cost)!=null?p$:null,totalCost:(o$=T6.usage.cost.total_cost)!=null?o$:null}:null;if(T6.images!=null)v.perplexity.images=T6.images.map((_6)=>({imageUrl:_6.image_url,originUrl:_6.origin_url,height:_6.height,width:_6.width}));let j6=T6.choices[0];if((j6==null?void 0:j6.finish_reason)!=null)w={unified:mM6(j6.finish_reason),raw:j6.finish_reason};if((j6==null?void 0:j6.delta)==null)return;let y$=j6.delta.content;if(y$!=null){if(!c)B$.enqueue({type:"text-start",id:"0"}),c=!0;B$.enqueue({type:"text-delta",id:"0",delta:y$})}},flush(n){if(c)n.enqueue({type:"text-end",id:"0"});n.enqueue({type:"finish",finishReason:w,usage:gM6(S),providerMetadata:v})}})),request:{body:F},response:{headers:P}}}},Qc0=q.object({input_tokens_cost:q.number().nullish(),output_tokens_cost:q.number().nullish(),request_cost:q.number().nullish(),total_cost:q.number().nullish()}),cM6=q.object({prompt_tokens:q.number(),completion_tokens:q.number(),total_tokens:q.number().nullish(),citation_tokens:q.number().nullish(),num_search_queries:q.number().nullish(),reasoning_tokens:q.number().nullish(),cost:Qc0.nullish()}),dM6=q.object({image_url:q.string(),origin_url:q.string(),height:q.number(),width:q.number()}),Kc0=q.object({id:q.string(),created:q.number(),model:q.string(),choices:q.array(q.object({message:q.object({role:q.literal("assistant"),content:q.string()}),finish_reason:q.string().nullish()})),citations:q.array(q.string()).nullish(),images:q.array(dM6).nullish(),usage:cM6.nullish()}),Zc0=q.object({id:q.string(),created:q.number(),model:q.string(),choices:q.array(q.object({delta:q.object({role:q.literal("assistant").optional(),content:q.string().nullish()}),finish_reason:q.string().nullish()})),citations:q.array(q.string()).nullish(),images:q.array(dM6).nullish(),usage:cM6.nullish()}),iv$=q.object({error:q.object({code:q.number(),message:q.string().nullish(),type:q.string().nullish()})}),Gc0=class J{constructor(Y,Z){this.specificationVersion="v4",this.maxEmbeddingsPerCall=512,this.supportsParallelCalls=!0,this.modelId=Y,this.config=Z}get provider(){return this.config.provider}static[Y4](Y){return a4({modelId:Y.modelId,config:Y.config})}static[U4](Y){return new J(Y.modelId,Y.config)}async doEmbed({values:Y,abortSignal:Z,headers:W,providerOptions:z}){var H,F,P,E,w,S;if(Y.length>this.maxEmbeddingsPerCall)throw new JM({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Y});let v=(H=await dJ({provider:"perplexity",providerOptions:z,schema:$c0}))!=null?H:{},x=(F=v.encodingFormat)!=null?F:"base64_int8",{responseHeaders:c,value:r,rawValue:n}=await W4({url:`${this.config.baseURL}/v1/embeddings`,headers:TJ(this.config.headers(),W),body:{model:this.modelId,input:Y,dimensions:v.dimensions,encoding_format:x},failedResponseHandler:b2({errorSchema:iv$,errorToMessage:(_$)=>{var A$;return(A$=_$.error.message)!=null?A$:"Unknown error"}}),successfulResponseHandler:Z9(zc0),abortSignal:Z,fetch:this.config.fetch}),B$=(P=r.usage)==null?void 0:P.cost;return{embeddings:r.data.map((_$)=>Wc0(_$.embedding,x)),usage:r.usage?{tokens:r.usage.prompt_tokens}:void 0,providerMetadata:B$?{perplexity:{cost:{inputCost:(E=B$.input_cost)!=null?E:null,totalCost:(w=B$.total_cost)!=null?w:null,currency:(S=B$.currency)!=null?S:null}}}:void 0,response:{headers:c,body:n},warnings:[]}}};zc0=q.object({data:q.array(q.object({embedding:q.string()})),usage:q.object({prompt_tokens:q.number(),cost:q.object({input_cost:q.number().nullish(),total_cost:q.number().nullish(),currency:q.string().nullish()}).nullish()}).nullish()});Uc0=pM6()});var tM6={};EW(tM6,{zai:()=>Dc0,createZai:()=>oM6,VERSION:()=>nM6});function Vc0(J){let{doSample:Y,frequency_penalty:Z,presence_penalty:W,requestId:z,seed:H,thinking:F,toolStream:P,user:E,userId:w,verbosity:S,...v}=J;return{...v,...Y!==void 0&&{do_sample:Y},...F!==void 0&&{thinking:{...F.type!==void 0&&{type:F.type},...F.clearThinking!==void 0&&{clear_thinking:F.clearThinking}}},...P!==void 0&&{tool_stream:P},...z!==void 0&&{request_id:z},...w!==void 0&&{user_id:w}}}function aM6(J){switch(J.raw){case"sensitive":return{unified:"content-filter",raw:J.raw};case"model_context_window_exceeded":return{unified:"length",raw:J.raw};case"network_error":return{unified:"error",raw:J.raw};default:return J}}function oM6(J={}){var Y;let Z=(Y=XW(J.baseURL))!=null?Y:"https://api.z.ai/api/paas/v4",W=()=>sK({Authorization:`Bearer ${Kz({apiKey:J.apiKey,environmentVariableName:"ZAI_API_KEY",description:"Z.AI API key"})}`,...J.headers},`ai-sdk/zai/${nM6}`),z=(F)=>new qc0(F,{provider:"zai.chat",baseURL:Z,headers:W,fetch:J.fetch}),H=(F)=>z(F);return H.specificationVersion="v4",H.languageModel=z,H.chat=z,H.embeddingModel=(F)=>{throw new CW({modelId:F,modelType:"embeddingModel"})},H.textEmbeddingModel=H.embeddingModel,H.imageModel=(F)=>{throw new CW({modelId:F,modelType:"imageModel"})},H}var nM6="3.0.1",jc0,sM6,Bc0,Hc0,qc0,Dc0;var eM6=n9(()=>{g4();C1();KZ$();C1();c8();c8();jc0=q.object({doSample:q.boolean().optional(),thinking:q.object({type:q.enum(["enabled","disabled"]).optional(),clearThinking:q.boolean().optional()}).optional(),reasoningEffort:q.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),toolStream:q.boolean().optional(),requestId:q.string().min(6).max(64).optional(),userId:q.string().min(6).max(128).optional()}),sM6=q.object({code:q.union([q.number(),q.string()]).nullish(),message:q.string()}),Bc0=q.union([sM6,q.object({error:sM6})]),Hc0={errorSchema:Bc0,errorToMessage:(J)=>("error"in J)?J.error.message:J.message};qc0=class J extends Ju{static[Y4](Y){return a4({modelId:Y.modelId,config:Y.zaiConfig})}static[U4](Y){return new J(Y.modelId,Y.config)}constructor(Y,Z){let W=Z.headers;super(Y,{provider:Z.provider,url:({path:z})=>`${Z.baseURL}${z}`,headers:W==null?void 0:()=>typeof W==="function"?W():W,fetch:Z.fetch,errorStructure:Hc0,transformRequestBody:Vc0,supportedUrls:()=>({"image/*":[/^https?:\/\//],"video/*":[/^https?:\/\//]})});this.zaiConfig=Z}async prepareCallOptions(Y){let Z=[],W=await dJ({provider:"zai",providerOptions:Y.providerOptions,schema:jc0});if(Y.frequencyPenalty!=null)Z.push({type:"unsupported",feature:"frequencyPenalty"});if(Y.presencePenalty!=null)Z.push({type:"unsupported",feature:"presencePenalty"});if(Y.seed!=null)Z.push({type:"unsupported",feature:"seed"});let{tools:z,toolChoice:H}=Y;if((H==null?void 0:H.type)==="none")z=void 0,H=void 0;else if(H!=null&&H.type!=="auto")Z.push({type:"unsupported",feature:`toolChoice ${H.type}`,details:"Z.AI currently supports only automatic tool selection."}),H=void 0;return{normalizedOptions:{...Y,frequencyPenalty:void 0,presencePenalty:void 0,seed:void 0,tools:z,toolChoice:H,providerOptions:W==null?Y.providerOptions:{...Y.providerOptions,zai:W}},warnings:Z}}async doGenerate(Y){let{normalizedOptions:Z,warnings:W}=await this.prepareCallOptions(Y),z=await super.doGenerate(Z);return{...z,finishReason:aM6(z.finishReason),warnings:[...z.warnings,...W]}}async doStream(Y){let{normalizedOptions:Z,warnings:W}=await this.prepareCallOptions(Y),z=await super.doStream(Z);return{...z,stream:z.stream.pipeThrough(new TransformStream({transform(H,F){if(H.type==="stream-start"){F.enqueue({...H,warnings:[...H.warnings,...W]});return}if(H.type==="finish"){F.enqueue({...H,finishReason:aM6(H.finishReason)});return}F.enqueue(H)}}))}}};Dc0=oM6()});var MQ$={UNKNOWN:{code:"AX-UNKNOWN-001",title:"Unclassified Error",description:"An error occurred that hasn't been given a proper code yet. This is itself worth fixing \u2014 see the err(cause) call site that produced it.",source:"runtime",severity:"fatal"},PROMPT_NOT_FOUND:{code:"AX-PROMPT-001",title:"Prompt Not Found",description:"The requested prompt could not be resolved \u2014 it is not declared by the agent, or the published package it names ships no prompt by that name.",source:"runtime",severity:"fatal",expected:!0},PROMPT_FILE_NOT_FOUND:{code:"AX-PROMPT-002",title:"Prompt File Missing",description:"The prompt is declared but its source file no longer exists on disk.",source:"runtime",severity:"fatal",expected:!0},PROMPT_RENDER_FAILED:{code:"AX-PROMPT-003",title:"Prompt Render Failed",description:"The prompt's source file failed to compile or render \u2014 likely a malformed SFC (content outside <template>/<script>/<style>) or an error thrown while rendering. See the cause for the underlying parser/render error.",source:"runtime",severity:"fatal"},OUTPUT_INVALID:{code:"AX-OUTPUT-001",title:"Invalid Output Type",description:"The `output` type passed to request() is not valid TypeScript, or references a type that does not exist. Checked before the model is called, so no inference was spent \u2014 fix the type string at the call site.",source:"runtime",severity:"fatal"},OUTPUT_UNSATISFIED:{code:"AX-OUTPUT-002",title:"Output Type Not Satisfied",description:"The model could not produce a response matching the declared `output` type within its retry budget. The accumulated TypeScript diagnostics describe what it got wrong on each attempt.",source:"runtime",severity:"fatal"},OUTPUT_EMPTY:{code:"AX-OUTPUT-003",title:"Model Produced No Output Block",description:"Every reply must wrap its content in a <text> or <script> block \u2014 text outside a block is discarded by the parser. The model replied with none, on every attempt in its retry budget, so there was nothing to render or run. Usually means the model is not following the block protocol rather than that anything is misconfigured: the reply itself is often correct, just unwrapped. Try a different model, or check that the protocol the cognet renders matches the one it parses with.",source:"runtime",severity:"fatal",expected:!0},SCRIPT_NOT_FOUND:{code:"AX-SCRIPT-001",title:"Script Not Found",description:"The requested script was not found in the agent's blueprint. It may not be declared, or the agent needs to be re-prepared.",source:"runtime",severity:"fatal",expected:!0},SCRIPT_FILE_NOT_FOUND:{code:"AX-SCRIPT-002",title:"Script File Missing",description:"The script is declared but its source file no longer exists on disk.",source:"runtime",severity:"fatal",expected:!0},SUBAGENT_LINK_UNSUPPORTED:{code:"AX-SCRIPT-004",title:"Subagent Not Supported Over The Link",description:"An agent asked to spawn a subagent whose child runs as a confined process. `axon.request()` returns a wake's collected entries, while the link's `stimulus` verb returns only admission \u2014 the supervisor needs a verb that collects a wake and answers when it settles. Until that exists this fails rather than returning an admission receipt the caller would read as a result.",source:"runtime",severity:"fatal"},AGENT_BOOT_FAILED:{code:"AX-AGENT-006",title:"Agent Failed To Boot",description:"The agent process exited before it connected to its supervisor. Its own stderr is carried as the detail \u2014 the agent usually knows exactly what went wrong (a missing cognet, a tool that would not compile), and without this that diagnosis died in a pipe while the supervisor reported only a closed socket.",source:"runtime",severity:"fatal"},CAPSULE_NOT_LOCAL:{code:"AX-AGENT-007",title:"No Capsule On This Machine",description:'A console eval was requested against an attached deployment. Its capsule runs wherever the deployment is hosted, so there is nothing here to execute in \u2014 and quietly resolving would read as "it ran and did nothing".',source:"runtime",severity:"fatal",expected:!0},LINK_NO_HANDLER:{code:"AX-LINK-001",title:"No Handler For Link Verb",description:"The peer sent a verb this side does not implement. Both ends speak a versioned contract, so this means they disagree about it \u2014 a wiring fault, not something a user did.",source:"runtime",severity:"fatal"},LINK_PEER_CLOSED:{code:"AX-LINK-002",title:"Agent Disconnected",description:"The agent process closed its side of the link. Every call still in flight is rejected rather than left hanging \u2014 a dead peer must be an error, never a wait that never ends.",source:"runtime",severity:"fatal"},LINK_CLOSED:{code:"AX-LINK-003",title:"Link Closed",description:"The link to the agent was torn down by this side \u2014 a shutdown, a dispose, or a failed boot. Outstanding calls are rejected with this rather than hanging.",source:"runtime",severity:"fatal"},LINK_FRAME_TOO_LARGE:{code:"AX-LINK-004",title:"Link Frame Too Large",description:"A message on the link exceeded the maximum frame size, or a length prefix declared one that did. The prefix is peer-controlled input, so an oversized declaration is refused rather than allocated \u2014 a desynchronised stream cannot be recovered by reading past it.",source:"runtime",severity:"fatal"},LINK_UNKNOWN_PROMPT_ACTION:{code:"AX-LINK-005",title:"Unknown Prompt Action",description:"The prompt verb was called with an action this side does not know. Loud rather than silent: an unrecognised action would otherwise return undefined, which a caller renders as an empty prompt list.",source:"runtime",severity:"fatal"},AGENT_LINK_MISSING:{code:"AX-AGENT-001",title:"Agent Started Without A Supervisor",description:"An agent process was started with no link paths in its environment, which means nothing is supervising it. It cannot guess a socket path \u2014 doing so risks connecting to a different agent's supervisor entirely.",source:"runtime",severity:"fatal"},AGENT_LINK_MALFORMED:{code:"AX-AGENT-002",title:"Malformed Agent Link",description:"The link carrier in the agent's environment is not valid JSON, or does not name both a control and a data socket. Both are required \u2014 an agent with only one connected can accept work it has no way to answer.",source:"runtime",severity:"fatal"},AGENT_BLUEPRINT_MISSING:{code:"AX-AGENT-003",title:"Agent Started Without A Blueprint",description:"An agent process was started with no blueprint path in its environment. The supervisor writes the blueprint beside the sockets before spawning; its absence means the spawn path is broken.",source:"runtime",severity:"fatal"},AGENT_NOT_READY:{code:"AX-AGENT-004",title:"Agent Still Booting",description:"A verb arrived before the agent's runtime finished booting. The link connects first so that boot failures are reportable, which leaves a brief window where the agent can be addressed but cannot answer.",source:"runtime",severity:"fatal"},CLI_AGENT_NOT_LOCAL:{code:"AX-AGENT-005",title:"Command Needs An In-Process Agent",description:"A headless CLI command booted an agent that runs as a separate process, but the command reaches into the runtime directly. This is a wiring fault: the command needs either an in-process agent or a link verb.",source:"runtime",severity:"fatal"},ENGINE_ROLE_UNBOUND_LINK:{code:"AX-ENGINE-010",title:"No Engine For Role",description:"A confined agent asked for inference on a role the supervisor has no engine bound to. Roles are resolved on the supervisor's side before the agent starts, so an unbound one here means resolution and the cognet's declaration disagree.",source:"runtime",severity:"fatal"},ENGINE_KIND_MISMATCH_LINK:{code:"AX-ENGINE-011",title:"Engine Kind Mismatch",description:"A role bound to a transform or session engine was asked to serve a generate call. Resolution already matched the declared type, so reaching here means a provider's create() disagreed with the capability it was handed.",source:"runtime",severity:"fatal"},ENGINE_MISSING:{code:"AX-ENGINE-001",title:"No Engine Configured",description:"The agent's blueprint has no engine \u2014 it cannot dispatch to a model. Set `engine` in axon.config.ts.",source:"runtime",severity:"fatal"},ENGINE_ROLE_UNBOUND:{code:"AX-ENGINE-002",title:"Engine Role Not Bound",description:"The cognet asked for an engine role that resolution did not fill. A required role stops the boot, so reaching this means an OPTIONAL role was used without checking `kernel.engine.has()` first \u2014 or the role was never declared in the cognet's `engines:` block.",source:"runtime",severity:"fatal"},RESOURCES_EXHAUSTED:{code:"AX-RES-001",title:"Not Enough Memory",description:"A local model does not fit in what is left of this machine's video memory. Nothing was evicted: another agent is using it, and taking memory out from under a running agent would slow it down invisibly. Stop an agent that is holding a model, or raise the ceiling in your profile's `resources`.",source:"runtime",severity:"degraded",expected:!0},ENGINE_PIN_UNAVAILABLE:{code:"AX-ENGINE-004",title:"Model Not Available",description:"The agent pins a model no declared provider can supply. The agent still runs \u2014 resolution picked the best available model instead \u2014 but it is NOT the one that was asked for. Declare the provider that supplies it in your profile, or pick a model from a provider you have.",source:"runtime",severity:"degraded",expected:!0},ENGINE_REQUIREMENTS_UNMET:{code:"AX-ENGINE-003",title:"Inference Requirements Unmet",description:"This cognet declares engine roles that nothing among the user's providers can fill. Add a provider that supplies what is missing, or run a cognet whose requirements this machine meets.",source:"runtime",severity:"fatal",expected:!0},INJECT_OUTSIDE_RUNTIME:{code:"AX-RUNTIME-001",title:"Runtime Accessed Before Boot",description:"A runtime global (axon, args) was read before the runtime finished booting.",source:"runtime",severity:"fatal"},BOOT_FAILED:{code:"AX-BOOT-001",title:"Agent Failed To Start",description:"The agent's runtime crashed while starting, before it could accept requests.",source:"runtime",severity:"fatal"},BOOT_SCRIPT_FAILED:{code:"AX-BOOT-002",title:"Boot Script Failed",description:"The agent's boot.vue threw while rendering \u2014 check the script setup block for the error.",source:"runtime",severity:"fatal"},BOOT_SCRIPT_INVALID:{code:"AX-BOOT-003",title:"Boot Script Malformed",description:"The agent's boot.vue has content outside its recognized <script>/<template> blocks, or otherwise failed to parse as a valid SFC.",source:"runtime",severity:"fatal"},COGNET_ACCESSED_BEFORE_LOAD:{code:"AX-COGNET-001",title:"Cognet Accessed Before Load",description:"A cognet global (kernel, phase, system, blueprint) was read before the brain finished loading, or outside the loop body that owns it.",source:"cognet",severity:"fatal"},COGNET_LOOP_ALREADY_DECLARED:{code:"AX-COGNET-002",title:"Loop Already Declared",description:"A cognet's main() called loop() more than once \u2014 the loop is the program's entire main body and can only be declared once.",source:"cognet",severity:"fatal"},COGNET_ALREADY_LOADED:{code:"AX-COGNET-003",title:"Cognet Bound To A Different Kernel",description:"This cognet instance already loaded against a different kernel ABI \u2014 a reload produced a conflicting bind instead of a clean swap.",source:"cognet",severity:"fatal"},COGNET_NO_LOOP:{code:"AX-COGNET-004",title:"Cognet Declared No Loop",description:"The cognet's main() ran (or was woken) without ever declaring loop() \u2014 there is no program to run.",source:"cognet",severity:"fatal"},COGNET_LOAD_FAILED:{code:"AX-COGNET-016",title:"Cognet Failed To Load",description:"The cognet's own main() threw while running at load(). The brain never finished booting, so the agent has nothing to think with. The cause below is the error the cognet's code raised \u2014 it comes from the brain's source, not from Axon.",source:"cognet",severity:"fatal"},COGNET_MAX_TICKS:{code:"AX-COGNET-005",title:"Cognet Exceeded Max Ticks",description:"The cognet's loop ran more ticks in one wake than its configured limit allows \u2014 likely a runaway loop that never calls stop().",source:"cognet",severity:"fatal"},COGNET_ABI_MISMATCH:{code:"AX-COGNET-006",title:"Cognet ABI Mismatch",description:"The compiled cognet targets a kernel ABI version the running kernel doesn't provide \u2014 rebuild the cognet against the current framework version.",source:"cognet",severity:"fatal"},COGNET_MISSING:{code:"AX-COGNET-007",title:"No Compiled Cognet",description:"The blueprint points at a compiled cognet bundle that doesn't exist on disk yet \u2014 run `axon prepare` before booting.",source:"cognet",severity:"fatal"},COGNET_HASH_MISMATCH:{code:"AX-COGNET-008",title:"Cognet Bundle Hash Mismatch",description:"The compiled cognet bundle on disk doesn't match the hash the blueprint expects \u2014 it's stale or was tampered with. Run `axon prepare` again.",source:"cognet",severity:"fatal"},COGNET_INVALID:{code:"AX-COGNET-009",title:"Invalid Cognet Bundle",description:"The compiled cognet's default export isn't a real cognet definition \u2014 the compile step produced something malformed.",source:"cognet",severity:"fatal"},COGNET_IDENTITY_MISMATCH:{code:"AX-COGNET-010",title:"Cognet Identity Mismatch",description:"The compiled cognet artifact's own name doesn't match what the blueprint declared \u2014 the wrong bundle may be at this path.",source:"cognet",severity:"fatal"},COGNET_CONFIG_MISSING:{code:"AX-COGNET-011",title:"Cognet Config Missing",description:"No cognet.config.ts was found in the cognet's source directory \u2014 every cognet needs one to declare its identity.",source:"cognet",severity:"fatal"},COGNET_BUILD_FAILED:{code:"AX-COGNET-012",title:"Cognet Failed To Compile",description:"Bundling the cognet's source into a runnable artifact failed \u2014 check the build log for the underlying syntax or import error.",source:"cognet",severity:"fatal"},COGNET_RUNTIME_UNAVAILABLE:{code:"AX-COGNET-014",title:"Cognet Runtime Temporarily Unavailable",description:"The cognet runtime is declared but not present on disk \u2014 the dependency tree is mid-rewrite. Transient: the reload keeps the previous blueprint and picks the change up on the next watch event.",source:"cognet",severity:"recovered"},COGNET_AMBIGUOUS:{code:"AX-COGNET-015",title:"Two Cognets Declared",description:"The agent both declares `cognet:` in axon.config.ts and holds an inline cognet at `cognet/`. An agent has exactly one brain, and choosing between them silently would either ignore a directory of source or overrule what the author wrote. Keep one.",source:"cognet",severity:"fatal"},COGNET_NOT_FOUND:{code:"AX-COGNET-013",title:"Cognet Not Found",description:"The cognet named by `cognet:` in axon.config.ts could not be located. The detail says where it was looked for \u2014 a registry that answered 404, or a node_modules tree it was missing from. Check the specifier for a typo, and check which registry the CLI is pointed at (AXON_API_BASE).",source:"cognet",severity:"fatal",expected:!0},MODULE_SPECIFIER_INVALID:{code:"AX-PROJECT-005",title:"Invalid Module Specifier",description:"Module names must be scoped as @scope/name. The registry does not accept unscoped packages, so an unscoped specifier can never resolve.",source:"manifest",severity:"fatal"},CONFIG_MODULES_UNPARSEABLE:{code:"AX-PROJECT-006",title:"Could Not Edit axon.config.ts",description:"The install succeeded but the module entry could not be written into the config's modules array automatically \u2014 add or remove it by hand.",source:"manifest",severity:"fatal"},CONFIG_ENGINE_DEPRECATED:{code:"AX-PROJECT-033",title:"`engine:` Is Deprecated And Ignored",description:"This agent's axon.config.ts declares `engine:`, which the runtime no longer reads \u2014 inference is resolving against the profile's providers instead. Use `model: \"codex:gpt-5.6-terra\"` for a cortex pin, and `providers: [...]` for a source the user would not otherwise have.",source:"manifest",severity:"degraded"},MODULE_DEPENDENCY_INSTALL_FAILED:{code:"AX-PROJECT-004",title:"Module Dependencies Failed To Install",description:"The module source was downloaded, but its npm dependencies could not be materialized for the agent. Resolve the package-manager error and run the install again.",source:"manifest",severity:"fatal"},BLUEPRINT_NOT_LOADED:{code:"AX-PROJECT-002",title:"Blueprint Accessed Before Load",description:"Something read the blueprint's current value before load() had ever run.",source:"manifest",severity:"fatal"},AGENT_INVALID:{code:"AX-PROJECT-003",title:"Invalid Agent Directory",description:"The agent root has no package.json \u2014 every agent is a real package, this one isn't.",source:"manifest",severity:"fatal"},CORRUPT_JSON:{code:"AX-PROJECT-016",title:"Corrupt JSON File",description:"A stored JSON file failed to parse \u2014 it may have been hand-edited into an invalid state, or a write was interrupted mid-flight.",source:"manifest",severity:"fatal"},FILE_UNREADABLE:{code:"AX-PROJECT-032",title:"File Could Not Be Read",description:"A file exists but could not be read \u2014 most often a permissions problem, a directory where a file was expected, or a disk error. Distinct from a missing file, which is an ordinary absent-surface state.",source:"manifest",severity:"fatal"},PROVIDER_NOT_CONNECTED:{code:"AX-TUI-011",title:"Provider Not Connected",description:"The selected model routes through a provider (OpenRouter, Codex) that isn't connected yet \u2014 connect it before picking a model on that route.",source:"tui",severity:"fatal",expected:!0},PALETTE_INPUT_REQUIRED:{code:"AX-TUI-012",title:"Required Input Missing",description:"A palette command needs a value for this field before it can run.",source:"tui",severity:"fatal",expected:!0},BENCH_NO_CASES:{code:"AX-TUI-013",title:"Bench Declared No Cases",description:"The bench's test file ran to completion under Bun but never declared a single benchmark case.",source:"tui",severity:"fatal"},TOOL_GLOBAL_COLLISION:{code:"AX-TOOL-409",title:"Tool Global Collides With A Builtin",description:"A flattened tool export has the same name as something that already exists in the agent's global scope, and replacing it would break the code around it. Reach this member through `axon.tools.<namespace>.<member>`, rename the export, or drop `flat` so the module lands under its own namespace instead.",source:"manifest",severity:"fatal",expected:!0},SCRIPT_FAILED:{code:"AX-SCRIPT-500",title:"Script Failed",description:"A script declared by this agent was invoked and threw. The agent's own error follows \u2014 this is the script's failure, not the runtime's.",source:"runtime",severity:"fatal",expected:!0},AGENT_SERVE_NO_PORT:{code:"AX-AGENT-503",title:"No Free Port",description:"The agent tried to bind its HTTP surface and every port in the range it walked was already in use. Free one, or pass a different port with --port.",source:"runtime",severity:"fatal",expected:!0},AGENT_NOT_FOUND:{code:"AX-AGENT-404",title:"Agent Not Found",description:"No local agent goes by this name. Agent references resolve against your local pools only \u2014 watched paths first, then installed agents \u2014 and never fetch from the registry. Install it first with `axon install`.",source:"manifest",severity:"fatal",expected:!0},AGENT_AMBIGUOUS:{code:"AX-AGENT-409",title:"Ambiguous Agent Name",description:"More than one local pool holds an agent with this name, and there is no correct way to guess which was meant \u2014 pass an explicit path, or unwatch one of the roots.",source:"manifest",severity:"fatal",expected:!0},PROJECT_NOT_FOUND:{code:"AX-PROJECT-017",title:"Project Not Found",description:"No axon.config.ts, module.config.ts, cognet.config.ts, bench.config.ts, or prompt.config.ts was found at this path \u2014 it isn't a recognized project directory.",source:"manifest",severity:"fatal",expected:!0},PROJECT_WRONG_KIND:{code:"AX-PROJECT-011",title:"Wrong Project Kind",description:"This command targets one project kind, and the directory holds another \u2014 run the command that matches what is actually here.",source:"manifest",severity:"fatal",expected:!0},PROJECT_EXISTS:{code:"AX-PROJECT-018",title:"Project Already Exists",description:"Scaffolding refused to overwrite a directory that already exists \u2014 remove it or pick a different name first.",source:"manifest",severity:"fatal"},TYPEGEN_NO_BLUEPRINT:{code:"AX-PROJECT-007",title:"Typegen Needs A Loaded Blueprint",description:"Agent-kind typegen was called without a blueprint \u2014 its declared surfaces are the source of the generated types.",source:"manifest",severity:"fatal"},DEPLOY_AGENTS_ONLY:{code:"AX-PROJECT-008",title:"Only Agents Can Deploy",description:"A module was asked to deploy on its own \u2014 modules only run installed inside an agent, deploy the agent instead.",source:"manifest",severity:"fatal"},BUNDLE_IMAGE_FAILED:{code:"AX-PROJECT-039",title:"Image Build Failed",description:"`docker build` did not succeed. Its own output is above \u2014 that is the real diagnostic. Check that a Docker daemon is running, and that the base image can be pulled.",source:"manifest",severity:"fatal",expected:!0},CONFIG_IMPORT_ESCAPES_ROOT:{code:"AX-PROJECT-038",title:"Config Imports Outside The Project",description:"axon.config.ts imports a file from outside this project's directory. A bundle contains the project and nothing above it, so that file is not published with it \u2014 the agent loads locally and then fails at boot in the cloud, after provisioning has already been paid for. Move what it needs inside the project, or publish it and import it by name.",source:"manifest",severity:"fatal",expected:!0},PUBLISH_NAMESPACE_DENIED:{code:"AX-PROJECT-036",title:"That Namespace Is Not Yours",description:"Publishing writes to a scope you own. This package is named for a scope owned by someone else, or by an org you are not a member of \u2014 rename it in package.json to a scope you own, or switch to the account that owns this one.",source:"cloud",severity:"fatal",expected:!0},PUBLISH_USERNAME_REQUIRED:{code:"AX-PROJECT-037",title:"A Username Is Required",description:"A username owns your registry namespace, and nothing can be published until one is set. It is set once, on the account, and every package you publish is scoped under it.",source:"cloud",severity:"fatal",expected:!0},PUBLISH_UNSUPPORTED_KIND:{code:"AX-PROJECT-009",title:"This Project Kind Cannot Publish",description:"The registry accepts agents, modules, cognets, benches and prompts. Extensions are not accepted yet \u2014 the `registry_artifact_kind` enum needs the value first, and publishing before then would register under the wrong kind and claim the name in the shared namespace. A profile is never publishable: it holds one person's credentials, history and agents. See KINDS[kind].publishable.",source:"manifest",severity:"fatal"},MODEL_SPECIFIER_INVALID:{code:"AX-MODEL-001",title:"Malformed Model Specifier",description:"A `models:` entry in cognet.config.ts could not be parsed. The short form is `hf:owner/repo/path/to/file` \u2014 a repo alone is ambiguous, since one repo holds many weights.",source:"manifest",severity:"fatal"},MODEL_FETCH_FAILED:{code:"AX-MODEL-002",title:"Model Weights Could Not Be Fetched",description:"A declared model could not be downloaded. Check the repo, file path and revision, and that the machine can reach the registry. A brain without its weights is broken rather than degraded, so this fails at prepare instead of at first inference.",source:"manifest",severity:"fatal"},MODEL_HASH_MISMATCH:{code:"AX-MODEL-003",title:"Model Weights Failed Verification",description:"Downloaded bytes did not hash to the expected value \u2014 the upstream file changed, or the download was corrupted. Nothing is cached: storing unverified weights would make every later run trust them.",source:"manifest",severity:"fatal"},MODEL_NOT_CACHED:{code:"AX-MODEL-004",title:"Declared Model Is Not Cached",description:"`--frozen` asserts the machine is already provisioned, so it will not fetch. Run `axon prepare` without --frozen to populate the model cache.",source:"manifest",severity:"fatal"},PREPARE_FROZEN_DRIFT:{code:"AX-PROJECT-014",title:"Dependencies Drifted From The Lockfile",description:"`--frozen` asserts that package.json, the lockfile and node_modules already agree. Something did not: a dependency is missing, at a version outside its declared range, or declared but no longer selected. Run `axon prepare` without --frozen to reconcile, and commit the result.",source:"manifest",severity:"fatal"},PUBLISH_VERIFY_FAILED:{code:"AX-PROJECT-013",title:"Artifact Does Not Compile",description:"The package was built, but compiling it the way a consumer would failed \u2014 so publishing it would ship something nobody can install. Usually a file the source imports was left out of the package. Published versions are immutable, so this is caught before upload rather than after.",source:"manifest",severity:"fatal"},DEPLOY_PROVISION_FAILED:{code:"AX-PROJECT-012",title:"Deployment Provisioning Failed",description:"The agent was published, but the cloud control plane could not provision its runtime. The request ID identifies the server-side failure.",source:"manifest",severity:"fatal"},DEPLOY_RUNTIME_FAILED:{code:"AX-PROJECT-035",title:"Agent Failed To Start",description:"Cloud infrastructure was provisioned, but the agent process failed during boot. The reported runtime diagnostic identifies the immediate cause.",source:"runtime",severity:"fatal"},DEPLOY_ENV_RESERVED:{code:"AX-PROJECT-043",title:"Reserved Deployment Variable",description:"The production .env file attempts to override a variable owned by the Axon runtime or Cloud Run.",source:"manifest",severity:"fatal"},DEPLOY_ENV_INVALID:{code:"AX-PROJECT-015",title:"Invalid Deployment Variable",description:"The production .env file contains a key that is not a valid environment variable name.",source:"manifest",severity:"fatal"},BUNDLE_MODULE_COLLISION:{code:"AX-PROJECT-019",title:"Module Name Collision",description:"A hard-imported source module's name collides with an already-installed registry module of the same name.",source:"manifest",severity:"fatal"},BUNDLE_INVALID:{code:"AX-PROJECT-010",title:"Invalid Bundle Source",description:"The directory being bundled has no package.json, or its package.json has no name \u2014 every bundle needs a real package identity.",source:"manifest",severity:"fatal"},BUNDLE_TAR_MISSING:{code:"AX-PROJECT-020",title:"tar Not Found",description:"Bundling shells out to the system's tar binary, which isn't on PATH \u2014 install Git for Windows or use WSL on that platform.",source:"manifest",severity:"fatal"},BUNDLE_TAR_FAILED:{code:"AX-PROJECT-021",title:"tar Failed",description:"The tar subprocess exited non-zero while building a bundle archive.",source:"manifest",severity:"fatal"},BENCH_RUN_NOT_FOUND:{code:"AX-BENCH-001",title:"Bench Run Not Found",description:"No recorded bench run exists with this id.",source:"bench",severity:"fatal",expected:!0},BENCH_NOT_FOUND:{code:"AX-BENCH-002",title:"Bench Not Found",description:"No bench.config.ts was found at this path \u2014 it isn't a recognized bench project.",source:"bench",severity:"fatal",expected:!0},BENCH_TESTS_NOT_FOUND:{code:"AX-BENCH-003",title:"Bench Test Files Not Found",description:"The bench config declares test files that don't exist on disk.",source:"bench",severity:"fatal",expected:!0},BENCH_LOCAL_REF_NOT_FOUND:{code:"AX-BENCH-004",title:"Bench Local Reference Not Found",description:"A factor variable references a local file/directory that doesn't exist.",source:"bench",severity:"fatal",expected:!0},BENCH_CONFIG_INVALID:{code:"AX-BENCH-005",title:"Bench Config Invalid",description:"bench.config.ts failed to evaluate or didn't produce a valid bench definition.",source:"bench",severity:"fatal"},BENCH_PACKAGE_NOT_FOUND:{code:"AX-BENCH-006",title:"Bench Package Not Found",description:"No package.json exists at the bench root \u2014 every bench project needs one for identity.",source:"bench",severity:"fatal",expected:!0},BENCH_PACKAGE_NAME_REQUIRED:{code:"AX-BENCH-007",title:"Bench Package Name Required",description:"The bench's package.json has no name field.",source:"bench",severity:"fatal",expected:!0},BENCH_PACKAGE_VERSION_REQUIRED:{code:"AX-BENCH-008",title:"Bench Package Version Required",description:"The bench's package.json has no version field.",source:"bench",severity:"fatal",expected:!0},BENCH_CONTEXT_MISSING:{code:"AX-BENCH-009",title:"Bench Context Missing",description:"The benchmark preload needs AXON_BENCH_CONTEXT set \u2014 it was run outside the bench harness.",source:"bench",severity:"fatal"},BENCH_NO_ACTIVE_CASE:{code:"AX-BENCH-010",title:"No Active Bench Case",description:"A bench emission (measurement, artifact) happened outside any running Bun test \u2014 these calls must occur inside a test case.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_UNAVAILABLE:{code:"AX-BENCH-011",title:"Bench Workspace Unavailable",description:"The bench's workspace directory hasn't been materialized yet for this run.",source:"bench",severity:"fatal"},BENCH_AGENT_UNRESOLVED:{code:"AX-BENCH-012",title:"Bench Agent Unresolved",description:"The bench's declared subject agent isn't a prepared local agent \u2014 run `axon prepare` on it first.",source:"bench",severity:"fatal"},BENCH_MEASUREMENT_UNKNOWN:{code:"AX-BENCH-013",title:"Unknown Bench Measurement",description:"A measurement was emitted under an id the bench config never declared.",source:"bench",severity:"fatal"},BENCH_MEASUREMENT_TYPE:{code:"AX-BENCH-014",title:"Bench Measurement Type Mismatch",description:"A measurement's emitted value doesn't match the type its bench config declaration expects.",source:"bench",severity:"fatal"},BENCH_MEASUREMENT_DOMAIN:{code:"AX-BENCH-015",title:"Bench Measurement Out Of Domain",description:"A measurement's emitted value falls outside the range or category the bench config declares for it.",source:"bench",severity:"fatal"},BENCH_DIMENSION_UNKNOWN:{code:"AX-BENCH-016",title:"Unknown Bench Dimension",description:"A dimension value was set under an id the bench config never declared.",source:"bench",severity:"fatal"},BENCH_DIMENSION_DOMAIN:{code:"AX-BENCH-017",title:"Bench Dimension Out Of Domain",description:"A dimension's set value isn't one of the categories its bench config declares.",source:"bench",severity:"fatal"},BENCH_AXIS_UNKNOWN:{code:"AX-BENCH-018",title:"Unknown Bench Factor",description:"Something referenced a factor id the running bench's coordinate never assigned a value to.",source:"bench",severity:"fatal"},BENCH_ARTIFACT_UNKNOWN:{code:"AX-BENCH-019",title:"Unknown Bench Artifact",description:"An artifact was emitted under an id the bench config never declared.",source:"bench",severity:"fatal"},BENCH_ARTIFACT_MEDIA_TYPE:{code:"AX-BENCH-020",title:"Bench Artifact Media Type Not Allowed",description:"An artifact was emitted with a media type its bench config declaration doesn't allow.",source:"bench",severity:"fatal"},BENCH_SCHEMA_UNREADABLE:{code:"AX-BENCH-030",title:"Bench Schema Unreadable",description:"bench.config.ts could not be parsed while extracting the measurement schema.",source:"bench",severity:"fatal"},BENCH_SCHEMA_EMPTY:{code:"AX-BENCH-031",title:"Bench Schema Empty",description:"defineBench<Schema> was given a type with no properties \u2014 an empty schema and a failed extraction must never look alike.",source:"bench",severity:"fatal"},BENCH_SCHEMA_UNSUPPORTED_TYPE:{code:"AX-BENCH-032",title:"Bench Measurement Type Unsupported",description:"A measurement is not a boolean, number, union of string literals, or string.",source:"bench",severity:"fatal"},BENCH_SCHEMA_EXTRACTION_FAILED:{code:"AX-BENCH-033",title:"Bench Schema Extraction Failed",description:"The schema worker did not return a schema. Prepare fails rather than continuing with an empty one, which would silently make every measurement undeclared.",source:"bench",severity:"fatal"},BENCH_AXIS_NOT_FOUND:{code:"AX-BENCH-021",title:"Bench Axis Not Found",description:"The bench config's matrix has no axis with this key.",source:"bench",severity:"fatal",expected:!0},BENCH_AXIS_VALUE_NOT_FOUND:{code:"AX-BENCH-022",title:"Bench Axis Value Not Found",description:"The bench config's matrix axis has no declared value with this id.",source:"bench",severity:"fatal",expected:!0},BENCH_WORKSPACE_ESCAPE:{code:"AX-BENCH-023",title:"Bench Workspace Path Escapes Root",description:"A workspace source entry resolved to a path outside the workspace directory \u2014 refused rather than materialized.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_SYMLINK_UNSUPPORTED:{code:"AX-BENCH-024",title:"Bench Workspace Symlinks Unsupported",description:"A workspace source contains a symlink \u2014 not supported when materializing a bench workspace.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_OUTSIDE_ROOT:{code:"AX-BENCH-025",title:"Bench Template Outside Root",description:"A workspace template's declared source path resolves outside the bench project root.",source:"bench",severity:"fatal"},BENCH_WORKSPACE_SOURCE_NOT_FOUND:{code:"AX-BENCH-026",title:"Bench Template Not Found",description:"A workspace template's declared source path isn't a real directory.",source:"bench",severity:"fatal",expected:!0},BENCH_LOG_INVALID:{code:"AX-BENCH-027",title:"Bench Log Invalid",description:"A bench run's event log is missing an entry its projection requires \u2014 the log is incomplete or was written out of order.",source:"bench",severity:"fatal"},TOOL_DECLARE_FAILED:{code:"AX-BLUEPRINT-002",title:"Tool Declaration Failed",description:"Compiling a src/tools/*.ts file's TypeScript declarations failed \u2014 the worker subprocess reported a compile error.",source:"manifest",severity:"fatal"},TOOL_BUNDLE_FAILED:{code:"AX-BLUEPRINT-006",title:"Tool Bundle Failed",description:"Bundling a src/tools/*.ts file to self-contained source failed \u2014 the bundler subprocess reported an error. Tools are bundled so the sandbox loads them without mounting the project; a bundle failure means the tool cannot enter the box.",source:"manifest",severity:"fatal"},ROUTE_LOAD_FAILED:{code:"AX-BLUEPRINT-007",title:"Route Load Failed",description:"A file in server/api/ could not be imported. The agent would serve an endpoint set that is not the declared one \u2014 a caller gets a 404 for a route whose file exists.",source:"manifest",severity:"fatal"},SCRIPT_LOAD_FAILED:{code:"AX-BLUEPRINT-008",title:"Script Load Failed",description:"A file in src/scripts/ could not be processed. `axon run <name>` would report the script as not found while its file sits in the project.",source:"manifest",severity:"fatal"},PLUGIN_LOAD_FAILED:{code:"AX-BLUEPRINT-009",title:"Plugin Load Failed",description:"A plugin could not be imported. Plugins wire server behaviour at boot; one silently missing means the agent runs without behaviour its author declared.",source:"manifest",severity:"fatal"},MIDDLEWARE_LOAD_FAILED:{code:"AX-BLUEPRINT-010",title:"Middleware Load Failed",description:"A middleware file could not be imported. Middleware commonly carries auth and validation, so a silently skipped one is a request path running without the checks its author wrote.",source:"manifest",severity:"fatal"},PROMPT_INTROSPECT_FAILED:{code:"AX-BLUEPRINT-011",title:"Prompt Introspection Failed",description:"A .vue prompt could not be introspected for its props. The prompt would render without the inputs it declares, or not at all.",source:"manifest",severity:"fatal"},CONFIG_NOT_FOUND:{code:"AX-BLUEPRINT-003",title:"Config Not Found",description:"No axon.config.ts exists at this path.",source:"manifest",severity:"fatal",expected:!0},CONFIG_LOAD_FAILED:{code:"AX-BLUEPRINT-004",title:"Config Failed To Load",description:"axon.config.ts threw or failed to evaluate \u2014 check the file for a syntax or runtime error.",source:"manifest",severity:"fatal"},CONFIG_INVALID:{code:"AX-BLUEPRINT-005",title:"Config Invalid",description:"axon.config.ts evaluated but never called defineAgent() \u2014 every agent config must produce one.",source:"manifest",severity:"fatal"},ENGINE_NO_DONE:{code:"AX-KERNEL-001",title:"Engine Stream Ended Without Completing",description:"The model driver's stream ended without ever emitting a completion event \u2014 the engine likely disconnected or crashed mid-response.",source:"kernel",severity:"fatal"},ENGINE_NOT_CONNECTED:{code:"AX-KERNEL-015",title:"Provider Not Connected",description:"This model's route is not connected to your account yet \u2014 run `:provider <name> connect` for the provider named below, or pick a model on a route you are already signed in to.",source:"kernel",severity:"fatal",expected:!0},ENGINE_AUTH_FAILED:{code:"AX-KERNEL-016",title:"Provider Rejected Your Credentials",description:"The provider refused the credential this agent is using \u2014 it has expired, been revoked, or is for a different account. Reconnect the provider, or pick a model on a route you are signed in to.",source:"kernel",severity:"fatal",expected:!0},ENGINE_RATE_LIMITED:{code:"AX-KERNEL-017",title:"Provider Rate Limit Reached",description:"The provider is refusing further calls right now \u2014 either too many requests in a short window, or a subscription whose allowance is spent. Waiting usually clears the first; the second needs a plan change or a different model.",source:"kernel",severity:"fatal",expected:!0},ENGINE_QUOTA_EXHAUSTED:{code:"AX-KERNEL-018",title:"Provider Credits Exhausted",description:"This route has no credit left to spend. Top it up, or switch to a model on a route that does \u2014 the conversation is intact either way.",source:"kernel",severity:"fatal",expected:!0},ENGINE_REQUEST_REJECTED:{code:"AX-KERNEL-019",title:"Provider Rejected The Request",description:"The provider refused this call as malformed or unsupported \u2014 commonly a model id it does not serve, a context window this conversation has outgrown, or a parameter that route does not accept.",source:"kernel",severity:"fatal",expected:!0},ENGINE_UNREACHABLE:{code:"AX-KERNEL-020",title:"Could Not Reach The Provider",description:"The provider could not be reached, or kept failing, across every retry \u2014 usually a network problem on this machine or an outage on their side. Nothing about this agent needs changing; try again.",source:"kernel",severity:"fatal",expected:!0},ENGINE_STREAM_FAILED:{code:"AX-KERNEL-008",title:"Engine Stream Failed",description:"The model driver's stream failed and exhausted its retries (or the failure wasn't retryable) \u2014 see context for the provider's fault code.",source:"kernel",severity:"fatal"},CODEX_NOT_CONNECTED:{code:"AX-KERNEL-012",title:"Codex Subscription Not Connected",description:"This agent uses a Codex model, but your Axon account is not connected to ChatGPT \u2014 run :provider codex connect and try again.",source:"kernel",severity:"fatal",expected:!0},RUN_IN_PROGRESS:{code:"AX-KERNEL-002",title:"A Wake Is Already Running",description:"The kernel only executes one wake at a time \u2014 a new run was requested while the previous one was still active.",source:"kernel",severity:"recovered"},RUN_RESERVATION_EXPIRED:{code:"AX-KERNEL-003",title:"Wake Reservation Expired",description:"The reserved execution slot for this wake is no longer active \u2014 it was released before the run could start.",source:"kernel",severity:"fatal"},NO_COGNET_LOADED:{code:"AX-KERNEL-004",title:"No Cognet Loaded",description:"The kernel tried to execute a wake, but the blueprint carried no cognet definition to run it against.",source:"kernel",severity:"fatal"},SYSCALL_OUTSIDE_RUN:{code:"AX-KERNEL-005",title:"Syscall Outside An Active Run",description:"A kernel syscall (engine.stream and similar) was made with no active wake to attribute it to.",source:"kernel",severity:"fatal"},CAPSULE_ACCESSED_BEFORE_BOOT:{code:"AX-KERNEL-007",title:"Capsule Accessed Before Boot",description:"Something reached for the live capsule instance before boot() had run \u2014 there is no sandbox yet to hand back.",source:"kernel",severity:"fatal"},COGNET_EMIT_FORBIDDEN:{code:"AX-KERNEL-009",title:"Cognet Emit Forbidden",description:"A cognet tried to emit an event outside the cognet:* namespace \u2014 the ABI only lets a cognet narrate its own telemetry, never forge kernel machinery events.",source:"kernel",severity:"fatal"},KNOWLEDGE_NOT_FOUND:{code:"AX-KERNEL-011",title:"Knowledge Entry Not Found",description:"A cognet read a knowledge entry that does not exist. The knowledge store is not a cache \u2014 a brain reading something the catalogue advertised has hit a real inconsistency, so this is loud rather than an empty result.",source:"kernel",severity:"fatal",expected:!0},KNOWLEDGE_READONLY:{code:"AX-KERNEL-013",title:"Knowledge Entry Is Read-Only",description:"A cognet tried to write or remove knowledge contributed by a module. Module material lives inside its own package and the next install would destroy any change \u2014 so this fails loudly rather than succeeding and vanishing later. An agent's own data/knowledge/ is writable.",source:"kernel",severity:"fatal",expected:!0},KNOWLEDGE_RECORD_FAILED:{code:"AX-KERNEL-014",title:"Knowledge Mutation Went Unrecorded",description:"A knowledge write or remove succeeded on disk, but the session record of it could not be committed. The mutation is real and already visible to the agent; only its audit trail is missing, so this is reported rather than thrown \u2014 the caller cannot undo a completed write. It matters because 'the agent rewrote its own memory' is the fact you want weeks later when behaviour drifts, and here the ledger and the filesystem disagree.",source:"kernel",severity:"degraded"},KNOWLEDGE_ESCAPE:{code:"AX-KERNEL-021",title:"Knowledge Path Escapes Store",description:"A knowledge name resolved outside the store root. Names are identifiers, not paths \u2014 traversal is refused at the boundary rather than trusted not to happen.",source:"kernel",severity:"fatal"},SCHEDULER_MODE_MISMATCH:{code:"AX-KERNEL-010",title:"Scheduler Mode Mismatch",description:"A caller used the wrong wake verb for the cognet's mode: continuous cognets advance via tick(), driven by the body's clock; invocation cognets wake on a stimulus via request()/stream().",source:"kernel",severity:"fatal"},THREAD_UNKNOWN_PARENT:{code:"AX-SESSION-001",title:"Thread Branched From Unknown Parent",description:"A thread's recorded lineage points at a parent thread id that isn't registered in this session \u2014 the session index is inconsistent.",source:"thread",severity:"fatal"},THREAD_NOT_FOUND:{code:"AX-SESSION-002",title:"Thread Not Found",description:"The requested thread id isn't registered in this session.",source:"thread",severity:"fatal",expected:!0},THREAD_BRANCH_UNKNOWN:{code:"AX-SESSION-003",title:"Cannot Branch Unknown Thread",description:"A branch was requested from a parent thread id that isn't registered in this session.",source:"thread",severity:"fatal"},SENSORY_WRITE_FAILED:{code:"AX-SESSION-004",title:"Sensory Ring Write Failed",description:"A dense sense entry (audio or visual) could not be written to the session's sensory ring \u2014 usually a full or read-only data directory. Delivery to the cognet is unaffected; the debug window for this session will have a gap.",source:"runtime",severity:"degraded"},NO_COGNET:{code:"AX-BLUEPRINT-001",title:"No Cognet Declared",description:"The blueprint carries no cognet definition \u2014 an agent cannot run without a brain. The CLI or test harness must construct and pass one.",source:"runtime",severity:"fatal"},CONTROL_PATH_NOT_FOUND:{code:"AX-CONTROL-001",title:"Control Path Not Found",description:"A control-channel call named a method the peer does not expose. The two ends disagree about the surface \u2014 usually a TUI and an extension built from different versions.",source:"server",severity:"fatal",expected:!0},CONTROL_PATH_NOT_CALLABLE:{code:"AX-CONTROL-002",title:"Control Path Not Callable",description:"A control-channel call resolved to a value on the peer's handle that is not a function.",source:"server",severity:"fatal"},CONTROL_CALL_FAILED:{code:"AX-CONTROL-003",title:"Control Call Failed",description:"The peer served a control-channel call and it threw. The remote message is carried here \u2014 the failure surfaces at the local call site rather than being returned as a falsy value.",source:"server",severity:"fatal"},CONTROL_CLOSED:{code:"AX-CONTROL-004",title:"Control Channel Closed",description:"A control-channel call was made, or was still in flight, when the channel closed. In-flight calls reject on close rather than hanging forever on an answer that is no longer coming.",source:"server",severity:"fatal"},CONTROL_UNAUTHORIZED:{code:"AX-CONTROL-005",title:"Control Handshake Rejected",description:"A connection to the control socket presented a missing or incorrect token. The token lives in the instance record, which is readable only by the owning user \u2014 a mismatch means the caller is not the local Fleet extension.",source:"server",severity:"fatal"},PLUGIN_BOOT_FAILED:{code:"AX-SERVER-001",title:"Plugin Failed During Boot",description:"A server plugin threw while running at boot \u2014 plugins are the one place in server startup where a failure must abort the boot rather than being warned and skipped.",source:"server",severity:"fatal"},HANDLE_SHUTDOWN_FAILED:{code:"AX-RUNTIME-002",title:"Handle Failed To Shut Down",description:"One of the runtime's owned handles (kernel, etc.) threw during shutdown \u2014 teardown is error-isolated, so the others still ran, but this one didn't close cleanly.",source:"runtime",severity:"fatal"},BUS_HANDLER_FAILED:{code:"AX-RUNTIME-004",title:"Bus Handler Failed",description:"A handler subscribed to a runtime bus event threw. Handler failures are non-fatal by design \u2014 the remaining handlers still run \u2014 but they are recorded rather than swallowed, since plugins and modules register handlers and a silently-broken one is invisible rot.",source:"runtime",severity:"degraded"},TOOL_CALL_FAILED:{code:"AX-RUNTIME-003",title:"Tool Call Failed",description:"An axon.tools.<namespace>.<fn>() call from script-land completed with a non-ok result from the capsule \u2014 unwrapped here into a normal throw, since script-land expects the ordinary call/throw contract, not the kernel's own stable-result shape.",source:"runtime",severity:"fatal"},CAPSULE_TOOL_TIMEOUT:{code:"AX-CAPSULE-001",title:"Tool Load Timed Out",description:"The sandbox never confirmed loading a declared tool within the timeout \u2014 it may be stuck on a slow import or the subprocess is unresponsive.",source:"capsule",severity:"fatal"},CAPSULE_TOOL_SCOPE_MISMATCH:{code:"AX-CAPSULE-002",title:"Tool Scope Mismatch",description:"A tool's declared exports don't match what it actually exported once loaded in the sandbox \u2014 the bundled source and its declaration have drifted apart.",source:"capsule",severity:"fatal"},CAPSULE_TOOL_FAILED:{code:"AX-CAPSULE-003",title:"Tool Failed To Load",description:"A declared tool failed to load into the sandbox \u2014 its source may be malformed, too large to import, or the subprocess exited before confirming.",source:"capsule",severity:"fatal"},AGENT_ENV_RESERVED:{code:"AX-CAPSULE-012",title:"Reserved Environment Variable",description:"An agent's .env sets a framework-owned variable the runtime controls (AGENT_ID, AXON_API_BASE and similar). These identify the agent to the platform, so overriding one locally would make the agent report itself as something it is not. The deploy path has always refused this; the local path now refuses it identically.",source:"capsule",severity:"fatal"},CAPSULE_NET_UNRESOLVED:{code:"AX-CAPSULE-010",title:"Network Policy Did Not Resolve",description:"A `net.allow` entry names a hostname that did not resolve to any address. Egress rules are installed as addresses, so an unresolvable name becomes no rule at all \u2014 a grant you believe you made and did not. The box refuses to boot rather than run with an allowlist quietly smaller than the one you wrote. Check the hostname, or use a literal address if the name is resolvable only from inside the box.",source:"capsule",severity:"fatal"},CAPSULE_NET_UNAVAILABLE:{code:"AX-CAPSULE-011",title:"Network Confinement Unavailable",description:"The policy declares a `net` allowlist, which needs a userspace network stack (slirp4netns) and nftables inside the box's namespace. One of them is missing on this host. Install slirp4netns and nftables, or drop the `net` block to run with no network at all \u2014 the box will not fall back to unfiltered egress.",source:"capsule",severity:"fatal"},CAPSULE_CONFINE_UNAVAILABLE:{code:"AX-CAPSULE-004",title:"OS Confinement Unavailable",description:"The policy requested OS confinement (isolation: auto) but the host is missing a required primitive (bubblewrap, systemd, nft, or the axon-agent user). Run `axon install`, or set isolation: none to opt out explicitly. The capsule refuses to boot rather than silently run unconfined.",source:"capsule",severity:"fatal"},CAPSULE_CONFINE_USER_UNRESOLVED:{code:"AX-CAPSULE-005",title:"Confinement User Unresolved",description:"The confinement user exists but its numeric uid/gid could not be read \u2014 the box cannot drop privileges without them. The host user database may be inconsistent.",source:"capsule",severity:"fatal"},CAPSULE_BOOT_FAILED:{code:"AX-CAPSULE-006",title:"Capsule Failed To Boot",description:"The sandbox subprocess exited or reported failure before completing the boot handshake. The captured stderr in the error context is the real cause \u2014 most often a confinement mount that could not be satisfied (a declared fs path that does not exist) or a runtime that could not start.",source:"capsule",severity:"fatal"},CAPSULE_BOOT_TIMEOUT:{code:"AX-CAPSULE-007",title:"Capsule Boot Timed Out",description:"The sandbox subprocess did not report ready within the boot timeout. Its captured stderr is in the error context; if empty, the subprocess may be hung rather than crashed.",source:"capsule",severity:"fatal"},CAPSULE_SPAWN_FAILED:{code:"AX-CAPSULE-008",title:"Capsule Spawn Failed",description:"The capsule subprocess command could not be spawned at all \u2014 the interpreter or confinement wrapper was not found, or PATH is unset. Check that bun (and, under confinement, bwrap/systemd-run) are on PATH.",source:"capsule",severity:"fatal"},CAPSULE_WIRE_CLOSED:{code:"AX-CAPSULE-009",title:"Capsule Wire Closed",description:"A command was sent to the sandbox after its stdin pipe was gone \u2014 the subprocess has exited or is mid-teardown. The caller is racing the capsule lifecycle.",source:"capsule",severity:"fatal"},CAPSULE_DOWN:{code:"AX-CAPSULE-023",title:"No Live Capsule",description:"An operation needed a running sandbox subprocess, but none is live \u2014 it is booting, restarting after a crash, or has been declared dead.",source:"capsule",severity:"fatal"},CAPSULE_ALREADY_BOOTED:{code:"AX-CAPSULE-024",title:"Capsule Already Booted",description:"boot() was called on a capsule that already has a live subprocess. Boot is once per lifetime; use update()/reload() to replace a running incarnation.",source:"capsule",severity:"fatal"},CAPSULE_INSTALL_FAILED:{code:"AX-CAPSULE-013",title:"Confinement Install Failed",description:"Provisioning the host for the hardened confinement tier failed \u2014 most often because creating the dedicated system user needs root. Re-run `axon install` with sufficient privilege.",source:"capsule",severity:"fatal"},CAPSULE_HOST_UNAVAILABLE:{code:"AX-CAPSULE-014",title:"Host Bridge Unavailable",description:"Sandboxed code called a host service, but this capsule was built with no host provider. Host calls require a wired host bridge on the manager side.",source:"capsule",severity:"fatal"},CAPSULE_CRASHED:{code:"AX-CAPSULE-015",title:"Capsule Crashed",description:"An unhandled error escaped inside the sandbox subprocess. The capsule reports it on the wire and exits immediately \u2014 after an unhandled throw the sandbox's state is unknown, and a capsule that keeps serving is worse than one that dies loudly.",source:"capsule",severity:"fatal"},CAPSULE_DEAD:{code:"AX-CAPSULE-016",title:"Capsule Dead",description:"The capsule subprocess is gone and supervision gave up restarting it. Every subsequent execution request fails until a new capsule is booted.",source:"capsule",severity:"fatal"},CAPSULE_PARSE_ERROR:{code:"AX-CAPSULE-017",title:"Capsule Wire Parse Error",description:"A line arriving from the sandbox was not a valid protocol event. The sandbox is speaking garbage \u2014 a protocol mismatch or corrupted output \u2014 and the line is dropped rather than acted on, never silently.",source:"capsule",severity:"degraded"},CAPSULE_CMD_FAILED:{code:"AX-CAPSULE-018",title:"Capsule Command Failed",description:"Code executed in the sandbox threw. This is the ordinary failure path for an agent-emitted block or a script-land run() \u2014 the error is the sandboxed code's own, surfaced verbatim.",source:"capsule",severity:"degraded"},CAPSULE_FN_FAILED:{code:"AX-CAPSULE-019",title:"Tool Call Threw",description:"A mediated tool function threw inside the sandbox. The failure is the tool's own; it propagates to the calling code unchanged and is recorded as the closing half of the call's span.",source:"capsule",severity:"degraded"},CAPSULE_PROC_DENIED:{code:"AX-CAPSULE-020",title:"Process Spawn Denied",description:"A process the sandbox tried to start was refused \u2014 denied by policy, killed before it could spawn, or the spawn itself failed. No process was created.",source:"capsule",severity:"degraded"},CAPSULE_PROC_FAILED:{code:"AX-CAPSULE-022",title:"Managed Process Failed",description:"A spawned child process errored without ever producing an exit code \u2014 an exec failure or a broken IPC channel. Distinct from a non-zero exit, which is the process running correctly and reporting a result.",source:"capsule",severity:"degraded"},CAPSULE_PROC_STDIN_FAILED:{code:"AX-CAPSULE-021",title:"Process Stdin Write Failed",description:"Writing to a managed child process's stdin failed \u2014 the process is no longer running, or its stdin has already closed.",source:"capsule",severity:"degraded"},NOT_BOOTED:{code:"AX-TUI-001",title:"No Agent Running",description:"A message was sent, or an action requiring a live agent was taken, before any agent finished booting.",source:"tui",severity:"fatal"},NOT_AUTHENTICATED:{code:"AX-TUI-002",title:"Not Logged In",description:"The action needs an active profile, but none is logged in yet.",source:"tui",severity:"fatal",expected:!0},PROFILE_NOT_AUTHENTICATED:{code:"AX-TUI-003",title:"Profile Has No Session",description:"The target profile exists but has no stored session \u2014 it has never logged in, or its session was cleared.",source:"tui",severity:"fatal",expected:!0},BACKEND_UNREACHABLE:{code:"AX-TUI-044",title:"Backend Unreachable",description:"A stored credential could not be verified because the backend could not be reached. The credential is NOT discarded \u2014 it may be perfectly valid \u2014 but it cannot be trusted until it is checked, so the action is refused rather than proceeding unverified.",source:"tui",severity:"fatal",expected:!0},PROFILE_UNKNOWN:{code:"AX-TUI-004",title:"Unknown Profile",description:"The requested profile id isn't one of the profiles stored on this machine.",source:"tui",severity:"fatal",expected:!0},SESSION_NOT_FOUND:{code:"AX-SESSION-005",title:"Session Not Found",description:"No session log exists at that path. A session is a .jsonl file under the agent's frame (`.agent/data/sessions/`); it may have been deleted, or belong to an agent that has since been removed.",source:"runtime",severity:"fatal",expected:!0},SESSION_UNREADABLE:{code:"AX-SESSION-006",title:"Session Log Unreadable",description:"The session log does not begin with a `session:header` line, so it cannot be forked or renamed. Either the file is truncated, or it was written by a version predating the header \u2014 an older log can still be read and resumed, just not copied.",source:"runtime",severity:"fatal",expected:!0},SESSION_ALREADY_RUNNING:{code:"AX-TUI-005",title:"Session Is Already Running",description:"spawn() was asked to resume a session that already has a live instance. Focus the running instance instead of booting a second runtime over the same log.",source:"tui",severity:"fatal",expected:!0},SESSION_NOT_RUNNING:{code:"AX-TUI-016",title:"Session Is Not Running",description:"focus() was pointed at a sessionId with no live instance behind it. Spawn (or resume) it first \u2014 focus is pure selection over running instances.",source:"tui",severity:"fatal",expected:!0},NO_ACTIVE_AGENT:{code:"AX-TUI-045",title:"No Active Agent",description:"The action needs a running agent, but none is active \u2014 start one first.",source:"tui",severity:"fatal",expected:!0},NO_LOCAL_PROJECT:{code:"AX-TUI-050",title:"No Local Project",description:"This agent has no project directory on this machine \u2014 it was attached over the network, so its source lives wherever it is running. Opening its config, or any other file verb, has to happen there. Focus a local agent instead.",source:"tui",severity:"fatal",expected:!0},NO_FOCUSED_INSTANCE:{code:"AX-TUI-017",title:"No Focused Agent Instance",description:"A module install/uninstall was requested with no running agent instance focused \u2014 spawn or focus one first.",source:"tui",severity:"fatal",expected:!0},MODEL_UNAVAILABLE:{code:"AX-TUI-051",title:"Model Not Available From Any Declared Provider",description:"The picked model was saved to the agent's config, but no provider this profile declares can supply it \u2014 so the running agent still uses its previous model. Connect the provider that serves it, or pick a model from the offered list.",source:"tui",severity:"fatal",expected:!0},MODEL_IMMUTABLE_DEPLOYED:{code:"AX-TUI-006",title:"Cannot Change A Deployment's Model",description:"A deployed agent's config lives in the cloud, not on this machine \u2014 its model is fixed at deploy time. Change it in the local project and deploy again.",source:"tui",severity:"fatal",expected:!0},MODULE_INSTALL_FAILED:{code:"AX-TUI-018",title:"Module Install Failed",description:"The registry installer returned an error for this module specifier \u2014 check the specifier and registry connectivity.",source:"tui",severity:"fatal"},NO_MODULES_INSTALLED:{code:"AX-TUI-019",title:"No Modules Installed",description:"The `:module uninstall` command was opened with no modules resolved into the focused instance's blueprint.",source:"tui",severity:"fatal"},SETTINGS_NOT_WRITABLE:{code:"AX-EXT-027",title:"Settings Cannot Be Written",description:"A settings change was requested on a store with no profile config behind it \u2014 nobody is logged in, or this Store was built without one (tests). Settings live in `profile.config.ts`, so there is nowhere to write them; the change was refused rather than saved somewhere nothing reads back.",source:"tui",severity:"fatal",expected:!0},REGISTRY_EMPTY:{code:"AX-TUI-047",title:"Nothing To Install",description:"The install palette was opened with no rows to show \u2014 the catalogue is still loading, the registry could not be reached, or everything published for that kind is already installed. The row itself says which.",source:"tui",severity:"fatal",expected:!0},NO_EXTENSIONS_INSTALLED:{code:"AX-TUI-046",title:"No Extensions Installed",description:"The `:ext uninstall` command was opened with no extensions declared in the active profile's profile.config.ts.",source:"tui",severity:"fatal",expected:!0},ATTACH_URL_REQUIRED:{code:"AX-TUI-048",title:"Attach URL Required",description:"`:attach` needs the address of a running agent \u2014 e.g. `:attach http://localhost:3010`. The agent must already be serving; attach binds to it and never boots anything.",source:"tui",severity:"fatal"},AGENT_NAME_REQUIRED:{code:"AX-CLI-001",title:"A Name Is Required",description:"Scaffolding a project needs a name \u2014 it becomes the directory and the package name.",source:"cli",severity:"fatal",expected:!0},MODULE_SPECIFIER_REQUIRED:{code:"AX-CLI-002",title:"A Module Name Is Required",description:"The command needs at least one module to act on, named as a scoped registry package.",source:"cli",severity:"fatal",expected:!0},FLAG_VALUE_REQUIRED:{code:"AX-CLI-007",title:"A Flag Is Missing Its Value",description:"The flag takes a value and none followed it. Quote the value if it contains spaces, and check it was not consumed as another flag.",source:"cli",severity:"fatal",expected:!0},RUN_INSTRUCTION_REQUIRED:{code:"AX-CLI-006",title:"Nothing To Run",description:"The agent was named but not told what to do. A reference on its own opens the terminal on that agent; giving it work needs an instruction, a declared prompt, or a script.",source:"cli",severity:"fatal",expected:!0},BENCH_RUN_ID_REQUIRED:{code:"AX-CLI-003",title:"A Run Id Is Required",description:"Reading a benchmark result needs the id of the run to read.",source:"cli",severity:"fatal",expected:!0},PROFILE_INCOMPLETE:{code:"AX-CLI-004",title:"Profile Is Missing Its Identity",description:"Credentials are stored for this profile but no identity is, so there is nothing to report. Logging out and back in rewrites both.",source:"cli",severity:"fatal",expected:!0},BUNDLE_KIND_MISMATCH:{code:"AX-CLI-005",title:"Wrong Bundle Kind",description:"The bundler produced an artifact of a different kind than the command expected. This is a wiring fault in our own code, not something a project can cause.",source:"cli",severity:"fatal"},ATTACH_UNREACHABLE:{code:"AX-TUI-052",title:"Agent Not Reachable",description:"Nothing answered at that address. The agent may not be running, may be on a different port, or may be behind something that refused the connection. `axon dev` prints the address it bound to.",source:"tui",severity:"fatal",expected:!0},ATTACH_URL_INVALID:{code:"AX-TUI-049",title:"Attach URL Invalid",description:"The address is not a usable agent URL. An agent is reached over http or https and the scheme is required \u2014 `localhost:3010` is a path, `http://localhost:3010` is an address. Checked before anything connects, so a typo fails immediately rather than as a transport error.",source:"tui",severity:"fatal"},DEPLOYMENT_NOT_CONNECTABLE:{code:"AX-TUI-028",title:"Deployment Not Connectable",description:"The deployment is not in the connectable list \u2014 it may have stopped, errored, or never finished provisioning. Refresh the deployment list and try again.",source:"tui",severity:"fatal"},SUBAGENT_REMOTE_PARENT:{code:"AX-TUI-027",title:"Cannot Spawn A Subagent From A Deployment",description:"A subagent is forked from its parent's local project, and an attached deployment has no local project here \u2014 the deployed agent runs its own subagents inside its own capsule.",source:"tui",severity:"fatal"},BASE_MODEL_INSTANCE_CONFLICT:{code:"AX-TUI-026",title:"Managed Model Instance Already Running",description:"A managed base instance is already running on a different engine. The base workspace holds one shared config, so spawning a second naked model would rewrite it underneath the live instance \u2014 close the running one first.",source:"tui",severity:"fatal"},NOT_WIRED:{code:"AX-TUI-008",title:"Not Wired Yet",description:"This surface is a declared stub \u2014 the real implementation hasn't been built yet.",source:"tui",severity:"fatal"},MIC_ALREADY_CAPTURING:{code:"AX-TUI-009",title:"Mic Already Capturing",description:"capture.start() was called while a capture was already in progress \u2014 stop the current one first.",source:"tui",severity:"fatal"},MIC_CAPTURE_UNAVAILABLE:{code:"AX-TUI-010",title:"No Audio Capture Tool Found",description:"Voice input needs one of arecord, sox, or ffmpeg installed and on PATH.",source:"tui",severity:"fatal"},MIC_FFT_SIZE_MISMATCH:{code:"AX-TUI-014",title:"FFT Sample Size Mismatch",description:"computeBuckets() was called with a sample buffer that isn't exactly config.fftSize long \u2014 an internal invariant, callers must pad/trim first.",source:"tui",severity:"fatal"},MIC_CAPTURE_FAILED:{code:"AX-TUI-015",title:"Mic Capture Failed",description:"The audio capture subprocess produced no output or exited immediately \u2014 check that a microphone is available.",source:"tui",severity:"fatal"},WATCH_PATH_REQUIRED:{code:"AX-TUI-021",title:"Watch Path Required",description:"`axon watch`/`axon unwatch` need a directory argument.",source:"tui",severity:"fatal",expected:!0},WATCH_PATH_NOT_FOUND:{code:"AX-TUI-022",title:"Watch Path Not Found",description:"`axon watch` was given a directory that doesn't exist on disk.",source:"tui",severity:"fatal",expected:!0},EDITOR_NOT_SET:{code:"AX-TUI-023",title:"No Editor Configured",description:"`axon settings` needs the $EDITOR environment variable set to know which editor to open.",source:"tui",severity:"fatal"},EDITOR_LAUNCH_FAILED:{code:"AX-TUI-024",title:"Editor Failed To Launch",description:"The command in $EDITOR could not be spawned \u2014 check that it's installed and on PATH.",source:"tui",severity:"fatal"},WATCH_AND_INIT_ARGS_REQUIRED:{code:"AX-TUI-025",title:"Directory And Name Required",description:`The init palette's "watch a new directory" entry needs both a directory path and an agent name, space-separated.`,source:"tui",severity:"fatal",expected:!0},MODULE_CONFIG_LOAD_FAILED:{code:"AX-MODULE-001",title:"Module Config Failed To Load",description:"The runtime could not import a module's module.config.ts at boot \u2014 the file is missing at its resolved path, or importing it threw. A module that cannot load contributes nothing, so boot fails rather than run a partially-wired agent.",source:"runtime",severity:"fatal"},MODULE_SOURCE_DECLARED:{code:"AX-MODULE-008",title:"Module Declared As Source",description:"Uninstall was asked to remove a module that axon.config.ts declares as an IMPORT rather than by registry name. The import statement is the author's own code, so uninstall does not rewrite it \u2014 and removing the dependency alone would leave the config importing a package that is no longer declared, with the agent still loading it. Nothing was changed: delete the import and its entry in modules: [...] by hand.",source:"cli",severity:"fatal"},MODULE_NOT_INSTALLED:{code:"AX-MODULE-003",title:"Module Not Installed",description:"A plugin asked for the options of a module this agent does not have installed \u2014 almost always a name mismatch between the plugin and the module that ships it. Reported rather than defaulted: handing back an empty options bag would let a hardware module open the wrong device and never say so.",source:"runtime",severity:"fatal"},MODULE_OPTIONS_INVALID:{code:"AX-MODULE-002",title:"Invalid Module Options",description:"The options declared for a module under modules.<name> in axon.config.ts do not satisfy the module's options schema \u2014 a required option is missing or a value has the wrong type.",source:"runtime",severity:"fatal"},MODULE_SETUP_FAILED:{code:"AX-MODULE-007",title:"Module Setup Failed",description:"A module's setup() threw during agent boot. Setup runs sequentially in blueprint order and a failure is total \u2014 no later module is wired, and the agent does not boot half-configured.",source:"runtime",severity:"fatal"},MODULE_SERVER_NOT_WIRED:{code:"AX-MODULE-004",title:"Module Server API Not Wired",description:"A module's setup() called ctx.server.addRoute/addMiddleware or ctx.tools.get, but that surface is not implemented yet. Declare routes as server/api/ files in the module instead.",source:"runtime",severity:"fatal"},MODULE_ENV_REQUIRED:{code:"AX-MODULE-005",title:"Module Env Var Missing",description:"A module's setup() called ctx.env.require() for a variable the agent's resolved environment does not provide. The module declares required env in module.config.ts; the agent must supply it (e.g. in .env).",source:"runtime",severity:"fatal",expected:!0},MODULE_POLICY_IMMUTABLE:{code:"AX-MODULE-006",title:"Module Policy Is Immutable At Boot",description:"A module's setup() called ctx.policy.update(). The resolved agent policy is authoritative and cannot be mutated at boot \u2014 declare policy needs statically in module.config.ts so the CLI reconciles them at install.",source:"runtime",severity:"fatal",expected:!0},CLONE_REF_REQUIRED:{code:"AX-PROJECT-022",title:"No Artifact Named",description:"`axon clone` was run without an artifact to clone. Name one, for example: axon clone @axon/arxiv",source:"cli",severity:"fatal",expected:!0},FORK_REF_REQUIRED:{code:"AX-PROJECT-023",title:"No Artifact Named",description:"`axon fork` was run without an artifact to fork. Name one, for example: axon fork @axon/arxiv --as @you/arxiv",source:"cli",severity:"fatal"},FORK_NAME_REQUIRED:{code:"AX-PROJECT-024",title:"Fork Needs A New Name",description:"A fork is published under your own namespace, so it needs a name: pass --as <package-name>, for example: axon fork @axon/arxiv --as @you/arxiv",source:"cli",severity:"fatal"},CLONE_TARGET_EXISTS:{code:"AX-PROJECT-025",title:"Clone Target Not Empty",description:"The directory the artifact would be cloned into already has files in it. Clone into a new directory, or clear this one first.",source:"cli",severity:"fatal"},ARTIFACT_DOWNLOAD_FAILED:{code:"AX-PROJECT-026",title:"Artifact Download Failed",description:"The registry did not serve the artifact's source archive. The version may have been unpublished, or the network request failed.",source:"cli",severity:"fatal"},ARTIFACT_EXTRACT_FAILED:{code:"AX-PROJECT-027",title:"Artifact Extract Failed",description:"The downloaded archive could not be unpacked. It may be truncated, or `tar` is unavailable on this machine.",source:"cli",severity:"fatal"},VERSION_INVALID:{code:"AX-PROJECT-028",title:"Invalid Version",description:"The project's package.json version is not valid semver, so the next version cannot be derived from it. Fix the version field by hand.",source:"cli",severity:"fatal"},FRAMEWORK_NOT_INSTALLED:{code:"AX-PROJECT-029",title:"Framework Packages Not Installed",description:"The generated type frame references @arcforge/types, @arcforge/engines and h3, none of which resolve from this project. Run `bun install` before `axon prepare`.",source:"cli",severity:"fatal"},FRAME_MIGRATION_CONFLICT:{code:"AX-PROJECT-034",title:"Frame Migration Cannot Proceed Safely",description:"Runtime output exists in BOTH the old location and the new one, so migrating would have to merge or overwrite two sets of session history. Nothing was moved. Inspect both directories and remove or merge them by hand.",source:"cli",severity:"fatal"},CONFIG_EVALUATION_ESCAPED:{code:"AX-PROJECT-030",title:"defineAgent() Called Outside Config Evaluation",description:"defineAgent() ran outside the loader that evaluates axon.config.ts \u2014 it is a declaration helper, not a runtime function, and cannot be called from application code.",source:"cli",severity:"fatal"},PROMPT_NOT_INSTALLABLE:{code:"AX-PROJECT-044",title:"Prompts Are Not Installed Into Agents",description:"A prompt is content, not a capability: it resolves from the global cache and renders on demand, so every agent can already use it without declaring anything. Installing one into an agent would put content through the code path \u2014 an ABI check, a node_modules link, an agent reload \u2014 for something that needs none of it.",source:"manifest",severity:"fatal"},ASSET_TYPE_REFUSED:{code:"AX-PROJECT-045",title:"Unsupported Asset Type",description:"A file in assets/ is not a type the registry serves. Images (png, jpg, jpeg, webp, gif) and video (mp4, webm, mov) are accepted. SVG is deliberately refused: it is an executable document that would be served from our own storage origin, so a published SVG is a script-injection surface for every visitor reading that README.",source:"manifest",severity:"fatal",expected:!0},ASSET_TOO_LARGE:{code:"AX-PROJECT-046",title:"Asset Exceeds Size Limit",description:"A single file in assets/ is over the per-asset limit. Assets exist to illustrate a README, not to distribute media \u2014 compress the file or link to it externally.",source:"manifest",severity:"fatal",expected:!0},ASSETS_BUDGET_EXCEEDED:{code:"AX-PROJECT-040",title:"Assets Exceed Total Budget",description:"The assets/ folder as a whole is over budget for one published version. Every version stores its own copy of every asset, so the total is what determines how much a package costs to host forever.",source:"manifest",severity:"fatal",expected:!0},ASSET_PATH_INVALID:{code:"AX-PROJECT-041",title:"Unsafe Asset Path",description:"An entry under assets/ is a symlink, or its name escapes the assets directory. Both are refused: a published asset must be a real file that lands where its name says it does, or extraction on the server could write outside the target directory.",source:"manifest",severity:"fatal",expected:!0},ASSET_UNREADABLE:{code:"AX-PROJECT-042",title:"Asset Could Not Be Processed",description:"A file in assets/ has an image extension but could not be decoded, so it is either corrupt or not the format its name claims. Publishing it would ship a broken image into a README.",source:"manifest",severity:"fatal",expected:!0},PORT_UNAVAILABLE:{code:"AX-PROJECT-031",title:"No Free Port",description:"Every port in the range the agent scanned is already in use. Stop whatever is holding them, or start the agent on a different port.",source:"cli",severity:"fatal"},PARENT_INSTANCE_NOT_RUNNING:{code:"AX-RUNTIME-005",title:"Parent Agent Not Running",description:"A subagent was requested against a parent session that is no longer live \u2014 the parent shut down, crashed, or was never booted by this process.",source:"runtime",severity:"fatal"},SUBAGENT_DEPTH_EXCEEDED:{code:"AX-RUNTIME-006",title:"Subagent Depth Limit Reached",description:"An agent tried to spawn a subagent beyond the maximum nesting depth. The limit exists so a recursive delegation cannot spawn processes without bound.",source:"runtime",severity:"fatal"},SUBAGENT_CHILD_LIMIT_EXCEEDED:{code:"AX-RUNTIME-007",title:"Subagent Child Limit Reached",description:"One agent tried to hold more live children than the limit allows. Existing children must finish before more can be spawned.",source:"runtime",severity:"fatal"},SUBAGENT_DESCENDANT_LIMIT_EXCEEDED:{code:"AX-RUNTIME-008",title:"Subagent Descendant Limit Reached",description:"The whole subagent tree beneath one root exceeded its live-descendant budget. The limit bounds total concurrent processes, not just direct children.",source:"runtime",severity:"fatal"},SUBAGENT_REQUEST_INVALID:{code:"AX-RUNTIME-009",title:"Malformed Subagent Request",description:"A subagent request did not carry a usable prompt. It must be an object with `prompt` as a string or an array of strings.",source:"runtime",severity:"fatal"},INSTANCE_NOT_LOCAL:{code:"AX-RUNTIME-010",title:"Agent Instance Is Not Local",description:"An operation that only works against a locally booted agent was given a remote one. Subagent spawning and the managed base workspace both require a local process.",source:"runtime",severity:"fatal"},HOST_METHOD_UNKNOWN:{code:"AX-RUNTIME-011",title:"Unknown Host Method",description:"A booted agent called a host method this platform does not implement. The agent's framework version is likely newer than the CLI running it.",source:"runtime",severity:"fatal"},UPDATE_CURRENT_VERSION_INVALID:{code:"AX-TUI-029",title:"Running Version Is Not Semver",description:"The version this app reports for itself is not valid semver, so it cannot be compared against the latest release.",source:"cli",severity:"fatal"},UPDATE_RELEASE_INVALID:{code:"AX-TUI-030",title:"Malformed Release Record",description:"The backend's release record did not describe a valid @arcforge/axon `latest` version, so there is nothing safe to update to.",source:"cli",severity:"fatal"},UPDATE_UNAVAILABLE_IN_DEVELOPMENT:{code:"AX-TUI-031",title:"Update Not Available Here",description:"Self-update needs the packaged update helper and a supervisor request path, neither of which exists in a source checkout. Update the installed app instead.",source:"cli",severity:"fatal"},UPDATE_SUPERVISOR_UNAVAILABLE:{code:"AX-TUI-032",title:"Update Supervisor Unavailable",description:"The running app has no supervisor request path, so it cannot hand an update off to be applied after exit.",source:"cli",severity:"fatal"},UPDATE_HELPER_ARGS_INVALID:{code:"AX-TUI-033",title:"Malformed Update Helper Arguments",description:"The update helper was invoked without the --from/--to/--bun/--axon/--state arguments it requires. It is spawned by the app, not run by hand.",source:"cli",severity:"fatal"},UPDATE_HELPER_VERSION_INVALID:{code:"AX-TUI-034",title:"Update Helper Given Bad Versions",description:"The update helper received a --from or --to value that is not valid semver, so it refused to install anything.",source:"cli",severity:"fatal"},TEST_FILES_NOT_FOUND:{code:"AX-TUI-035",title:"No Test Files Matched",description:"No files matched the requested test patterns, so there was nothing to run. Check the pattern, or the directory it was resolved against.",source:"cli",severity:"fatal"},OLLAMA_UNAVAILABLE:{code:"AX-TUI-037",title:"Ollama Is Not Running",description:"No Ollama daemon answered on this machine. Start it with `ollama serve`, or install Ollama from https://ollama.com to run models locally.",source:"cli",severity:"fatal"},OLLAMA_REQUEST_FAILED:{code:"AX-TUI-038",title:"Ollama Request Failed",description:"The local Ollama daemon is running but refused a request \u2014 most often an unknown model name. The daemon's own message is included.",source:"cli",severity:"fatal"},OLLAMA_REGISTRY_UNREACHABLE:{code:"AX-TUI-039",title:"Ollama Registry Unreachable",description:"Could not reach the Ollama model registry to look a model up. Downloading needs a network connection; models already on disk still work offline.",source:"cli",severity:"fatal"},NO_EDITOR_ATTACHED:{code:"AX-TUI-042",title:"No Editor Attached",description:"Opening a pane hands it to a connected editor, and none is listening. Open this project in an editor running the Axon Fleet extension \u2014 it dials each running TUI itself, so the connection appears on its own once the window is up.",source:"tui",severity:"fatal"},NO_SESSION_TO_OPEN:{code:"AX-TUI-043",title:"No Session To Open",description:"A runtime pane is a view of one conversation, and no agent is focused yet \u2014 so there is nothing to point it at. Start or focus an agent first.",source:"tui",severity:"fatal"},CLEAR_IMMUTABLE_DEPLOYED:{code:"AX-TUI-041",title:"Cannot Clear A Deployment's Conversation",description:"A deployed agent owns its own session in the cloud \u2014 the TUI attaches to whatever session it is already running, so there is no fresh one to start from here. Use `:close` to detach, or clear it on a local instance of the same agent.",source:"tui",severity:"fatal"},OLLAMA_PULL_FAILED:{code:"AX-TUI-040",title:"Model Download Failed",description:"Ollama could not finish downloading the model. The name may not exist in the registry, or the transfer was interrupted \u2014 a retry resumes from whatever was already fetched.",source:"cli",severity:"fatal"},TEST_PRELOAD_MISSING:{code:"AX-TUI-036",title:"Test API Loaded Without Its Preload",description:"The instrumented test API was imported without the preload that installs it. Tests must run through `axon test`, which wires the preload.",source:"cli",severity:"fatal"},PROFILE_CONFIG_INVALID:{code:"AX-EXT-001",title:"profile.config.ts Did Not Call defineProfile()",description:"A profile's config must default-export defineProfile({ ... }). Without it there is no extension list to read, so nothing can be installed, enabled or disabled. The rest of the profile \u2014 main.ts and plugins/ \u2014 still loads.",source:"tui",severity:"fatal",expected:!0},PROFILE_CONFIG_FAILED:{code:"AX-EXT-002",title:"profile.config.ts Failed to Load",description:"The file threw while being evaluated, so its extension list could not be read and no extensions were loaded. The profile's own main.ts and plugins/ are unaffected \u2014 a typo in an extension list must not cost you the config you already had working.",source:"tui",severity:"degraded",expected:!0},EXTENSION_ENTRY_INVALID:{code:"AX-EXT-003",title:"Malformed Extension Entry",description:'An entry in profile.config.ts\'s `extensions` array is neither a string nor an object with a `source`. Accepted forms are "@scope/name" for a registry extension and "./extensions/name" for a local one.',source:"tui",severity:"degraded",expected:!0},EXTENSION_NOT_FOUND:{code:"AX-EXT-004",title:"Extension Not Found",description:"An extension listed in profile.config.ts is not on disk. A local path may have moved or been deleted; a registry name may never have been installed. Everything else in the list still loads.",source:"tui",severity:"degraded",expected:!0},EXTENSION_INSTALL_FAILED:{code:"AX-EXT-005",title:"Extension Install Failed",description:"A registry extension could not be fetched or prepared \u2014 most often no network, or a name that does not exist in the registry. It is skipped for this session and retried on the next launch.",source:"tui",severity:"degraded",expected:!0},EXTENSION_UNINSTALL_FAILED:{code:"AX-EXT-028",title:"Extension Uninstall Failed",description:"An extension could not be removed from profile.config.ts \u2014 most often the file is unreadable or has been edited into a shape the editor cannot find the extensions list in. The extension is still declared and will load on the next launch.",source:"tui",severity:"degraded",expected:!0},EXTENSION_NOT_AN_EXTENSION:{code:"AX-EXT-006",title:"Not an Extension",description:"The directory has no extension.config.ts, which is the file that marks a directory as an extension. A path pointing at an agent, a module, or an ordinary folder is not loadable as one.",source:"tui",severity:"degraded",expected:!0},EXTENSION_LOAD_FAILED:{code:"AX-EXT-007",title:"Extension Failed to Load",description:"An extension's main.ts threw while it was being loaded, so whatever it had not yet registered is missing. Its commands, keys and palettes are removed and the rest of your config loads normally.",source:"tui",severity:"degraded",expected:!0},PROFILE_MAIN_FAILED:{code:"AX-EXT-008",title:"main.ts Failed to Load",description:"Your profile's main.ts threw while being evaluated. Anything it registered before the error survives; everything after it did not run. Plugins and extensions still load.",source:"tui",severity:"degraded",expected:!0},AGENT_NO_SUPERVISOR:{code:"AX-AGENT-030",title:"No Supervisor to Boot This Agent",description:"Something asked a platform to spawn an agent, but that platform was built without a supervisor. Supervision holds the provider credential and the session log, so it lives in the daemon rather than in whichever process happened to ask \u2014 a platform used only to read the store or publish a project does not need one, and this is where the difference surfaces.",source:"runtime",severity:"fatal",expected:!0},MODEL_RUNTIME_MISSING:{code:"AX-MODEL-031",title:"That Runtime Is Not Installed",description:"An adapter recognised the model and the library that executes it is not on this machine. Local inference runtimes are optional because they are large \u2014 ONNX Runtime alone is around 300MB of native binaries \u2014 so they are installed when first wanted rather than shipped with the CLI.",source:"daemon",severity:"fatal",expected:!0},MODEL_LOAD_FAILED:{code:"AX-MODEL-032",title:"The Model Could Not Be Loaded",description:"A runtime recognised the file and failed to read it. Distinct from an unsupported format: this weight is one this machine can execute in principle, so the file itself is the problem \u2014 truncated, corrupt, or not the model its name claims.",source:"daemon",severity:"fatal"},MODEL_WILL_NOT_FIT:{code:"AX-MODEL-033",title:"Not Enough Memory for This Model",description:"The weight loaded and did not fit within this machine's ceiling, so it was unloaded again. The refusal names what is holding the memory \u2014 a model already resident, or another process entirely, since the check measures the whole card rather than Axon's share. Nothing is evicted automatically: a silent eviction is another agent mysteriously slowing down.",source:"daemon",severity:"degraded",expected:!0},MODEL_NOT_RESIDENT:{code:"AX-MODEL-034",title:"That Model Is Not Loaded",description:"Inference was asked of a weight that is not in memory. Loading is never implicit: it is a claim on the machine's memory, and taking one a caller did not ask for would make admission invisible at the moment it matters.",source:"daemon",severity:"degraded",expected:!0},MODEL_NOT_CACHED:{code:"AX-MODEL-035",title:"That Model Is Not On This Machine",description:"A weight was asked for that has not been fetched. The daemon caches models content-addressed and machine-wide, so one download serves every agent \u2014 but it only serves what has actually been downloaded.",source:"daemon",severity:"degraded",expected:!0},MODEL_NO_SINGLE_WEIGHT:{code:"AX-MODEL-036",title:"That Repository Has No Single Weight",description:"A repository was asked for by name and publishes several weights with no obvious one to take \u2014 an encoder-decoder export ships both halves and needs both, and a quantised set is a choice about quality rather than a default. Name the file to fetch. Guessing would download half a model that fails at load with something obscure.",source:"daemon",severity:"degraded",expected:!0},MODEL_NO_RUNTIME:{code:"AX-MODEL-030",title:"No Runtime Can Execute This Model",description:"The weight is on this machine and no adapter claims it. Runtimes are registered per format \u2014 ONNX, llama.cpp \u2014 and a file none of them recognises can be fetched and cached but not loaded. Either the format needs an adapter, or the file is not the model it appears to be.",source:"daemon",severity:"fatal",expected:!0},DAEMON_NOT_RUNNING:{code:"AX-DAEMON-001",title:"The Axon Daemon Is Not Running",description:"Something asked axond for machine-wide state \u2014 what is loaded on the GPU, which agents are running \u2014 and no daemon is listening. Start it with `axon daemon up`. Every agent is supervised by the daemon, so this is not a degraded mode: nothing that boots an agent can proceed without one.",source:"daemon",severity:"fatal"},DAEMON_ALREADY_RUNNING:{code:"AX-DAEMON-002",title:"A Daemon Is Already Running",description:"A second axond was asked to start while one is already listening on this socket. One daemon per user per machine is the whole point \u2014 two would each believe they owned the GPU. Nothing was started; the existing one is untouched.",source:"daemon",severity:"degraded",expected:!0},DAEMON_SOCKET_UNAVAILABLE:{code:"AX-DAEMON-003",title:"Could Not Bind the Daemon Socket",description:"axond could not listen on its unix socket. Usually a stale socket file left by a process killed with -9, which the daemon removes on start; if it persists, the path may be unwritable or on a filesystem that does not support unix sockets.",source:"daemon",severity:"fatal"},DAEMON_START_FAILED:{code:"AX-DAEMON-004",title:"The Daemon Failed to Start",description:"axond was spawned but never reported itself ready. Every agent runs under the daemon's supervision, so a machine without one cannot boot an agent at all \u2014 this fails loudly rather than falling back, because a silent fallback is how a broken daemon went unnoticed in a published release. Its output is in the daemon log named by the detail; the usual causes are a port or socket conflict and a broken profile config.",source:"daemon",severity:"fatal"},DAEMON_NOT_WIRED:{code:"AX-DAEMON-005",title:"That Part of the Daemon Is Not Built Yet",description:"A domain the daemon declares exists but is not implemented. It throws rather than answering, because a stub returning an empty list is indistinguishable from a real answer and gets built on top of.",source:"daemon",severity:"degraded",expected:!0},EXTENSION_LOAD_TIMEOUT:{code:"AX-EXT-034",title:"Extension Took Too Long to Load",description:"A config file did not finish evaluating within the load budget \u2014 usually a blocking loop or a synchronous wait at module scope. Loading continued without it, so its commands, keys and palettes are missing; everything else in your config still loaded. The file itself keeps running until it finishes, because there is no safe way to interrupt code mid-execution.",source:"tui",severity:"degraded",expected:!0},PLUGIN_FAILED:{code:"AX-EXT-009",title:"Plugin Failed to Load",description:"A file in plugins/ threw while being imported, so its hooks were not registered. Other plugins in the same folder are unaffected \u2014 each file is loaded independently.",source:"tui",severity:"degraded",expected:!0},HOOK_FAILED:{code:"AX-EXT-010",title:"Lifecycle Hook Failed",description:"A tui.hook() handler threw while the event it listens for was firing. For a notification hook nothing else is affected; for a gating hook (tui:boot, tui:shutdown) the operation continues anyway rather than leaving the terminal stuck.",source:"tui",severity:"degraded",expected:!0},HOOK_TIMED_OUT:{code:"AX-EXT-011",title:"Hook Blocked Too Long",description:"A gating hook (tui:boot or tui:shutdown) did not finish within its budget, so the TUI continued without waiting. A config must never be able to hang the terminal silently \u2014 whatever the handler was doing may not have completed.",source:"tui",severity:"degraded",expected:!0},COMMAND_NOT_FOUND:{code:"AX-EXT-012",title:"No Such Command",description:"commands.run() was given a path that resolves to nothing in the command tree. The path must name a leaf, spelled exactly as it appears in the `:` palette.",source:"tui",severity:"fatal",expected:!0},PALETTE_NOT_FOUND:{code:"AX-EXT-013",title:"No Such Palette",description:"palette.open() was given a name no palette was registered under. Palettes are created with palette.create(name, ...) \u2014 a name is only openable once its registration has run.",source:"tui",severity:"fatal",expected:!0},PALETTE_NAME_TAKEN:{code:"AX-EXT-014",title:"Palette Name Already Registered",description:"Two palettes tried to claim the same name. Names are how palette.open() addresses one, so they have to be unique \u2014 silently replacing the first would make whichever loaded last win, invisibly.",source:"tui",severity:"degraded",expected:!0},PALETTE_ALREADY_OPEN:{code:"AX-EXT-015",title:"A Palette Is Already Open",description:"Something tried to open a palette, or ask a question, while the user was already navigating one. Stealing it mid-navigation would drop whatever they were doing, so the call fails instead \u2014 check palette.isOpen first.",source:"tui",severity:"degraded",expected:!0},KEY_CHORD_UNBOUND:{code:"AX-EXT-022",title:"No Such Key Binding",description:"keys.send() was given a chord nothing is bound to \u2014 neither a mode key nor a registered binding. Sending it would do nothing at all, which is indistinguishable from a binding that ran and had no effect.",source:"tui",severity:"fatal",expected:!0},AGENT_SPAWN_NO_INSTANCE:{code:"AX-EXT-023",title:"Agent Started but No Instance Appeared",description:"A spawn reported success without producing a focused instance, so there is no id to hand back. This is a fault in Axon rather than in your config \u2014 the agent may or may not be running.",source:"tui",severity:"fatal"},PROFILE_CONFIG_MISSING:{code:"AX-EXT-025",title:"No profile.config.ts",description:"The profile has no config file to record the extension in. It is normally created on first launch \u2014 starting Axon once will scaffold it.",source:"tui",severity:"fatal",expected:!0},PROFILE_CONFIG_UNEDITABLE:{code:"AX-EXT-026",title:"profile.config.ts Could Not Be Edited",description:"The `defineProfile({ ... })` call could not be located, or editing it would have produced invalid TypeScript. Nothing was written \u2014 this file is yours, and a botched edit costs your whole TUI config. Add or remove the entry by hand.",source:"tui",severity:"fatal",expected:!0},COMMAND_INVALID:{code:"AX-EXT-029",title:"Command Is Not Registerable",description:"A command was registered with no path, or with no `run` to call. Both are caught here rather than when someone presses Enter on it \u2014 a command that registers cleanly and then does nothing reads as a broken terminal instead of a config mistake, and gives no clue which file to open. Use `commands.register(path, fn)` or `commands.register(path, { run })`.",source:"tui",severity:"degraded",expected:!0},COMPONENT_NAME_TAKEN:{code:"AX-EXT-030",title:"Component Already Registered",description:"Two sources registered the same line component name. The first one loaded keeps it \u2014 your own config beats any extension. A silently shadowed component would render someone else's value under your name, so the second registration fails instead. Component names are `provider:name`; pick a prefix of your own.",source:"tui",severity:"degraded",expected:!0},COMPONENT_UNKNOWN:{code:"AX-EXT-031",title:"No Such Component",description:"A line named a component that is not registered. Caught when the line is created rather than when it paints, because a missing component renders as an empty gap \u2014 which reads as a layout bug instead of a typo, and gives no clue which name was wrong. components.list() returns everything available.",source:"tui",severity:"degraded",expected:!0},LINE_NAME_TAKEN:{code:"AX-EXT-032",title:"Line Already Registered",description:"Two sources registered the same line name. The first one loaded keeps it, the same rule commands and key chords follow.",source:"tui",severity:"degraded",expected:!0},LINE_UNKNOWN:{code:"AX-EXT-033",title:"No Such Line",description:"lines.set(), move(), show(), hide() or toggle() named a line that is not registered. Doing nothing would be indistinguishable from a line that registered and then rendered empty, so this fails instead. lines.list() returns what exists.",source:"tui",severity:"degraded",expected:!0},COMMAND_PATH_TAKEN:{code:"AX-EXT-020",title:"Command Already Registered",description:"Two sources registered the same command path. The first one loaded keeps it \u2014 your own config beats any extension, and between extensions the one listed earlier in profile.config.ts wins. Rename one of them.",source:"tui",severity:"degraded",expected:!0},KEY_CHORD_TAKEN:{code:"AX-EXT-021",title:"Key Chord Already Bound",description:"Two sources bound the same key chord. The first one loaded keeps it. A silently shadowed binding is unbearable to debug in someone else's config, so the second registration fails instead of replacing it.",source:"tui",severity:"degraded",expected:!0},MODE_KEY_TAKEN:{code:"AX-EXT-016",title:"Mode Key Already Bound",description:"A palette asked for a mode key that is already in use \u2014 either by a built-in mode or by another extension. A silently shadowed key is unbearable to debug in someone else's config, so the registration fails loudly instead.",source:"tui",severity:"degraded",expected:!0},MODE_UNKNOWN:{code:"AX-EXT-017",title:"No Such Mode",description:"mode.set() was given a name that is neither a built-in mode nor a registered palette. Doing nothing would look identical to a mode that simply does not render, so this fails instead.",source:"tui",severity:"fatal",expected:!0},NO_FOCUSED_AGENT:{code:"AX-EXT-018",title:"No Agent Focused",description:"A verb that acts on the focused agent \u2014 send, stop, reboot \u2014 was called while nothing was running. Start one with agents.spawn(name) or tui.nav(name) first.",source:"tui",severity:"fatal",expected:!0},INSTANCE_NOT_RUNNING:{code:"AX-EXT-019",title:"Instance Not Running",description:"An instance id was given for a conversation that is not live \u2014 it may already have been stopped, or it belongs to an earlier session. agents.list() returns what is currently running.",source:"tui",severity:"fatal",expected:!0},CONNECT_REJECTED:{code:"AX-EXT-035",title:"Connector Credential Rejected",description:"The platform refused the credential pasted during `:connect`. Verification runs before the value is written, so nothing was stored \u2014 the detail carries the platform's own reason, and the most common cause is copying the wrong secret from the developer portal.",source:"tui",severity:"fatal",expected:!0}};import{readFileSync as R40}from"fs";var w40=/at\s+(.*?)\s+\((.*?):(\d+):(\d+)\)/,S40=/at\s+(.*?):(\d+):(\d+)/,C40=["node_modules","native:","internal","bun:"],G76=2;function eE$(J=1){let Y=Error().stack;if(!Y)return[];return Y.split(`
727
727
  `).slice(1+J).map(z76).filter(U76).map(j76)}function W76(J){return J.split(`
728
728
  `).slice(1).map(z76).filter(U76).map(j76)}function $_$(J){if(!J)return null;return W76(J)[0]??null}function z76(J){let Y=J.match(w40);if(Y){let[,W,z,H,F]=Y;return{functionName:W??null,fileName:z??null,lineNumber:NQ$(H),columnNumber:NQ$(F)}}let Z=J.match(S40);if(Z){let[,W,z,H]=Z;return{functionName:null,fileName:W??null,lineNumber:NQ$(z),columnNumber:NQ$(H)}}return{functionName:null,fileName:null,lineNumber:null,columnNumber:null}}function NQ$(J){if(J===void 0)return null;let Y=parseInt(J,10);return Number.isNaN(Y)?null:Y}function U76(J){if(!J.fileName)return!1;return!C40.some((Y)=>J.fileName.includes(Y))}function j76(J){return{...J,source:b40(J.fileName,J.lineNumber)}}function b40(J,Y){if(!J||Y===null)return null;let Z;try{Z=R40(J,"utf-8")}catch{return null}let W=Z.split(`
729
729
  `),z=Y-1;if(z<0||z>=W.length)return null;let H=Math.max(0,z-G76),F=Math.min(W.length-1,z+G76),P=[];for(let E=H;E<=F;E++)P.push({lineNumber:E+1,text:W[E]??""});return P}function H76(J){if(!J.fileName||J.lineNumber===null)return J.functionName?`at ${J.functionName}`:"at <unknown>";let Y=`${J.fileName}:${J.lineNumber}:${J.columnNumber??0}`,Z=J.functionName?`at ${J.functionName} (${Y})`:`at ${Y}`,W=J.source?v40(J.source,J.lineNumber,J.columnNumber):null;return W?`${Z}