pi-namespace-patch 1.0.2-namespace.2 → 1.0.3-namespace.1
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/CHANGELOG.md +27 -0
- package/README.md +8 -8
- package/dist/bundle/chunks/{anthropic-messages-MVG2FL56.js → anthropic-messages-Y22YDKSW.js} +1 -1
- package/dist/bundle/chunks/azure-openai-responses-YJDJIIDQ.js +2 -0
- package/dist/bundle/chunks/chunk-22CYIUS4.js +2 -0
- package/dist/bundle/chunks/{chunk-SYF2TF6W.js → chunk-2VBQLN7Y.js} +3 -3
- package/dist/bundle/chunks/{chunk-ZSI3BL5Q.js → chunk-6DBOMCBS.js} +1 -1
- package/dist/bundle/chunks/{chunk-2KAZSACP.js → chunk-7TP2J6F2.js} +1 -1
- package/dist/bundle/chunks/{chunk-6FX7UEPL.js → chunk-AXOERKKW.js} +3 -3
- package/dist/bundle/chunks/{chunk-OSKPX3Z5.js → chunk-C47CLQZK.js} +1 -1
- package/dist/bundle/chunks/{chunk-DN3QEIXS.js → chunk-DEVCTHZR.js} +1 -1
- package/dist/bundle/chunks/{chunk-IKZJX7ZT.js → chunk-HQHD6PZI.js} +1 -1
- package/dist/bundle/chunks/{chunk-OLBCNJCL.js → chunk-ITAWMMSC.js} +30 -30
- package/dist/bundle/chunks/chunk-KJUDFE6Y.js +11 -0
- package/dist/bundle/chunks/{chunk-WCQZGZ6I.js → chunk-PSQJVYXD.js} +1 -1
- package/dist/bundle/chunks/{chunk-G7EDXK4D.js → chunk-TAOL3JFA.js} +1 -1
- package/dist/bundle/chunks/chunk-UBHCV62G.js +20 -0
- package/dist/bundle/chunks/{chunk-BYB6ZAAQ.js → chunk-WE4MXUQS.js} +1 -1
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +2 -0
- package/dist/bundle/chunks/chunk-ZSQEXT6X.js +15 -0
- package/dist/bundle/chunks/{cli-KILDDGW3.js → cli-HTJP6F6Z.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-X5PVWWYJ.js → cloudflare-workers-ai-system-one-NM3JRRWQ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +0 -1
- package/dist/bundle/chunks/{easter-egg-3d-T5FFWIBR.js → easter-egg-3d-6YCNESG3.js} +1 -1
- package/dist/bundle/chunks/{execute-RYVK27GT.js → execute-JRUOLYDA.js} +4 -4
- package/dist/bundle/chunks/{google-generative-ai-ZOK6CV7D.js → google-generative-ai-XMFHGQC5.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-VKWZQ3AY.js → google-vertex-4XRRNP74.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-7DAUEE4N.js → mistral-conversations-Q22M3IBG.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-TC3OK7B4.js → openai-codex-responses-4MYQSO5E.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-GWHGMQ3T.js → openai-completions-OSRCWAAA.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-EZ7FJ2KL.js → openai-responses-UHF3DHNG.js} +1 -1
- package/dist/bundle/chunks/{runtime-D5I2NTIF.js → runtime-NW7GPWKS.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-A4CZTQWZ.js → typesafe-system-one-PRR5K6CI.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-U4SEX4TD.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/config.d.ts +18 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +44 -6
- package/dist/config.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -7
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/keybindings.d.ts +4 -4
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -10
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +49 -8
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.js +1 -1
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +4 -9
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +42 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/output-files.d.ts +15 -0
- package/dist/utils/output-files.d.ts.map +1 -0
- package/dist/utils/output-files.js +30 -0
- package/dist/utils/output-files.js.map +1 -0
- package/docs/codemode.md +3 -3
- package/docs/keybindings.md +4 -4
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +10 -10
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +0 -2
- package/dist/bundle/chunks/chunk-7JGR3GZN.js +0 -11
- package/dist/bundle/chunks/chunk-OYBSLV7Y.js +0 -16
- package/dist/bundle/chunks/chunk-PDFMCAOZ.js +0 -19
- package/dist/bundle/chunks/chunk-VIV3CWXG.js +0 -2
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +0 -2
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{AssistantMessageEventStream,formatThrownValue}from"./chunk-A3JYRWB6.js";function contentText(content,separator=`
|
|
3
|
+
`){return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(separator)}function getSystemMessageText(message){let parts=[contentText(message.content)];for(let text of Object.values(message.sections??{}))text!==null&&parts.push(text);return parts.filter(part=>part.length>0).join(`
|
|
4
|
+
|
|
5
|
+
`)}function renderSystemMessageUpdate(message){let parts=[],text=contentText(message.content);text.length>0&&parts.push(text);for(let[name,value]of Object.entries(message.sections??{}))parts.push(value===null?`Removed system prompt section "${name}".`:`Updated system prompt section "${name}":
|
|
6
|
+
|
|
7
|
+
${value}`);return parts.join(`
|
|
8
|
+
|
|
9
|
+
`)}function createInitialSystemMessage(systemPrompt,tools){let hasSystemPrompt=systemPrompt!==void 0&&systemPrompt.length>0,hasTools=tools!==void 0&&tools.length>0;if(!(!hasSystemPrompt&&!hasTools))return{role:"system",content:systemPrompt??"",...hasTools?{toolsAdded:tools}:{},timestamp:0}}function normalizeContext(context){let initialMessage=createInitialSystemMessage(context.systemPrompt,context.tools);return{messages:initialMessage?[initialMessage,...context.messages]:context.messages}}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
10
|
+
|
|
11
|
+
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function getCurrentSystemPrompt(messages){let message=getCurrentSystemMessage(messages);return message?getSystemMessageText(message):""}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function resolveTranscript(context,supportsMidConvoSystemMessages){return supportsMidConvoSystemMessages?context:collapseSystemMessages(context)}function toToolDeclaration(tool){return{name:tool.name,description:tool.description,parameters:JSON.parse(JSON.stringify(tool.parameters)),...tool.constrainedSampling===void 0?{}:{constrainedSampling:tool.constrainedSampling}}}function declarationsEqual(left,right){return JSON.stringify(toToolDeclaration(left))===JSON.stringify(toToolDeclaration(right))}function getToolStateChanges(previous,current){let previousTools=new Map(previous.map(tool=>[tool.name,tool])),currentTools=new Map(current.map(tool=>[tool.name,tool]));return{toolsAdded:current.filter(tool=>{let previousTool=previousTools.get(tool.name);return previousTool===void 0||!declarationsEqual(previousTool,tool)}).map(toToolDeclaration),toolsRemoved:previous.filter(tool=>{let currentTool=currentTools.get(tool.name);return currentTool===void 0||!declarationsEqual(tool,currentTool)}).map(tool=>({name:tool.name}))}}function getDeclaredTools(messages){let definitions=new Map;for(let message of messages)if(isSystemMessage(message))for(let tool of message.toolsAdded??[])definitions.set(tool.name,tool);return[...definitions.values()]}function hasToolRedefinitions(messages){let declared=new Map;for(let message of messages)if(isSystemMessage(message))for(let tool of message.toolsAdded??[]){let previous=declared.get(tool.name);if(previous!==void 0&&!declarationsEqual(previous,tool))return!0;declared.set(tool.name,tool)}return!1}function hasNonAdditiveToolChanges(messages){let declared=new Set;for(let message of messages)if(isSystemMessage(message)){if((message.toolsRemoved?.length??0)>0)return!0;for(let tool of message.toolsAdded??[]){if(declared.has(tool.name))return!0;declared.add(tool.name)}}return!1}function resolveTranscriptTools(messages,supportsToolAdditions){let anchorsAdditions=supportsToolAdditions&&!hasNonAdditiveToolChanges(messages);return{requestTools:anchorsAdditions?getInitialSystemMessage(messages)?.toolsAdded??[]:getCurrentTools(messages),anchorsAdditions}}function createSetupErrorMessage(model,error){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:error instanceof Error?error.message:String(error),timestamp:Date.now()}}function hasResult(source){return typeof source.result=="function"}async function forwardStream(target,source){for await(let event of source)target.push(event);target.end(hasResult(source)?await source.result():void 0)}function lazyStream(model,setup){let outer=new AssistantMessageEventStream;return setup().then(inner=>forwardStream(outer,inner)).catch(error=>{let message=createSetupErrorMessage(model,error);outer.push({type:"error",reason:"error",error:message}),outer.end(message)}),outer}function lazyApi(load,capabilities){let api={stream:(model,context,options)=>lazyStream(model,async()=>(await load()).stream(model,context,options)),streamSimple:(model,context,options)=>lazyStream(model,async()=>(await load()).streamSimple(model,context,options))};return capabilities?.fetchDeferred&&(api.fetchDeferred=(model,handle,options)=>lazyStream(model,async()=>{let implementation=await load();if(!implementation.fetchDeferred)throw new Error("API does not support deferred responses");return implementation.fetchDeferred(model,handle,options)})),capabilities?.cancelDeferred&&(api.cancelDeferred=async(model,handle,options)=>{let implementation=await load();if(!implementation.cancelDeferred)throw new Error("API cannot cancel deferred responses");await implementation.cancelDeferred(model,handle,options)}),api}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path},importNodeModule=specifier=>import(__rewriteRelativeImportExtension(specifier));function getProcessEnv(){return globalThis.process?.env}function defaultProviderAuthContext(){return{async env(name){let value=getProcessEnv()?.[name];return typeof value=="string"&&value.trim().length>0?value:void 0},async fileExists(path){try{let fs=await importNodeModule("node:fs/promises"),resolved=path;return resolved.startsWith("~")&&(resolved=(await importNodeModule("node:os")).homedir()+resolved.slice(1)),await fs.access(resolved),!0}catch{return!1}}}}function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()})}var InMemoryCredentialStore=class{credentials=new Map;chains=new Map;enqueue(providerId,task,options){let signal=operationSignal(options?.signal),previous=this.chains.get(providerId)??Promise.resolve(),queued=(async()=>(await previous.catch(()=>{}),signal.throwIfAborted(),task()))(),tail=queued.catch(()=>{});return this.chains.set(providerId,tail),tail.then(()=>{this.chains.get(providerId)===tail&&this.chains.delete(providerId)}),raceWithAbortSignal(queued,signal)}async read(providerId,options){return options?.signal?.throwIfAborted(),this.credentials.get(providerId)}async list(options){return options?.signal?.throwIfAborted(),[...this.credentials].map(([providerId,credential])=>({providerId,type:credential.type}))}modify(providerId,fn,options){return this.enqueue(providerId,async()=>{let current=this.credentials.get(providerId),next=await fn(current);return options?.signal?.throwIfAborted(),next!==void 0&&this.credentials.set(providerId,next),next??current},options)}delete(providerId,options){return this.enqueue(providerId,async()=>{this.credentials.delete(providerId)},options)}};var ModelsError=class extends Error{code;constructor(code,message,options){super(withCauseDetail(message,options?.cause),options),this.name="ModelsError",this.code=code}};function withCauseDetail(message,cause){if(cause==null)return message;let detail=formatThrownValue(cause).trim();return!detail||message.includes(detail)?message:`${message}: ${detail}`}function resolveProviderAuth(provider,credentials,authContext,overrides){let signal=operationSignal(overrides?.signal);return raceWithAbortSignal(resolveProviderAuthWithSignal(provider,credentials,authContext,overrides,signal),signal)}async function resolveProviderAuthWithSignal(provider,credentials,authContext,overrides,signal){signal.throwIfAborted();let requestAuthContext=overrides?.env?overlayEnvAuthContext(authContext,overrides.env):authContext;if(overrides?.apiKey!==void 0&&provider.auth.apiKey)return resolveApiKey(requestAuthContext,provider.auth.apiKey,provider.id,{type:"api_key",key:overrides.apiKey,env:overrides.env},signal);let stored=await readCredential(credentials,provider.id,signal);if(stored){if(stored.type==="oauth"&&provider.auth.oauth)return resolveStoredOAuth(credentials,provider.id,provider.auth.oauth,stored,signal,overrides?.minOAuthValidityMs);if(stored.type==="api_key"&&provider.auth.apiKey){let credential=overrides?.env?{...stored,env:{...stored.env,...overrides.env}}:stored;return resolveApiKey(requestAuthContext,provider.auth.apiKey,provider.id,credential,signal)}return}return provider.auth.apiKey?resolveApiKey(requestAuthContext,provider.auth.apiKey,provider.id,void 0,signal):void 0}function overlayEnvAuthContext(base,env){return{env:async name=>env[name]||await base.env(name),fileExists:path=>base.fileExists(path)}}var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS=300*1e3,DEFAULT_OAUTH_REFRESH_TIMEOUT_MS=15e3;async function refreshStoredOAuthCredential(credentials,providerId,oauth,needsRefresh,signal){let post,lockWait=new AbortController,cancelLockWait=()=>lockWait.abort(signal.reason);signal.addEventListener("abort",cancelLockWait,{once:!0}),signal.aborted&&cancelLockWait();try{post=await credentials.modify(providerId,async current=>{if(signal.removeEventListener("abort",cancelLockWait),signal.throwIfAborted(),current?.type==="oauth"&&needsRefresh(current))try{return await oauth.refresh(current,AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS))}catch(error){throw new ModelsError("oauth",`OAuth refresh failed for ${providerId}`,{cause:error})}},{signal:lockWait.signal})}catch(error){throw error instanceof ModelsError?error:(signal.throwIfAborted(),new ModelsError("auth",`Credential store modify failed for ${providerId}`,{cause:error}))}finally{signal.removeEventListener("abort",cancelLockWait)}return post?.type==="oauth"?post:void 0}async function resolveStoredOAuth(credentials,providerId,oauth,stored,signal,minOAuthValidityMs){let minimumValidityMs=Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,minOAuthValidityMs??0),expiresSoon=credential2=>Date.now()+minimumValidityMs>=credential2.expires,credential=stored;if(expiresSoon(credential)){let post=await refreshStoredOAuthCredential(credentials,providerId,oauth,expiresSoon,signal);if(!post)return;if(credential=post,minOAuthValidityMs!==void 0&&expiresSoon(credential))throw new ModelsError("oauth",`OAuth refresh returned a token that expires too soon for ${providerId}`)}try{return{auth:await oauth.toAuth(credential),source:"OAuth"}}catch(error){throw new ModelsError("oauth",`OAuth auth derivation failed for ${providerId}`,{cause:error})}}async function resolveApiKey(authContext,apiKey,providerId,credential,signal){try{return await apiKey.resolve({ctx:authContext,credential,signal})}catch(error){throw new ModelsError("auth",`API key auth failed for provider ${providerId}`,{cause:error})}}async function readCredential(credentials,providerId,signal){try{return await credentials.read(providerId,{signal})}catch(error){throw new ModelsError("auth",`Credential store read failed for ${providerId}`,{cause:error})}}var InMemoryModelsStore=class{entries=new Map;async read(providerId,options){options?.signal?.throwIfAborted();let entry=this.entries.get(providerId);return entry?structuredClone(entry):void 0}async write(providerId,entry,options){options?.signal?.throwIfAborted(),this.entries.set(providerId,structuredClone(entry))}async delete(providerId,options){options?.signal?.throwIfAborted(),this.entries.delete(providerId)}};function getModelType(model){return model.type??"chat"}function isModelType(model,type){return getModelType(model)===type}function assertChatModel(model){if(!isModelType(model,"chat"))throw new ModelsError("provider",`Model ${model.provider}/${model.id} is not a chat model`)}function assertImageModel(model){if(!isModelType(model,"image"))throw new ModelsError("provider",`Model ${model.provider}/${model.id} is not an image model`)}function assertClassifierModel(model){if(!isModelType(model,"classifier"))throw new ModelsError("provider",`Model ${model.provider}/${model.id} is not a classifier model`)}function imageErrorResult(model,error,aborted=!1){return{api:model.api,provider:model.provider,model:model.id,output:[],stopReason:aborted?"aborted":"error",errorMessage:error instanceof Error?error.message:String(error),timestamp:Date.now()}}function classifierErrorResult(model,error,aborted=!1){return{api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:aborted?"aborted":"error",errorMessage:error instanceof Error?error.message:String(error),timestamp:Date.now()}}var KNOWN_MODEL_TYPES={chat:!0,image:!0,classifier:!0};function hasKnownModelType(model){return Object.hasOwn(KNOWN_MODEL_TYPES,getModelType(model))}function withKnownModelTypes(entry){return{...entry,models:entry.models.filter(hasKnownModelType)}}function mergeHeaders(base,override){if(!base&&!override)return;let merged={...base};for(let[name,value]of Object.entries(override??{})){let lowerName=name.toLowerCase();for(let existingName of Object.keys(merged))existingName.toLowerCase()===lowerName&&delete merged[existingName];merged[name]=value}return merged}var ModelsImpl=class{providers=new Map;credentials;modelsStore;authContext;refreshGenerations=new Map;refreshControllers=new Map;publicationChains=new Map;constructor(options){this.credentials=options?.credentials??new InMemoryCredentialStore,this.modelsStore=options?.modelsStore??new InMemoryModelsStore,this.authContext=options?.authContext??defaultProviderAuthContext()}setProvider(provider){this.supersedeProviderRefresh(provider.id),this.providers.set(provider.id,provider)}deleteProvider(id){this.supersedeProviderRefresh(id),this.providers.delete(id)}clearProviders(){for(let id of new Set([...this.providers.keys(),...this.refreshControllers.keys()]))this.supersedeProviderRefresh(id);this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(id){return this.providers.get(id)}getModels(provider){if(provider!==void 0){let entry=this.providers.get(provider);if(!entry)return[];try{return entry.getModels()}catch{return[]}}let models=[];for(let entry of this.providers.values())try{models.push(...entry.getModels())}catch{}return models}getAllModels(provider){if(provider!==void 0){let entry=this.providers.get(provider);if(!entry)return[];try{return entry.getAllModels?.()??entry.getModels()}catch{return[]}}let models=[];for(let entry of this.providers.values())try{models.push(...entry.getAllModels?.()??entry.getModels())}catch{}return models}getModelsOfType(type,provider){return this.getAllModels(provider).filter(model=>isModelType(model,type))}getModel(provider,id){return this.getModels(provider).find(model=>model.id===id)}getModelOfType(type,provider,id){return this.getModelsOfType(type,provider).find(model=>model.id===id)}supersedeProviderRefresh(providerId){let generation=(this.refreshGenerations.get(providerId)??0)+1;this.refreshGenerations.set(providerId,generation);let previous=this.refreshControllers.get(providerId);return previous&&(this.refreshControllers.delete(providerId),previous.abort()),generation}beginProviderRefresh(providerId){let generation=this.supersedeProviderRefresh(providerId),controller=new AbortController;return this.refreshControllers.set(providerId,controller),{generation,controller}}publishProviderModels(providerId,generation,signal,publication){let previous=this.publicationChains.get(providerId)??Promise.resolve(),queued=(async()=>(await previous.catch(()=>{}),signal.aborted||this.refreshGenerations.get(providerId)!==generation||(publication.persist===null?await this.modelsStore.delete(providerId,{signal}):publication.persist!==void 0&&await this.modelsStore.write(providerId,structuredClone(publication.persist),{signal}),signal.aborted||this.refreshGenerations.get(providerId)!==generation)?!1:(publication.update?.(),!0)))(),tail=queued.catch(()=>{});return this.publicationChains.set(providerId,tail),tail.then(()=>{this.publicationChains.get(providerId)===tail&&this.publicationChains.delete(providerId)}),raceWithAbortSignal(queued,signal)}async runProviderRefreshPhase(provider,credential,allowNetwork,force,generation,signal){let stored=await this.modelsStore.read(provider.id,{signal});await provider.refreshModels({credential,stored:stored?withKnownModelTypes(structuredClone(stored)):void 0,publish:publication=>this.publishProviderModels(provider.id,generation,signal,publication),allowNetwork,force:allowNetwork?force:void 0,signal})}async refresh(options={}){let allowNetwork=options.allowNetwork??!0,callerSignal=operationSignal(options.signal),errors=new Map;if(callerSignal.aborted)return{aborted:!0,errors};let selected=options.providers?new Set(options.providers):void 0,refreshable=Array.from(this.providers.values()).filter(provider=>provider.refreshModels!==void 0&&(!selected||selected.has(provider.id))),refresh=Promise.all(refreshable.map(async provider=>{let{generation,controller}=this.beginProviderRefresh(provider.id),signal=AbortSignal.any([callerSignal,controller.signal]),operation=(async()=>{let storedCredential,credentialError;try{storedCredential=await this.readCredential(provider.id,signal)}catch(error){credentialError=error}if(await this.runProviderRefreshPhase(provider,storedCredential,!1,void 0,generation,signal),credentialError!==void 0)throw credentialError;if(!allowNetwork||signal.aborted)return;let credential=await this.resolveRefreshCredential(provider,storedCredential,signal);credential&&await this.runProviderRefreshPhase(provider,credential,!0,options.force,generation,signal)})();try{await raceWithAbortSignal(operation,signal)}catch(error){signal.aborted||errors.set(provider.id,error instanceof Error?error:new ModelsError("model_source",`Model refresh failed for ${provider.id}`,{cause:error}))}finally{this.refreshControllers.get(provider.id)===controller&&this.refreshControllers.delete(provider.id)}}));try{await raceWithAbortSignal(refresh,callerSignal)}catch(error){if(!callerSignal.aborted)throw error}return{aborted:callerSignal.aborted,errors:new Map(errors)}}async resolveRefreshCredential(provider,stored,signal){if(stored?.type==="oauth"){let oauth=provider.auth.oauth;return oauth?Date.now()<stored.expires?stored:signal.aborted?void 0:refreshStoredOAuthCredential(this.credentials,provider.id,oauth,current=>Date.now()>=current.expires,signal):void 0}let apiKey=provider.auth.apiKey;if(!apiKey)return;let credential=stored?.type==="api_key"?stored:void 0,result=await apiKey.resolve({ctx:this.authContext,credential,signal});if(result)return{type:"api_key",key:result.auth.apiKey,env:result.env}}async readCredential(providerId,signal){try{return await this.credentials.read(providerId,{signal})}catch(error){throw new ModelsError("auth",`Credential store read failed for ${providerId}`,{cause:error})}}async checkProviderAuth(provider,credential,signal){if(credential?.type==="oauth")return provider.auth.oauth?{source:"OAuth",type:"oauth"}:void 0;let apiKey=provider.auth.apiKey;if(!apiKey)return;if(apiKey.check)try{return await apiKey.check({ctx:this.authContext,credential:credential?.type==="api_key"?credential:void 0,signal})}catch(error){throw new ModelsError("auth",`API key auth check failed for provider ${provider.id}`,{cause:error})}let resolution=await resolveProviderAuth(provider,this.credentials,this.authContext,{signal});return resolution?{source:resolution.source,type:"api_key"}:void 0}checkAuth(providerId,options){let signal=operationSignal(options?.signal),check=(async()=>{signal.throwIfAborted();let provider=this.providers.get(providerId);if(provider)return this.checkProviderAuth(provider,await this.readCredential(providerId,signal),signal)})();return raceWithAbortSignal(check,signal)}async getAuthenticatedProviders(providerId,signal){signal.throwIfAborted();let providers=providerId?[this.providers.get(providerId)].filter(entry=>entry!==void 0):this.getProviders();return(await Promise.all(providers.map(async provider=>{let credential=await this.readCredential(provider.id,signal);return{provider,credential,auth:await this.checkProviderAuth(provider,credential,signal)}}))).filter(entry=>entry.auth!==void 0)}getAvailable(providerId,options){let signal=operationSignal(options?.signal),available=(async()=>(await this.getAuthenticatedProviders(providerId,signal)).flatMap(({provider,credential})=>{let models=provider.getModels();return provider.filterModels?.(models,credential)??models}))();return raceWithAbortSignal(available,signal)}async getAvailableOfType(type,providerId,options){return(await this.getAllAvailable(providerId,options)).filter(model=>isModelType(model,type))}getAllAvailable(providerId,options){let signal=operationSignal(options?.signal),available=(async()=>(await this.getAuthenticatedProviders(providerId,signal)).flatMap(({provider,credential})=>{let models=provider.getAllModels?.()??provider.getModels();if(provider.filterAllModels)return provider.filterAllModels(models,credential);if(!provider.filterModels)return models;let availableChatIds=new Set(provider.filterModels(provider.getModels(),credential).map(model=>model.id));return models.filter(model=>!isModelType(model,"chat")||availableChatIds.has(model.id))}))();return raceWithAbortSignal(available,signal)}async getAuth(providerOrModel,overrides){let signal=operationSignal(overrides?.signal),providerId=typeof providerOrModel=="string"?providerOrModel:providerOrModel.provider,provider=this.providers.get(providerId);if(!provider)return;let result=await resolveProviderAuth(provider,this.credentials,this.authContext,{...overrides,signal});return!result||typeof providerOrModel=="string"||!providerOrModel.headers?result:{...result,auth:{...result.auth,headers:mergeHeaders(result.auth.headers,providerOrModel.headers)}}}async login(providerId,type,interaction,options){let signal=operationSignal(interaction.signal);signal.throwIfAborted();let provider=this.providers.get(providerId);if(!provider)throw new ModelsError("provider",`Unknown provider: ${providerId}`);let method=type==="oauth"?provider.auth.oauth:provider.auth.apiKey;if(!method?.login)throw new ModelsError("auth",`${provider.name} does not support ${type} login`);let loginOperation=method.login({...interaction,signal},options),credential=await raceWithAbortSignal(loginOperation,signal),mutationStarted=!1,markMutationStarted,started=new Promise(resolve=>{markMutationStarted=resolve}),mutation=this.credentials.modify(providerId,async()=>(mutationStarted=!0,markMutationStarted?.(),credential),{signal});mutation.catch(()=>{});try{await new Promise((resolve,reject)=>{let onAbort=()=>{mutationStarted||reject(signal.reason)};signal.addEventListener("abort",onAbort,{once:!0}),Promise.race([started,mutation]).then(()=>{signal.removeEventListener("abort",onAbort),resolve()},error=>{signal.removeEventListener("abort",onAbort),reject(error)}),signal.aborted&&onAbort()}),await mutation}catch(error){throw signal.throwIfAborted(),new ModelsError("auth",`Credential store modify failed for ${providerId}`,{cause:error})}return credential}async logout(providerId,options){let signal=operationSignal(options?.signal);signal.throwIfAborted();try{await this.credentials.delete(providerId,{signal})}catch(error){throw signal.throwIfAborted(),new ModelsError("auth",`Credential store delete failed for ${providerId}`,{cause:error})}}requireProvider(model){let provider=this.providers.get(model.provider);if(!provider)throw new ModelsError("provider",`Unknown provider: ${model.provider}`);return provider}requireChatProvider(model){return assertChatModel(model),this.requireProvider(model)}async applyAuth(model,options){this.requireProvider(model);let resolution=await this.getAuth(model,{apiKey:options?.apiKey,env:options?.env,signal:options?.signal});if(!resolution)throw new ModelsError("auth",`Provider is not configured: ${model.provider}`);let auth=resolution.auth,apiKey=options?.apiKey??auth.apiKey,headers=mergeHeaders(auth.headers,options?.headers);options?.transformHeaders&&(headers=await options.transformHeaders(headers??{}));let env=resolution.env||options?.env?{...resolution.env??{},...options?.env??{}}:void 0,requestModel=auth.baseUrl?{...model,baseUrl:auth.baseUrl}:model,{transformHeaders:_transformHeaders,...providerOptions}=options??{},requestOptions={...providerOptions,apiKey,headers,env};return{requestModel,requestOptions}}stream(model,context,options){let transcript=normalizeContext(context);return lazyStream(model,async()=>{let provider=this.requireChatProvider(model),{requestModel,requestOptions}=await this.applyAuth(model,options);return provider.stream(requestModel,transcript,requestOptions)})}async complete(model,context,options){return this.stream(model,context,options).result()}streamSimple(model,context,options){let transcript=normalizeContext(context);return lazyStream(model,async()=>{let provider=this.requireChatProvider(model),{requestModel,requestOptions}=await this.applyAuth(model,options);return provider.streamSimple(requestModel,transcript,requestOptions)})}async completeSimple(model,context,options){return this.streamSimple(model,context,options).result()}streamDeferred(model,handle,options){return lazyStream(model,async()=>{let provider=this.requireChatProvider(model);if(!provider.fetchDeferred)throw new ModelsError("provider",`Provider ${model.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model,options);return provider.fetchDeferred(requestModel,handle,requestOptions)})}async fetchDeferred(model,handle,options){return this.streamDeferred(model,handle,options).result()}async cancelDeferred(model,handle,options){let provider=this.requireChatProvider(model);if(!provider.cancelDeferred)throw new ModelsError("provider",`Provider ${model.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model,options);await provider.cancelDeferred(requestModel,handle,requestOptions)}async generateImages(model,context,options){try{assertImageModel(model);let provider=this.requireProvider(model);if(!provider.generateImages)throw new ModelsError("provider",`Provider ${model.provider} does not support image generation`);let{requestModel,requestOptions}=await this.applyAuth(model,options);return await provider.generateImages(requestModel,context,requestOptions)}catch(error){return imageErrorResult(model,error,options?.signal?.aborted)}}async classify(model,context,options){try{assertClassifierModel(model);let provider=this.requireProvider(model);if(!provider.classify)throw new ModelsError("provider",`Provider ${model.provider} does not support classification`);let{requestModel,requestOptions}=await this.applyAuth(model,options);return await provider.classify(requestModel,context,requestOptions)}catch(error){return classifierErrorResult(model,error,options?.signal?.aborted)}}};function createModels(options){return new ModelsImpl(options)}function createProvider(input){let single=input.api&&typeof input.api.stream=="function"?input.api:void 0,byApi=single||!input.api?void 0:input.api,images=input.images,classifiers=input.classifiers,streams=single?[single]:Object.values(byApi??{}).filter(entry=>entry!==void 0),imageImplementations=Object.values(images??{}).filter(entry=>entry!==void 0),classifierImplementations=Object.values(classifiers??{}).filter(entry=>entry!==void 0);if(streams.length===0&&imageImplementations.length===0&&classifierImplementations.length===0)throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);let baselineModels=input.models,dynamicModels=[],fetchModels=input.fetchModels,currentModels=()=>{let merged=[...baselineModels];for(let model of dynamicModels){let index=merged.findIndex(entry=>getModelType(entry)===getModelType(model)&&entry.id===model.id);index>=0?merged[index]=model:merged.push(model)}return merged},apiFor=model=>single??byApi?.[model.api],dispatch=(model,run)=>{let streams2=apiFor(model);return streams2?run(streams2):lazyStream(model,async()=>{throw new ModelsError("stream",`Provider ${input.id} has no API implementation for "${model.api}"`)})},provider={id:input.id,name:input.name??input.id,baseUrl:input.baseUrl,headers:input.headers,auth:input.auth,getModels:()=>currentModels().filter(model=>isModelType(model,"chat")),getAllModels:currentModels,refreshModels:fetchModels?async context=>{if(context.stored){let restored=context.stored.models.filter(model=>model.provider===input.id).map(model=>model);if(!await context.publish({update:()=>{dynamicModels=restored}}))return}if(!context.allowNetwork||context.signal.aborted)return;let fetched=await fetchModels(context);if(context.signal.aborted)return;let refreshed=fetched.filter(hasKnownModelType);await context.publish({persist:{models:refreshed,checkedAt:Date.now()},update:()=>{dynamicModels=refreshed}})}:void 0,filterModels:input.filterModels,filterAllModels:input.filterAllModels,stream:(model,context,options)=>dispatch(model,streams2=>streams2.stream(model,context,options)),streamSimple:(model,context,options)=>dispatch(model,streams2=>streams2.streamSimple(model,context,options))};return streams.some(entry=>entry.fetchDeferred!==void 0)&&(provider.fetchDeferred=(model,handle,options)=>lazyStream(model,async()=>{let implementation=apiFor(model);if(!implementation?.fetchDeferred)throw new ModelsError("provider",`Provider ${input.id} does not support deferred responses for "${model.api}"`);return implementation.fetchDeferred(model,handle,options)})),streams.some(entry=>entry.cancelDeferred!==void 0)&&(provider.cancelDeferred=async(model,handle,options)=>{let implementation=apiFor(model);if(!implementation?.cancelDeferred)throw new ModelsError("provider",`Provider ${input.id} cannot cancel deferred responses for "${model.api}"`);await implementation.cancelDeferred(model,handle,options)}),images&&imageImplementations.length>0&&(provider.generateImages=async(model,context,options)=>{let implementation=images[model.api];return implementation?implementation.generateImages(model,context,options):imageErrorResult(model,new ModelsError("provider",`Provider ${input.id} has no image generation implementation for "${model.api}"`))}),classifiers&&classifierImplementations.length>0&&(provider.classify=async(model,context,options)=>{let implementation=classifiers[model.api];return implementation?implementation.classify(model,context,options):classifierErrorResult(model,new ModelsError("provider",`Provider ${input.id} has no classifier implementation for "${model.api}"`))}),provider}function hasApi(model,api){return isModelType(model,"chat")&&model.api===api}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i=requestedIndex;i<EXTENDED_THINKING_LEVELS.length;i++){let candidate=EXTENDED_THINKING_LEVELS[i];if(availableLevels.includes(candidate))return candidate}for(let i=requestedIndex-1;i>=0;i--){let candidate=EXTENDED_THINKING_LEVELS[i];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function modelsAreEqual(a,b){return!a||!b?!1:getModelType(a)===getModelType(b)&&a.id===b.id&&a.provider===b.provider}export{lazyStream,lazyApi,defaultProviderAuthContext,InMemoryCredentialStore,ModelsError,InMemoryModelsStore,getModelType,isModelType,assertChatModel,assertImageModel,assertClassifierModel,imageErrorResult,classifierErrorResult,contentText,getSystemMessageText,renderSystemMessageUpdate,createInitialSystemMessage,normalizeContext,getInitialSystemMessage,withoutInitialSystemMessage,getCurrentTools,getCurrentSystemMessage,getCurrentSystemPrompt,collapseSystemMessages,resolveTranscript,toToolDeclaration,declarationsEqual,getToolStateChanges,getDeclaredTools,hasToolRedefinitions,hasNonAdditiveToolChanges,resolveTranscriptTools,createModels,createProvider,hasApi,calculateCost,getSupportedThinkingLevels,clampThinkingLevel,modelsAreEqual};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isMcpAppResource,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-
|
|
2
|
+
import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isMcpAppResource,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-ZSQEXT6X.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-AXOERKKW.js";import{__toESM}from"./chunk-4L3WN2XY.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createServer}from"node:http";function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
|
|
3
3
|
|
|
4
4
|
${page.details}`:page.message}var OAuthCallbackServer=class _OAuthCallbackServer{redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(server,redirectUrl,paths,timeoutMs,renderPage2){this.server=server,this.redirectUrl=redirectUrl,this.paths=paths,this.timeoutMs=timeoutMs,this.renderPage=renderPage2}static async listen(options={}){let host=options.host??"127.0.0.1",redirectHost=options.redirectHost??host,path=options.path??"/callback",instance,server=createServer((request,response)=>instance?.handle(request.url??"/",response));await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port??0,host,()=>{server.off("error",reject),resolve2()})});let address=server.address();if(!address||typeof address=="string")throw new Error("OAuth callback server did not bind to TCP");return instance=new _OAuthCallbackServer(server,`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}:${address.port}${path}`,[path,...options.extraPaths??[]],options.timeoutMs??5*6e4,options.renderPage),instance}waitForCallback(state,path){if(this.pending.has(state))throw new Error("OAuth state is already pending");return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{this.pending.delete(state),reject(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(state,{resolve:resolve2,reject,timer,path})})}async close(){for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(new Error("OAuth callback server closed"));this.pending.clear(),await new Promise((resolve2,reject)=>{this.server.close(error=>error?reject(error):resolve2())})}reply(response,status,page){this.renderPage?(response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(this.renderPage(page))):response.writeHead(status,{"content-type":"text/plain; charset=utf-8"}).end(plainText(page))}handle(rawUrl,response){let url=new URL(rawUrl,this.redirectUrl);if(!this.paths.includes(url.pathname)){this.reply(response,404,{ok:!1,message:"Not found"});return}let state=url.searchParams.get("state"),pending=state?this.pending.get(state):void 0;if(!state||!pending){this.reply(response,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(pending.timer),this.pending.delete(state),pending.path!==void 0&&url.pathname!==pending.path){pending.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(response,400,{ok:!1,message:"Unexpected redirect URI"});return}let error=url.searchParams.get("error");if(error){let description=url.searchParams.get("error_description")??error;pending.reject(new Error(description)),this.reply(response,200,{ok:!1,message:"Authorization failed. You may close this window.",details:description});return}let code=url.searchParams.get("code");if(!code){pending.reject(new Error("OAuth callback did not include an authorization code")),this.reply(response,400,{ok:!1,message:"Missing authorization code"});return}let iss=url.searchParams.get("iss");pending.resolve({code,state,...iss?{iss}:{}}),this.reply(response,200,{ok:!0})}};var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){super(`OAuth issuer mismatch: expected ${JSON.stringify(expected)}, received ${received===void 0?"none":JSON.stringify(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRegistrationError=class extends Error{status;body;constructor(status,body){super(`OAuth dynamic client registration failed with status ${status}: ${body}`),this.name="OAuthRegistrationError",this.status=status,this.body=body}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function object(value,name){if(!isObject(value))throw new Error(`Invalid ${name}`);return value}function compact(value){return Object.fromEntries(Object.entries(value).filter(([,item])=>item!==void 0))}function requiredString(value,name){if(typeof value!="string"||value.length===0)throw new Error(`Invalid ${name}`);return value}function absent(value){return value==null||value===""}function optionalString(value,name){if(!absent(value))return requiredString(value,name)}function optionalStrings(value,name){if(value!=null){if(!Array.isArray(value)||value.some(item=>typeof item!="string"))throw new Error(`Invalid ${name}`);return[...value]}}function safeUrl(value,name){let text=requiredString(value,name);if(!URL.canParse(text))throw new Error(`Invalid ${name}`);let url=new URL(text);if(["javascript:","data:","vbscript:"].includes(url.protocol))throw new Error(`Invalid ${name}`);return text}function optionalUrl(value,name){return absent(value)?void 0:safeUrl(value,name)}function parseProtectedResourceMetadata(value){let input=object(value,"OAuth protected resource metadata");return compact({...input,resource:safeUrl(input.resource,"OAuth protected resource metadata resource"),authorization_servers:optionalStrings(input.authorization_servers,"authorization_servers")?.map(url=>safeUrl(url,"authorization server URL")),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported")})}function parseAuthorizationServerMetadata(value){let input=object(value,"authorization server metadata"),responseTypes=optionalStrings(input.response_types_supported,"response_types_supported");if(!responseTypes)throw new Error("Invalid response_types_supported");return compact({...input,issuer:safeUrl(input.issuer,"authorization server issuer"),authorization_endpoint:safeUrl(input.authorization_endpoint,"authorization endpoint"),token_endpoint:safeUrl(input.token_endpoint,"token endpoint"),registration_endpoint:optionalUrl(input.registration_endpoint,"registration endpoint"),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported"),response_types_supported:responseTypes,grant_types_supported:optionalStrings(input.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:optionalStrings(input.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:optionalStrings(input.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof input.client_id_metadata_document_supported=="boolean"?input.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof input.authorization_response_iss_parameter_supported=="boolean"?input.authorization_response_iss_parameter_supported:void 0})}function parseOAuthTokens(value){let input=object(value,"OAuth token response"),expires=absent(input.expires_in)?void 0:Number(input.expires_in);if(expires!==void 0&&!Number.isFinite(expires))throw new Error("Invalid expires_in");return compact({access_token:requiredString(input.access_token,"access_token"),token_type:requiredString(input.token_type,"token_type"),expires_in:expires,scope:optionalString(input.scope,"scope"),refresh_token:optionalString(input.refresh_token,"refresh_token"),id_token:optionalString(input.id_token,"id_token")})}function parseClientInformation(value){let input=object(value,"OAuth client registration response");return compact({...input,client_id:requiredString(input.client_id,"client_id"),client_secret:optionalString(input.client_secret,"client_secret"),client_id_issued_at:typeof input.client_id_issued_at=="number"?input.client_id_issued_at:void 0,client_secret_expires_at:typeof input.client_secret_expires_at=="number"?input.client_secret_expires_at:void 0,redirect_uris:optionalStrings(input.redirect_uris,"redirect_uris")??[]})}function discard(response){response?.body?.cancel().catch(()=>{})}function isDiscoveryMiss(status){return status>=400&&status<500||status===502}function pathSuffix(pathname){return pathname.endsWith("/")?pathname.slice(0,-1):pathname}function field(header,name){let match=header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`,"i"));return match?.[1]||match?.[2]||void 0}function parseWwwAuthenticate(header){if(!header)return{};let scheme=header.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(scheme!=="bearer"&&scheme!=="dpop")return{};let resourceMetadata=field(header,"resource_metadata"),resourceMetadataUrl;if(resourceMetadata)try{resourceMetadataUrl=new URL(resourceMetadata)}catch{}return{resourceMetadataUrl,scope:field(header,"scope"),error:field(header,"error"),errorDescription:field(header,"error_description")}}async function fetchMetadata(url,fetch,protocolVersion){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion}})}async function discoverProtectedResourceMetadata(serverUrl,options={}){let server=new URL(serverUrl),fetch=options.fetch??globalThis.fetch,version=options.protocolVersion??LATEST_PROTOCOL_VERSION,response=await fetchMetadata(options.resourceMetadataUrl?new URL(options.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,server.origin),fetch,version);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version)),!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);return parseProtectedResourceMetadata(await response.json())}function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl){let issuer=new URL(authorizationServerUrl),path=pathSuffix(issuer.pathname),urls=[{url:new URL(`/.well-known/oauth-authorization-server${path}`,issuer.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${path}`,issuer.origin),type:"oidc"}];return path&&urls.push({url:new URL(`${path}/.well-known/openid-configuration`,issuer.origin),type:"oidc"}),urls}async function discoverAuthorizationServerMetadata(authorizationServerUrl,options={}){let fetch=options.fetch??globalThis.fetch;for(let{url}of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)){let response=await fetchMetadata(url,fetch,options.protocolVersion??LATEST_PROTOCOL_VERSION);if(!response.ok){if(discard(response),isDiscoveryMiss(response.status))continue;throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`)}let metadata=parseAuthorizationServerMetadata(await response.json());if(!options.skipIssuerValidation){let expected=String(authorizationServerUrl),trim=value=>value.endsWith("/")?value.slice(0,-1):value;if(trim(metadata.issuer)!==trim(expected))throw new OAuthIssuerMismatchError(expected,metadata.issuer)}return metadata}}async function discoverOAuthServerInfo(serverUrl,options={}){let resourceMetadata;try{resourceMetadata=await discoverProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,fetch:options.fetch})}catch(error){if(error instanceof TypeError)throw error}if(options.authorizationServerMetadataUrl){let url=options.authorizationServerMetadataUrl,response=await fetchMetadata(url,options.fetch??globalThis.fetch,LATEST_PROTOCOL_VERSION);if(!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);let metadata=parseAuthorizationServerMetadata(await response.json());return{authorizationServerUrl:metadata.issuer,authorizationServerMetadata:metadata,resourceMetadata}}let authorizationServerUrl=resourceMetadata?.authorization_servers?.[0]??String(new URL("/",serverUrl));return{authorizationServerUrl,authorizationServerMetadata:await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation}),resourceMetadata}}function resourceUrlFromServerUrl(value){let url=new URL(value);return url.hash="",url}function selectResource(serverUrl,metadata){if(!metadata)return;let requested=resourceUrlFromServerUrl(serverUrl),configured=new URL(metadata.resource);if(requested.origin!==configured.origin)throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);let requestedPath=requested.pathname.endsWith("/")?requested.pathname:`${requested.pathname}/`,configuredPath=configured.pathname.endsWith("/")?configured.pathname:`${configured.pathname}/`;if(!requestedPath.startsWith(configuredPath))throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);return metadata.resource}function loopback(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function secureEndpoint(value){let url=new URL(value);if(url.protocol!=="https:"&&!loopback(url.hostname))throw new OAuthInsecureEndpointError(url.href);return url}function selectClientAuthMethod(information,supported){let hinted="token_endpoint_auth_method"in information?information.token_endpoint_auth_method:void 0;return hinted&&["client_secret_basic","client_secret_post","none"].includes(hinted)&&(supported.length===0||supported.includes(hinted))?hinted:supported.length===0?information.client_secret?"client_secret_basic":"none":information.client_secret&&supported.includes("client_secret_basic")?"client_secret_basic":information.client_secret&&supported.includes("client_secret_post")?"client_secret_post":supported.includes("none")?"none":information.client_secret?"client_secret_post":"none"}function applyClientAuthentication(method,information,headers,params){if(method==="client_secret_basic"){if(!information.client_secret)throw new Error("client_secret_basic requires a client secret");headers.set("Authorization",`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`)}else params.set("client_id",information.client_id),method==="client_secret_post"&&information.client_secret&¶ms.set("client_secret",information.client_secret)}async function pkce(){let bytes=crypto.getRandomValues(new Uint8Array(32)),verifier=Buffer.from(bytes).toString("base64url"),digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:Buffer.from(digest).toString("base64url")}}async function startAuthorization(authorizationServerUrl,options){let metadata=options.metadata;if(metadata&&!metadata.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(metadata?.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let url=new URL(metadata?.authorization_endpoint??new URL("/authorize",authorizationServerUrl)),{verifier,challenge}=await pkce();return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",options.clientInformation.client_id),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("redirect_uri",String(options.redirectUrl)),options.state&&url.searchParams.set("state",options.state),options.scope&&url.searchParams.set("scope",options.scope),options.scope?.split(/\s+/).includes("offline_access")&&url.searchParams.set("prompt","consent"),options.resource&&url.searchParams.set("resource",options.resource),{authorizationUrl:url,codeVerifier:verifier}}async function tokenRequest(authorizationServerUrl,options,params){let url=secureEndpoint(options.metadata?.token_endpoint??new URL("/token",authorizationServerUrl)),headers=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});options.resource&¶ms.set("resource",options.resource),options.addClientAuthentication?await options.addClientAuthentication(headers,params,url,options.metadata):applyClientAuthentication(selectClientAuthMethod(options.clientInformation,options.metadata?.token_endpoint_auth_methods_supported??[]),options.clientInformation,headers,params);let response=await(options.fetch??globalThis.fetch)(url,{method:"POST",headers,body:params}),text=await response.text(),value;try{value=JSON.parse(text)}catch{}if(isObject(value)&&typeof value.error=="string")throw new OAuthError(value.error,typeof value.error_description=="string"?value.error_description:value.error,typeof value.error_uri=="string"?value.error_uri:void 0);if(!response.ok)throw new OAuthError("server_error",`HTTP ${response.status}: ${text}`);return parseOAuthTokens(value)}async function registerClient(authorizationServerUrl,options){let endpoint=options.metadata?.registration_endpoint;if(options.metadata&&!endpoint)throw new Error("Authorization server does not support dynamic client registration");let response=await(options.fetch??globalThis.fetch)(new URL(endpoint??new URL("/register",authorizationServerUrl)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...options.clientMetadata,...options.scope?{scope:options.scope}:{}})});if(!response.ok)throw new OAuthRegistrationError(response.status,await response.text());return parseClientInformation(await response.json())}async function exchangeAuthorizationCode(authorizationServerUrl,options){return tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"authorization_code",code:options.code,code_verifier:options.codeVerifier,redirect_uri:String(options.redirectUrl)}))}async function refreshAuthorization(authorizationServerUrl,options){let tokens=await tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"refresh_token",refresh_token:options.refreshToken}));return{refresh_token:options.refreshToken,...tokens}}function withScope(tokens,scope){return tokens.scope===void 0&&scope?{...tokens,scope}:tokens}function stepUpScope(granted,challenged){if(!challenged)return;let scopes=[granted,challenged].flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]);return[...new Set(scopes)].join(" ")}async function runFlow(provider,options){let metadataUrl=options.authorizationServerMetadataUrl&&secureEndpoint(options.authorizationServerMetadataUrl),cached=metadataUrl?void 0:await provider.discoveryState?.(),discovered=cached?.authorizationServerUrl?{authorizationServerUrl:cached.authorizationServerUrl,authorizationServerMetadata:cached.authorizationServerMetadata??await discoverAuthorizationServerMetadata(cached.authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation});metadataUrl||await provider.saveDiscoveryState?.({...discovered,...options.resourceMetadataUrl?{resourceMetadataUrl:options.resourceMetadataUrl.href}:{}});let metadata=discovered.authorizationServerMetadata,resource=selectResource(options.serverUrl,discovered.resourceMetadata),scope=options.scope||discovered.resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,stored=await provider.clientInformation(),clientDocument=stored?void 0:provider.clientMetadataDocument?.(metadata);if(clientDocument){let url=new URL(clientDocument.url);if(url.protocol!=="https:"||url.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let client=stored??(clientDocument&&{client_id:clientDocument.url});if(!client){if(options.authorizationCode)throw new Error("OAuth client information is missing during code exchange");if(!provider.saveClientInformation)throw new Error("OAuth client information cannot be persisted");client=await registerClient(discovered.authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope,fetch:options.fetch}),await provider.saveClientInformation(client)}let redirectUrl=clientDocument?.redirectUrl??provider.redirectUrl,tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch};if(options.authorizationCode){let iss=options.iss;if(metadata&&(iss!==void 0||metadata.authorization_response_iss_parameter_supported)&&iss!==metadata.issuer)throw new OAuthIssuerMismatchError(metadata.issuer,iss);let tokens=await exchangeAuthorizationCode(discovered.authorizationServerUrl,{...tokenOptions,code:options.authorizationCode,codeVerifier:await provider.codeVerifier(),redirectUrl});return await provider.saveTokens(withScope(tokens,scope)),"AUTHORIZED"}let existing=options.skipRefresh?void 0:await provider.tokens();if(existing?.refresh_token)try{let tokens=await refreshAuthorization(discovered.authorizationServerUrl,{...tokenOptions,refreshToken:existing.refresh_token});return await provider.saveTokens(withScope(tokens,existing.scope)),"AUTHORIZED"}catch(error){if(error instanceof OAuthInsecureEndpointError||error instanceof OAuthError&&error.code!=="server_error")throw error}let state=await provider.state?.(),authorization=await startAuthorization(discovered.authorizationServerUrl,{metadata,clientInformation:client,redirectUrl,scope,state,resource});return await provider.saveCodeVerifier(authorization.codeVerifier),await provider.redirectToAuthorization(authorization.authorizationUrl),"REDIRECT"}async function authorizeMcp(provider,options){try{return await runFlow(provider,options)}catch(error){if(error instanceof OAuthError&&["invalid_client","unauthorized_client"].includes(error.code))return await provider.invalidateCredentials?.("all"),runFlow(provider,options);if(error instanceof OAuthError&&error.code==="invalid_grant")return await provider.invalidateCredentials?.("tokens"),runFlow(provider,options);throw error}}var MemoryOAuthStateStore=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(state){this.value=structuredClone(state)}},McpOAuthProvider=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(options){this.serverUrl=String(new URL(options.serverUrl)),this.redirectUrl=String(options.redirectUrl),this.clientMetadata={...options.clientMetadata,redirect_uris:options.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:options.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:options.clientMetadata.response_types??["code"],token_endpoint_auth_method:options.clientMetadata.token_endpoint_auth_method??(options.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=options.clientMetadataDocument,this.configuredClient=options.clientId?{client_id:options.clientId,...options.clientSecret?{client_secret:options.clientSecret}:{}}:void 0,this.store=options.store??new MemoryOAuthStateStore,this.onRedirect=options.onRedirect}async state(){let existing=(await this.load()).oauthState;if(existing)return existing;let state=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(value=>({...value,oauthState:state})),state}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(information){this.configuredClient||await this.update(value=>({...value,clientInformation:information}))}async tokens(){return(await this.load()).tokens}async saveTokens(tokens){let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1e3;await this.update(value=>{let next={...value,tokens};return expiresAt===void 0?delete next.tokensExpireAt:next.tokensExpireAt=expiresAt,next})}async redirectToAuthorization(url){await this.onRedirect(url)}async saveCodeVerifier(verifier){await this.update(value=>({...value,codeVerifier:verifier}))}async codeVerifier(){let verifier=(await this.load()).codeVerifier;if(!verifier)throw new Error("No OAuth PKCE code verifier is stored");return verifier}async invalidateCredentials(kind){await this.update(value=>{let next={...value};return(kind==="all"||kind==="client")&&delete next.clientInformation,(kind==="all"||kind==="tokens")&&(delete next.tokens,delete next.tokensExpireAt),(kind==="all"||kind==="verifier")&&delete next.codeVerifier,(kind==="all"||kind==="discovery")&&delete next.discovery,kind==="all"&&delete next.oauthState,next})}async saveDiscoveryState(discovery){await this.update(value=>({...value,discovery}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(update){this.writes=this.writes.then(async()=>{await this.store.save(update(this.own(await this.store.load())))}),await this.writes}own(state){return state?.serverUrl===this.serverUrl?state:{serverUrl:this.serverUrl}}};import{createHash}from"node:crypto";import{mkdirSync}from"node:fs";import{join}from"node:path";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
|
|
5
5
|
<html lang="en">
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{retryProviderRequest}from"./chunk-LD2P6SFZ.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-7JGR3GZN.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
|
|
2
|
+
import{retryProviderRequest}from"./chunk-LD2P6SFZ.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-HQHD6PZI.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-KJUDFE6Y.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
|
|
3
3
|
`)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
|
|
4
4
|
Content-Type: ${partContentType}\r
|
|
5
5
|
\r
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{Text,getBinDir,getCapabilities,getImageDimensions,hyperlink,imageFallback,resolvePath,truncateToWidth}from"./chunk-AXOERKKW.js";import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&existsSync(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(existsSync(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(existsSync(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
|
|
3
|
+
1. Install Git for Windows: https://git-scm.com/download/win
|
|
4
|
+
2. Add your bash to PATH (Cygwin, MSYS2, etc.)
|
|
5
|
+
3. Set shellPath in settings.json
|
|
6
|
+
|
|
7
|
+
Searched Git Bash in:
|
|
8
|
+
${paths.map(p=>` ${p}`).join(`
|
|
9
|
+
`)}`)}if(existsSync("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe")??findExecutableOnPath("powershell.exe");if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter);return{...process.env,[pathKey]:updatedPath}}function sanitizeBinaryOutput(str2){return str2.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn(join(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join2}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join2(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(`
|
|
10
|
+
`);return content.endsWith(`
|
|
11
|
+
`)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
|
|
12
|
+
`),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
|
|
13
|
+
`),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str2,maxBytes){let buf=Buffer.from(str2,"utf-8");if(buf.length<=maxBytes)return str2;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}function truncateMiddle(content,maxBytes){let buf=Buffer.from(content,"utf-8"),totalLines=splitLinesForCounting(content).length;if(buf.length<=maxBytes)return{content,truncated:!1,removedChars:0,totalBytes:buf.length,totalLines};let isBoundary=index=>index>=buf.length||(buf[index]&192)!==128,headEnd=Math.floor(maxBytes/2);for(;headEnd>0&&!isBoundary(headEnd);)headEnd--;let tailStart=buf.length-(maxBytes-Math.floor(maxBytes/2));for(;tailStart<buf.length&&!isBoundary(tailStart);)tailStart++;let head=buf.subarray(0,headEnd).toString("utf-8"),tail=buf.subarray(tailStart).toString("utf-8"),removedChars=Array.from(buf.subarray(headEnd,tailStart).toString("utf-8")).length;return{content:`${head}\u2026${removedChars} chars truncated\u2026${tail}`,truncated:!0,removedChars,totalBytes:buf.length,totalLines}}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options){this.options=options}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};function ansiRegex({onlyFirst=!1}={}){let pattern="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(pattern,onlyFirst?void 0:"g")}var regex=ansiRegex();function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(regex,"")}import*as os from"node:os";import{pathToFileURL}from"node:url";function shortenPath(path){if(typeof path!="string")return"";let home=os.homedir();return path.startsWith(home)?`~${path.slice(home.length)}`:path}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
|
|
14
|
+
`),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
|
|
15
|
+
`);output=output?`${output}
|
|
16
|
+
${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme,expanded){let header=theme.fg("toolTitle",theme.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(text).replace(/\r/g,"").split(`
|
|
17
|
+
`).join(`
|
|
18
|
+
`)}`});return`${header}
|
|
19
|
+
${theme.fg("muted",lines.join(`
|
|
20
|
+
`))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme.fg("muted",preview)}`}function invalidArgText(theme){return theme.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme,cwd,options){if(rawPath===null)return invalidArgText(theme);let value=rawPath||options?.emptyFallback;return value?linkPath(theme.fg("accent",shortenPath(value)),value,cwd):theme.fg("toolOutput","...")}export{getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree,stripAnsi,writeOutputFile,createOutputFileStream,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,truncateToVisualLines,VisualLinePreview,shortenPath,str,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,invalidArgText,renderToolPath};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-
|
|
2
|
+
import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-HQHD6PZI.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-KJUDFE6Y.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
3
3
|
`),images=content.filter(c=>c.type==="image"),hasText=textResult.length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!allowedToolCallProviders.has(model.provider)||!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId),normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId),transcriptTools=resolveTranscriptTools(normalizedContext.messages,(options?.supportsAdditionalTools??!1)||(options?.supportsToolSearch??!1)),appendSystemToolAdditions=(message,seed)=>{let tools=transcriptTools.anchorsAdditions?message.toolsAdded??[]:[];if(tools.length===0)return;if(options?.supportsAdditionalTools){messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options.toolOptions)});return}if(!options?.supportsToolSearch)return;let names=tools.map(tool=>tool.name),callId=`pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options.toolOptions,toolSearchResult:!0})})},includeInitialSystemMessage=options?.includeSystemPrompt??!0,compat=model.compat,instructionRole=model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="system"){if(isLeadingSystemMessage||appendSystemToolAdditions(msg,`system:${msgIndex}`),!isLeadingSystemMessage||includeInitialSystemMessage){let text=isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}}else if(msg.role==="user")if(typeof msg.content=="string")messages.push({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]});else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push({role:"user",content})}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0;for(let block of msg.content)if(block.type==="thinking"){if(block.thinkingSignature){let reasoningItem=JSON.parse(block.thinkingSignature);output.push(reasoningItem)}}else if(block.type==="text"){let textBlock=block,parsedSignature=parseTextSignature(textBlock.textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(textBlock.text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),itemId=itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0),customInputProperty!==void 0?output.push({type:"custom_tool_call",id:itemId,call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",id:itemId,call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;messages.push(...output)}else if(msg.role==="toolResult"){let[callId]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content);options?.grammarToolInputProperties?.has(msg.toolName)?messages.push({type:"custom_tool_call_output",call_id:callId,output}):messages.push({type:"function_call_output",call_id:callId,output})}isLeadingSystemMessage||msgIndex++}return messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function appendCustomToolCallInput(block,nextInput,close){let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta}async function processResponsesStream(openaiStream,output,stream,model,options){let sawTerminalResponseEvent=!1,outputSlots=new Map,reasoningBlocksById=new Map,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block={type:"thinking",thinking:""};output.content.push(block);let slot={type:"thinking",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"thinking_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="message"){applyMessagePhaseStopReason(item);let block={type:"text",text:""};output.content.push(block);let slot={type:"text",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"text_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="function_call"){let block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="custom_tool_call"){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item),backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=JSON.parse(block.thinkingSignature);storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{if(sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),response?.id&&(output.responseId=response.id),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens||0;output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,reasoning:response.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of openaiStream)if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
4
4
|
|
|
5
5
|
`,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";var DEFAULT_AZURE_API_VERSION="v1";function parseDeploymentNameMap(value){let map=new Map;if(!value)return map;for(let entry of value.split(",")){let trimmed=entry.trim();if(!trimmed)continue;let[modelId,deploymentName]=trimmed.split("=",2);!modelId||!deploymentName||map.set(modelId.trim(),deploymentName.trim())}return map}function resolveDeploymentName(model,options){return options?.azureDeploymentName?options.azureDeploymentName:parseDeploymentNameMap(getProviderEnvValue("AZURE_OPENAI_DEPLOYMENT_NAME_MAP",options?.env)).get(model.id)||model.id}function normalizeAzureBaseUrl(baseUrl){let trimmed=baseUrl.trim().replace(/\/+$/,""),url;try{url=new URL(trimmed)}catch{throw new Error(`Invalid Azure OpenAI base URL: ${baseUrl}`)}let isAzureHost=url.hostname.endsWith(".openai.azure.com")||url.hostname.endsWith(".cognitiveservices.azure.com")||url.hostname.endsWith(".ai.azure.com"),normalizedPath=url.pathname.replace(/\/+$/,"");return isAzureHost&&(normalizedPath===""||normalizedPath==="/"||normalizedPath==="/openai"||normalizedPath==="/openai/v1/responses")&&(url.pathname="/openai/v1",url.search=""),url.toString().replace(/\/+$/,"")}function buildDefaultBaseUrl(resourceName){return`https://${resourceName}.openai.azure.com/openai/v1`}function resolveAzureBaseUrl(model,options){let baseUrl=options?.azureBaseUrl?.trim()||getProviderEnvValue("AZURE_OPENAI_BASE_URL",options?.env)?.trim()||void 0,resourceName=options?.azureResourceName||getProviderEnvValue("AZURE_OPENAI_RESOURCE_NAME",options?.env),resolvedBaseUrl=baseUrl;if(!resolvedBaseUrl&&resourceName&&(resolvedBaseUrl=buildDefaultBaseUrl(resourceName)),!resolvedBaseUrl&&model.baseUrl&&(resolvedBaseUrl=model.baseUrl),!resolvedBaseUrl)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return normalizeAzureBaseUrl(resolvedBaseUrl)}function resolveAzureConfig(model,options){return{baseUrl:resolveAzureBaseUrl(model,options),apiVersion:options?.azureApiVersion||getProviderEnvValue("AZURE_OPENAI_API_VERSION",options?.env)||DEFAULT_AZURE_API_VERSION}}export{resolveDeploymentName,resolveAzureBaseUrl,resolveAzureConfig};
|