pi-namespace-patch 1.0.0-namespace.2 → 1.0.2-namespace.2
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 +54 -0
- package/README.md +22 -4
- package/dist/bundle/chunks/{anthropic-messages-UID2PALB.js → anthropic-messages-MVG2FL56.js} +3 -3
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
- package/dist/bundle/chunks/chunk-2KAZSACP.js +2 -0
- package/dist/bundle/chunks/{chunk-2KTBZM5G.js → chunk-6FX7UEPL.js} +5 -5
- package/dist/bundle/chunks/{chunk-2VNGUWBO.js → chunk-BYB6ZAAQ.js} +1 -1
- package/dist/bundle/chunks/chunk-DN3QEIXS.js +2 -0
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
- package/dist/bundle/chunks/{chunk-3LH3ZQKY.js → chunk-G7EDXK4D.js} +1 -1
- package/dist/bundle/chunks/chunk-IKZJX7ZT.js +2 -0
- package/dist/bundle/chunks/{chunk-4N5K4RKC.js → chunk-OLBCNJCL.js} +31 -32
- package/dist/bundle/chunks/{chunk-PRD6WYBT.js → chunk-OYBSLV7Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-IBCPYVFK.js → chunk-PDFMCAOZ.js} +4 -4
- package/dist/bundle/chunks/{chunk-LTXEMVMA.js → chunk-SYF2TF6W.js} +2 -2
- package/dist/bundle/chunks/chunk-WCQZGZ6I.js +82 -0
- package/dist/bundle/chunks/{chunk-KDN6RCEQ.js → chunk-ZSI3BL5Q.js} +2 -2
- package/dist/bundle/chunks/{cli-QOMC26IJ.js → cli-KILDDGW3.js} +2 -2
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-NPQN263E.js → cloudflare-workers-ai-system-one-X5PVWWYJ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +24 -3
- package/dist/bundle/chunks/easter-egg-3d-T5FFWIBR.js +2 -0
- package/dist/bundle/chunks/{execute-GVRSEGHL.js → execute-RYVK27GT.js} +25 -4
- package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-MXCOSOY3.js → google-vertex-VKWZQ3AY.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js} +1 -1
- package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-GK67DQQJ.js → openai-codex-responses-TC3OK7B4.js} +1 -1
- package/dist/bundle/chunks/openai-completions-GWHGMQ3T.js +7 -0
- package/dist/bundle/chunks/openai-responses-EZ7FJ2KL.js +3 -0
- package/dist/bundle/chunks/{runtime-2SO2JDWM.js → runtime-D5I2NTIF.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.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/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts +3 -3
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +6 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +11 -0
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +36 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +14 -2
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/provider-composer.d.ts +2 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +13 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/tools/renderers/index.d.ts +2 -2
- package/dist/core/tools/renderers/index.d.ts.map +1 -1
- package/dist/core/tools/renderers/index.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +3 -0
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +15 -3
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +46 -10
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +4 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +80 -45
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +4 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +54 -10
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +1 -0
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +3 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +19 -13
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +8 -4
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts +3 -0
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.js +7 -5
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/auth-url.d.ts +14 -0
- package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
- package/dist/modes/interactive/components/auth-url.js +37 -0
- package/dist/modes/interactive/components/auth-url.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
- package/dist/modes/interactive/components/{pi-logo-animation.js → easter-egg-3d.js} +127 -74
- package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +0 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +0 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +11 -5
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -18
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -45
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +15 -17
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +12 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/image-convert.d.ts +12 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js +45 -6
- package/dist/utils/image-convert.js.map +1 -1
- package/docs/cli.md +2 -0
- package/docs/codemode.md +1 -1
- package/docs/extensions.md +4 -0
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +23 -1
- package/docs/models.md +28 -2
- package/docs/quickstart.md +16 -2
- 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 +13 -14
- package/dist/bundle/chunks/azure-openai-responses-AFMVM6NP.js +0 -2
- package/dist/bundle/chunks/chunk-6D7LHLKG.js +0 -2
- package/dist/bundle/chunks/chunk-7FH3BDRG.js +0 -82
- package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +0 -42
- package/dist/bundle/chunks/chunk-MJOHEBV7.js +0 -2
- package/dist/bundle/chunks/node-O3RIBJRH.js +0 -16
- package/dist/bundle/chunks/openai-completions-JXDDPZ23.js +0 -7
- package/dist/bundle/chunks/openai-responses-CQDDLDQF.js +0 -3
- package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +0 -2
- package/dist/bundle/chunks/virtual-modules-3THEGRQQ.js +0 -2
- package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -140
- package/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.d.ts +0 -68
- package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +0 -7
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js +0 -12
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +0 -1
- package/npm-shrinkwrap.json +0 -1952
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-3LH3ZQKY.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-6D7LHLKG.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",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:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-G7EDXK4D.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",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:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js}
RENAMED
|
@@ -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{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-
|
|
2
|
+
import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){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:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{statusCode;body;constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
3
3
|
`).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))},currentTools=getCurrentTools(context.messages);return currentTools.length>0&&(payload.tools=toFunctionTools(currentTools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream,onProviderStreamEvent){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(await onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);if(!textDelta)continue;(!currentBlock||currentBlock.type!=="text")&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;(!currentBlock||currentBlock.type!=="thinking")&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");if(!textDelta)continue;(!currentBlock||currentBlock.type!=="text")&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let[index,msg]of messages.entries()){if(msg.role==="system"){let text=index===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&result.push({role:"system",content:sanitizeSurrogates(text)});continue}if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.push({role:"user",content});continue}hadImages&&!supportsImages&&result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
|
|
4
4
|
`),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
|
|
5
5
|
[tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{child_process,crypto,fs,path,stream,util}from"./chunk-7ZC4UXSL.js";import{AnthropicError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MIN_MEMORY_SYNC_INTERVAL_MS,ToolError,__classPrivateFieldGet,__classPrivateFieldSet,checkMemorySyncInterval,decodeUTF8,encodeUTF8,isStatus,loggerFor,promiseWithResolvers}from"./chunk-F5ZABL6Z.js";import"./chunk-4L3WN2XY.js";import*as fs4 from"node:fs/promises";import*as fssync from"node:fs";import*as path2 from"node:path";import*as cp from"node:child_process";import*as crypto2 from"node:crypto";import*as readline from"node:readline";function betaTool(options){if(options.inputSchema.type!=="object")throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`);return{type:"custom",name:options.name,input_schema:options.inputSchema,description:options.description,run:options.run,parse:content=>content,...options.close?{close:options.close}:{}}}var fs2=fs.promises,DIR_CREATE_MODE=448,FILE_CREATE_MODE=384;function isWithin(root,p){let rel=path.relative(root,p);return rel===""||!rel.startsWith(".."+path.sep)&&rel!==".."&&!path.isAbsolute(rel)}async function containingRoot(roots,target){for(let root of roots)if(isWithin(await canonicalize(path.resolve(root)),target))return root}var MAX_SYMLINK_HOPS=40;function errnoCode(err){let code=err?.code;return typeof code=="string"?code:void 0}async function canonicalize(abs){let tail=[],prefix=abs,hops=0;for(;;){let real;try{real=await fs2.realpath(prefix)}catch(realpathErr){let isLink;try{isLink=(await fs2.lstat(prefix)).isSymbolicLink()}catch(lstatErr){let code=errnoCode(lstatErr);if(code!=="ENOENT"&&code!=="ENOTDIR")throw lstatErr;let parent=path.dirname(prefix);if(parent===prefix)throw lstatErr;tail.push(path.basename(prefix)),prefix=parent;continue}if(!isLink)throw realpathErr;if(++hops>MAX_SYMLINK_HOPS)throw Object.assign(new Error("too many levels of symbolic links"),{code:"ELOOP"});prefix=path.resolve(path.dirname(prefix),await fs2.readlink(prefix));continue}return tail.length?path.join(real,...tail.reverse()):real}}async function confineToRoot(root,p,opts){let allowedRoots=opts?.allowedRoots??[],realRoot=await canonicalize(path.resolve(root)),real;try{real=await canonicalize(path.resolve(realRoot,p))}catch(err){throw new ToolError(fsErrorMessage(err,`path ${JSON.stringify(p)}`))}if(isWithin(realRoot,real)||await containingRoot(allowedRoots,real)!==void 0)return real;let permitted=allowedRoots.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new ToolError(`path ${JSON.stringify(p)} is outside ${permitted}`)}async function atomicWriteFile(targetPath,content){let dir=path.dirname(targetPath),tempPath=path.join(dir,`.tmp-${process.pid}-${crypto.randomUUID()}`),existingMode=await fs2.stat(targetPath).then(st=>st.mode&511,()=>{}),handle;try{handle=await fs2.open(tempPath,"wx",FILE_CREATE_MODE),existingMode!==void 0&&await handle.chmod(existingMode),await handle.writeFile(content,"utf-8"),await handle.sync(),await handle.close(),handle=void 0,await fs2.rename(tempPath,targetPath)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fs2.unlink(tempPath).catch(()=>{}),err}}function fsErrorMessage(err,file){let code=errnoCode(err);switch(code){case"ENOENT":return`${file}: no such file or directory`;case"EACCES":case"EPERM":return`${file}: permission denied`;case"ENOTDIR":return`${file}: not a directory`;case"EISDIR":return`${file}: is a directory`;case"ELOOP":return`${file}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${file}: file name too long`;case"ENOSPC":return`${file}: no space left on device`;case"EMFILE":case"ENFILE":return`${file}: too many open files`;default:return`${file}: ${code!==void 0?`i/o error (${code})`:"i/o error"}`}}var fs3=fs.promises,execFileAsync=util.promisify(child_process.execFile);async function setupSkills(ctx){let{client,sessionId}=ctx;if(!client)return async()=>{};let log=loggerFor(client),session=ctx.session;if(!session){if(sessionId===void 0)return async()=>{};log.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),session=await client.beta.sessions.retrieve(sessionId)}let skillsRoot=path.resolve(ctx.workdir,"skills"),created=[];for(let skill of session.agent.skills)try{let version=await client.beta.skills.versions.retrieve(skill.version,{skill_id:skill.skill_id}),dirname2=path.basename(version.name.trim());(dirname2===""||dirname2==="."||dirname2==="..")&&(dirname2=skill.skill_id);let dest=path.resolve(skillsRoot,dirname2);if(dest!==skillsRoot&&!dest.startsWith(skillsRoot+path.sep)){log.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:version.name});continue}let resp=await client.beta.skills.versions.download(version.id,{skill_id:skill.skill_id});await fs3.rm(dest,{recursive:!0,force:!0}),await fs3.mkdir(dest,{recursive:!0,mode:DIR_CREATE_MODE}),created.push(dest),await extractSkillArchive(resp,dest),log.info("downloaded skill",{component:"agent-tool-context",skill_id:skill.skill_id,version:version.id,dest})}catch(e){log.warn("failed to download skill",{component:"agent-tool-context",skill_id:skill.skill_id,error:String(e)})}return async()=>{for(let dest of created)await fs3.rm(dest,{recursive:!0,force:!0}).catch(e=>{log.warn("failed to clean up skill",{component:"agent-tool-context",dest,error:String(e)})})}}function assertSafeMemberNames(names){for(let raw of names){let entry=raw.trim();if(entry&&(path.isAbsolute(entry)||entry.split(/[\\/]/).includes("..")))throw new AnthropicError(`refusing to extract unsafe archive member: ${entry}`)}}var INCONSISTENT_LISTING="skill archive listing is inconsistent; refusing to extract",PLAIN_TYPE_CHARS={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function listingLines(listing){let lines=listing.split(`
|
|
3
|
+
`);return lines[lines.length-1]===""&&lines.pop(),lines}function canExcludeVerbatim(cmd,name){return/^[\x20-\x7E]+$/.test(name)&&!/[\\^#]/.test(name)&&!(cmd==="unzip"&&name.startsWith("-"))}function classifyArchiveListing(cmd,names,typed){let nameLines=listingLines(names),typedLines=listingLines(typed);if(nameLines.length!==typedLines.length)throw new AnthropicError(INCONSISTENT_LISTING);let plain=[],special=[];return nameLines.forEach((name,i)=>{if(PLAIN_TYPE_CHARS[cmd].has(typedLines[i].charAt(0))){plain.push(name);return}if(!canExcludeVerbatim(cmd,name))throw new AnthropicError(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(name)}`);special.push(name)}),{plain,special}}async function assertOnlyPlainEntries(dir){for(let entry of await fs3.readdir(dir,{withFileTypes:!0}))if(entry.isDirectory())await assertOnlyPlainEntries(path.join(dir,entry.name));else if(!entry.isFile())throw new AnthropicError(INCONSISTENT_LISTING)}async function runArchiveTool(cmd,args){try{let{stdout}=await execFileAsync(cmd,args);return stdout}catch(e){throw errnoCode(e)==="ENOENT"?new AnthropicError(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`):e}}function archiveTopDir(names){let top,nested=!1;for(let raw of names){let parts=raw.trim().split("/").filter(p=>p!==""&&p!==".");if(parts.length===0)continue;let first=parts[0];if(top===void 0)top=first;else if(first!==top)return"";parts.length>1&&(nested=!0)}return top!==void 0&&nested?top:""}async function extractSkillArchive(resp,dest){let tmp=path.join(dest,`.skill-archive-${process.pid}-${Date.now()}`);if(!resp.body)throw new AnthropicError("skill download response had no body");await stream.promises.pipeline(stream.Readable.fromWeb(resp.body),fs.createWriteStream(tmp));let stage=path.join(path.dirname(dest),`.skill-stage-${process.pid}-${Date.now()}`),excludeFile=path.join(path.dirname(dest),`.skill-exclude-${process.pid}-${Date.now()}`);try{let head=await readHead(tmp,4),isZip=head.length>=4&&head[0]===80&&head[1]===75&&head[2]===3&&head[3]===4,archiveCmd=isZip?"unzip":"tar",names=await runArchiveTool(archiveCmd,isZip?["-Z1",tmp]:["-tf",tmp]),typed=await runArchiveTool(archiveCmd,isZip?["-Z","--h","--t",tmp]:["-tvf",tmp]),{plain,special}=classifyArchiveListing(archiveCmd,names,typed);assertSafeMemberNames([...plain,...special]);let top=archiveTopDir(plain);await fs3.mkdir(stage,{recursive:!0,mode:DIR_CREATE_MODE}),plain.length>0&&await runArchiveTool(archiveCmd,await extractArgs(archiveCmd,tmp,stage,special,excludeFile)),await assertOnlyPlainEntries(stage);let srcRoot=top?path.join(stage,top):stage,entries=await fs3.readdir(srcRoot).catch(e=>{throw errnoCode(e)==="ENOENT"?new AnthropicError(INCONSISTENT_LISTING):e});for(let entry of entries)await fs3.rename(path.join(srcRoot,entry),path.join(dest,entry))}finally{await fs3.rm(tmp,{force:!0}),await fs3.rm(excludeFile,{force:!0}),await fs3.rm(stage,{recursive:!0,force:!0})}}async function extractArgs(cmd,archive,stage,special,excludeFile){let patterns=special.map(name=>name.replace(/[*?[\\]/g,"\\$&"));return cmd==="unzip"?["-oq",archive,"-d",stage,...patterns.length>0?["-x",...patterns]:[]]:patterns.length===0?["-xf",archive,"-C",stage]:(await fs3.writeFile(excludeFile,patterns.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",archive,"-C",stage,"-X",excludeFile])}async function readHead(file,n){let handle=await fs3.open(file,"r");try{let buf=Buffer.alloc(n),{bytesRead}=await handle.read(buf,0,n,0);return buf.subarray(0,bytesRead)}finally{await handle.close()}}var fsp=fs.promises,C=fs.constants,OWNER_ONLY_DIR_MODE=448,OWNER_ONLY_FILE_MODE=384,OWNER_ONLY_EXEC_MODE=448,O_NOFOLLOW=C.O_NOFOLLOW??0,O_NONBLOCK=C.O_NONBLOCK??0,FileStoreError=(()=>{class FileStoreError2 extends Error{constructor(reason,relPath){super(`path ${JSON.stringify(relPath)} ${reason}`),this.name="FileStoreError",this.reason=reason,this.relPath=relPath}}return FileStoreError2.ESCAPES_ROOT="escapes the store root",FileStoreError2.IS_A_SYMLINK="is a symlink",FileStoreError2.NOT_A_FILE="is not a regular file",FileStoreError2.NOT_A_DIRECTORY="is not a directory",FileStoreError2.NOT_UTF8="is not valid utf-8",FileStoreError2.MOVE_DESTINATION_EXISTS="already exists",FileStoreError2})();function isPathLegal(p){return p.startsWith("/")&&!p.split("/").includes("..")}var FileStore=(()=>{class FileStore2{constructor(root,removedOnDispose,utf8Only=!1){this.hashes=new Map,this.rootPath=root,this.removedOnDispose=removedOnDispose,this.decoder=utf8Only?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(root,opts){if(!platformSupported())throw new Error("FileStore requires O_NOFOLLOW support on this platform");let removedOnDispose=!1;try{await fsp.lstat(root)}catch(e){if(e.code!=="ENOENT")throw e;removedOnDispose=!0}return new FileStore2(path.resolve(root),removedOnDispose,opts?.utf8??!1)}async createRoot(){await makeDirAndAncestors(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){this.removedOnDispose&&await fsp.rm(this.rootPath,{recursive:!0,force:!0})}async put(relPath,data,opts){let tail=relPath.replace(/\\/g,"/");if(tail.endsWith("/")||tail.endsWith("/.")||tail===""||tail===".")throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let dest=this.resolveUnderRoot(relPath),payload=typeof data=="string"?encodeUTF8(data):data;this.requireUtf8(relPath,payload),await makeDirsBelowRoot(this.rootPath,path.dirname(dest)),await replaceViaTemp(dest,payload,opts?.executable??!1)}async get(relPath){let dest=this.resolveUnderRoot(relPath),handle;try{handle=await openRegularFile(relPath,dest)}catch(e){if(e.code==="ENOENT")return null;throw e}let data;try{let buf=await handle.readFile();data=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}finally{await handle.close()}return this.requireUtf8(relPath,data),data}async ls(under="/"){let base=this.resolveUnderRoot(under);return new Set((await filenamesInDir(this.rootPath,under,base)).map(([rel])=>rel))}async findSymlinks(under="/"){let base=this.resolveUnderRoot(under);return symlinksInDir(this.rootPath,under,base)}async hashtree(under="/"){let base=this.resolveUnderRoot(under),walkStartNs=_internals.nowNs(),out=Object.create(null);for(let[rel,full]of await filenamesInDir(this.rootPath,under,base)){let sha=await this.hashViaCache(rel,full,walkStartNs);sha!==null&&(out[rel]=sha)}return out}async hashFile(relPath){let dest=this.resolveUnderRoot(relPath),st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(st.isSymbolicLink())throw new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath);if(!st.isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let rel=path.relative(this.rootPath,dest).split(path.sep).join("/");return this.hashViaCache(rel,dest,_internals.nowNs())}async move(src,dst){let s=this.resolveUnderRoot(src),d=this.resolveUnderRoot(dst);if(s===this.rootPath||d===this.rootPath)return;if(await fsp.stat(d).then(()=>!0,()=>!1))throw new FileStoreError(FileStoreError.MOVE_DESTINATION_EXISTS,dst);await makeDirsBelowRoot(this.rootPath,path.dirname(d)),await fsp.rename(s,d)}async remove(relPath){let dest=this.resolveUnderRoot(relPath);if(dest===this.rootPath)return;let st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}if(st.isDirectory())await fsp.rm(dest,{recursive:!0,force:!0});else try{await fsp.unlink(dest)}catch(e){if(e.code!=="ENOENT")throw e}}resolveUnderRoot(relPath){let norm=relPath.replace(/\\/g,"/").replace(/^\/+/,""),parts=norm.split("/").filter(p=>p!==""&&p!==".");if(path.posix.isAbsolute(norm)||parts.includes(".."))throw new FileStoreError(FileStoreError.ESCAPES_ROOT,relPath);return parts.length===0?this.rootPath:path.join(this.rootPath,...parts)}requireUtf8(relPath,data){if(this.decoder)try{this.decoder.decode(data)}catch{throw new FileStoreError(FileStoreError.NOT_UTF8,relPath)}}async hashViaCache(rel,full,walkStartNs){let st;try{st=await fsp.lstat(full,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(!st.isFile())return null;let cached=this.hashes.get(rel),sha;if(cached!==void 0&&unchangedSinceHashed(cached,st))sha=cached.sha;else try{sha=await _internals.hashFile(full)}catch(e){let code=e.code;if(code==="ENOENT"||e instanceof FileStoreError||code==="ELOOP"||code==="EMLINK")return null;throw e}return oldEnoughToCache(st,walkStartNs)&&this.hashes.set(rel,{mtimeNs:st.mtimeNs,ctimeNs:st.ctimeNs,size:st.size,sha}),sha}}return FileStore2.isPathLegal=isPathLegal,FileStore2})();function platformSupported(){return O_NOFOLLOW!==0}async function makeDirAndAncestors(dir){let missing=[],current=dir;for(;;){try{await fsp.stat(current);break}catch(e){let code=e.code;if(code!=="ENOENT"&&code!=="ENOTDIR"&&code!=="ELOOP")throw e}missing.push(current);let parent=path.dirname(current);if(parent===current)break;current=parent}for(let directory of missing.reverse())try{await fsp.mkdir(directory,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}async function makeDirsBelowRoot(root,dir){let below=path.relative(root,dir);if(below==="")return;let current=root;for(let part of below.split(path.sep)){current=path.join(current,part);try{await fsp.mkdir(current,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}}async function replaceViaTemp(dest,data,isExecutable){let mode=isExecutable?OWNER_ONLY_EXEC_MODE:OWNER_ONLY_FILE_MODE,tmp=path.join(path.dirname(dest),`.fs-${crypto.randomBytes(8).toString("hex")}.tmp`),handle;try{handle=await fsp.open(tmp,C.O_WRONLY|C.O_CREAT|C.O_EXCL|O_NOFOLLOW,mode),await handle.writeFile(data),await handle.close(),handle=void 0,await fsp.rename(tmp,dest)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fsp.unlink(tmp).catch(()=>{}),err}}async function openRegularFile(relPath,dest){let handle;try{handle=await fsp.open(dest,C.O_RDONLY|O_NOFOLLOW|O_NONBLOCK)}catch(e){let code=e.code;throw code==="ELOOP"||code==="EMLINK"?new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath):e}try{if(!(await handle.stat()).isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath)}catch(e){throw await handle.close().catch(()=>{}),e}return handle}async function hashFile(full){let digest=crypto.createHash("sha256"),handle=await openRegularFile(path.basename(full),full),buf=new Uint8Array(1024*1024);try{for(;;){let{bytesRead}=await handle.read(buf,0,buf.length);if(bytesRead===0)break;digest.update(buf.subarray(0,bytesRead))}}finally{await handle.close()}return digest.digest("hex")}async function filenamesInDir(root,under,base){if(!await requireDir(under,base))return[];let out=[];return await walk(base,(full,entry)=>{entry.isFile()&&out.push([path.relative(root,full).split(path.sep).join("/"),full])}),out.sort(),out}async function symlinksInDir(root,under,base){let relOf=full=>path.relative(root,full).split(path.sep).join("/"),st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return new Set;throw e}if(st.isSymbolicLink())return new Set([relOf(base)]);if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);let out=new Set;return await walk(base,(full,entry)=>{entry.isSymbolicLink()&&out.add(relOf(full))}),out}async function requireDir(under,base){let st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return!1;throw e}if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);return!0}async function walk(base,visit){let stack=[base];for(;stack.length;){let dir=stack.pop(),entries;try{entries=await fsp.readdir(dir,{withFileTypes:!0})}catch(e){if(e.code==="ENOENT")continue;throw e}for(let entry of entries){let full=path.join(dir,entry.name);visit(full,entry),entry.isDirectory()&&!entry.isSymbolicLink()&&stack.push(full)}}}function unchangedSinceHashed(cached,st){return st.mtimeNs===cached.mtimeNs&&st.ctimeNs===cached.ctimeNs&&st.size===cached.size}function oldEnoughToCache(st,walkStartNs){return(st.mtimeNs>st.ctimeNs?st.mtimeNs:st.ctimeNs)<walkStartNs-_internals.timestampTrustMarginNs}var TIMESTAMP_TRUST_MARGIN_NS=2000000000n,_internals={hashFile,timestampTrustMarginNs:TIMESTAMP_TRUST_MARGIN_NS,nowNs:()=>BigInt(Date.now())*1000000n},LocalFileStore=FileStore,asyncDispose=Symbol.asyncDispose;asyncDispose&&Object.defineProperty(FileStore.prototype,asyncDispose,{value:FileStore.prototype.dispose,configurable:!0,writable:!0});var _SessionMemoryStores_instances,_SessionMemoryStores_client,_SessionMemoryStores_workdir,_SessionMemoryStores_syncIntervalMs,_SessionMemoryStores_syncDeletions,_SessionMemoryStores_log,_SessionMemoryStores_lastSyncAt,_SessionMemoryStores_finished,_SessionMemoryStores_stores,_SessionMemoryStores_storeRoot,_SessionMemoryStores_scanMarker,_SessionMemoryStores_syncStore,_SessionMemoryStores_flushStore,_SessionMemoryStores_recover,_SessionMemoryStores_stampAndPull,_SessionMemoryStores_syncPath,_SessionMemoryStores_removeLocal,_SessionMemoryStores_write,_SessionMemoryStores_pullAll,_SessionMemoryStores_uploadAll,_SessionMemoryStores_listMemories,_SessionMemoryStores_upload,_SessionMemoryStores_corroboratedDelete,_SessionMemoryStores_deleteRemote,MEMORY_FLUSH_TIMEOUT_MS=3e4,MARKER_PATH=".anthropic-memory-store",MARKER_VERSION=1;function markerSha(memoryStoreId){return crypto.createHash("sha256").update(`version ${MARKER_VERSION}
|
|
6
|
+
${memoryStoreId}`,"utf-8").digest("hex")}var DELETE_CORROBORATION_MS=3e4,LIST_PAGE_SIZE=100,FULL_LIST_PAGE_SIZE=20,FETCH_CONCURRENCY=16,UPLOAD_CONCURRENCY=32,DELETE_CAP_FLOOR=8,DELETE_CAP_CEILING=50,SessionMemoryError=class extends AnthropicError{constructor(message,cause){super(message),this.name="SessionMemoryError",cause!==void 0&&(this.cause=cause)}},DeletePass=class{constructor(mode,cap,waiveWindow){this.mode=mode,this.cap=cap,this.waiveWindow=waiveWindow,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){return this.attempted>=this.cap?(this.capped++,!1):(this.attempted++,!0)}},SessionMemoryStores=(()=>{class SessionMemoryStores2{constructor(client,opts){_SessionMemoryStores_instances.add(this),_SessionMemoryStores_client.set(this,void 0),_SessionMemoryStores_workdir.set(this,void 0),_SessionMemoryStores_syncIntervalMs.set(this,void 0),_SessionMemoryStores_syncDeletions.set(this,void 0),_SessionMemoryStores_log.set(this,void 0),_SessionMemoryStores_lastSyncAt.set(this,void 0),_SessionMemoryStores_finished.set(this,!1),_SessionMemoryStores_stores.set(this,[]),__classPrivateFieldSet(this,_SessionMemoryStores_client,client,"f"),__classPrivateFieldSet(this,_SessionMemoryStores_workdir,opts.workdir,"f"),__classPrivateFieldSet(this,_SessionMemoryStores_syncIntervalMs,opts.syncIntervalMs??DEFAULT_MEMORY_SYNC_INTERVAL_MS,"f"),checkMemorySyncInterval(__classPrivateFieldGet(this,_SessionMemoryStores_syncIntervalMs,"f"),"syncIntervalMs"),__classPrivateFieldSet(this,_SessionMemoryStores_syncDeletions,opts.syncDeletions??"enabled","f"),__classPrivateFieldSet(this,_SessionMemoryStores_log,loggerFor(client),"f"),__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}get roots(){return __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(s=>s.files.root().path)}get readOnlyRoots(){return __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").filter(s=>s.readOnly).map(s=>s.files.root().path)}async download(session){for(let resource of session.resources){if(resource.type!=="memory_store")continue;let root=__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_storeRoot).call(this,resource),store;try{if(store={memoryStoreId:resource.memory_store_id,files:await LocalFileStore.open(root,{utf8:!0}),readOnly:resource.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!store.files.root().removedOnDispose)throw new SessionMemoryError(`something already exists at the memory store's path: ${root} (memory_store_id=${resource.memory_store_id}); it must not exist when the session starts`);try{await store.files.createRoot()}catch(e){throw isErrno(e)?new SessionMemoryError(`cannot create the memory store's folder: ${root} (memory_store_id=${resource.memory_store_id}): ${e}; the worker host must make this mount path writable`,e):e}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("downloaded memories",{count:store.baseline.size,memory_store_id:store.memoryStoreId,dest:store.files.root().path}),__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").push(store)}catch(e){throw store&&await store.files.dispose().catch(()=>{}),e instanceof SessionMemoryError?e:new SessionMemoryError(`failed to download memory store memory_store_id=${resource.memory_store_id}: ${e}`,e)}}__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}async finish(){if(__classPrivateFieldGet(this,_SessionMemoryStores_finished,"f"))throw new AnthropicError("finish() was already called: it is the session's last sync and runs once");__classPrivateFieldSet(this,_SessionMemoryStores_finished,!0,"f"),await this.syncAll(!0)}async syncAll(final){await Promise.all(__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(store=>__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncStore).call(this,store,final))),__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}async syncIfDue(){Date.now()-__classPrivateFieldGet(this,_SessionMemoryStores_lastSyncAt,"f")<__classPrivateFieldGet(this,_SessionMemoryStores_syncIntervalMs,"f")||await this.syncAll(!1)}async flushWrites(signal){await Promise.all(__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(store=>__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_flushStore).call(this,store,signal)))}async dispose(){for(let store of __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f")){let root=store.files.root();try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk&&Object.keys(scan.files).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder on disk`,{root:root.path,memory_store_id:store.memoryStoreId});continue}await store.files.dispose()}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove the memory store folder",{root:store.files.root().path,memory_store_id:store.memoryStoreId,error:String(e)});continue}root.removedOnDispose&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("removed memory store dir",{dest:root.path,memory_store_id:store.memoryStoreId})}}}return _SessionMemoryStores_client=new WeakMap,_SessionMemoryStores_workdir=new WeakMap,_SessionMemoryStores_syncIntervalMs=new WeakMap,_SessionMemoryStores_syncDeletions=new WeakMap,_SessionMemoryStores_log=new WeakMap,_SessionMemoryStores_lastSyncAt=new WeakMap,_SessionMemoryStores_finished=new WeakMap,_SessionMemoryStores_stores=new WeakMap,_SessionMemoryStores_instances=new WeakSet,_SessionMemoryStores_storeRoot=function(resource){if(resource.mount_path){if(!isPathLegal(resource.mount_path))throw new SessionMemoryError(`memory store mount_path is not a clean absolute path: ${JSON.stringify(resource.mount_path)} (memory_store_id=${resource.memory_store_id})`);return resource.mount_path}return path.join(__classPrivateFieldGet(this,_SessionMemoryStores_workdir,"f"),"memory",resource.name||resource.memory_store_id)},_SessionMemoryStores_scanMarker=async function(store){let local=await store.files.hashtree(),marker=local[MARKER_PATH];return delete local[MARKER_PATH],marker===markerSha(store.memoryStoreId)?{files:local,markerOk:!0,distrustReason:null}:{files:local,markerOk:!1,distrustReason:marker!==void 0?"the marker file does not match this store":"the marker file is gone"}},_SessionMemoryStores_syncStore=async function(store,final){try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store),local=scan.files;if(!scan.markerOk){if(Object.keys(local).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder as found and not syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"the folder or its marker is gone");return}if(Object.keys(local).length===0&&store.baseline.size>1){await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"every memory file is gone at once");return}let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId))remote.set(rel,item);let deletes=new DeletePass(__classPrivateFieldGet(this,_SessionMemoryStores_syncDeletions,"f"),Math.max(DELETE_CAP_FLOOR,Math.min(DELETE_CAP_CEILING,Math.floor(store.baseline.size/4))),final),pulls=[],baseline=new Map,paths=[...new Set([...remote.keys(),...Object.keys(local),...store.baseline.keys()])].sort();for(let rel of paths){let remoteItem=remote.get(rel),localSha=local[rel],baseSha=store.baseline.get(rel),sha;localSha===void 0&&baseSha!==void 0&&remoteItem!==void 0&&remoteItem.content_sha256===baseSha&&!store.readOnly?sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_corroboratedDelete).call(this,store,rel,remoteItem,baseSha,deletes):sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncPath).call(this,store,rel,remoteItem,localSha,pulls),sha!==void 0&&baseline.set(rel,sha)}store.baseline=baseline,await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_pullAll).call(this,store,pulls),deletes.suppressed>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:deletes.suppressed,memory_store_id:store.memoryStoreId}),deletes.capped>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`delete cap reached: ${deletes.mode==="log_only"?"would send":"sent"} ${deletes.attempted} deletes, held ${deletes.capped} for later syncs`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory sync failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_flushStore=async function(store,signal){let dirty=new Map,unsent=new Set,push=async()=>{if(store.readOnly)return;let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; not uploading anything from the memory store folder`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}for(let[rel,sha]of Object.entries(scan.files))sha!==store.baseline.get(rel)&&store.refusedShas.get(rel)!==sha&&(dirty.set(rel,sha),unsent.add(rel));if(dirty.size===0||signal?.aborted)return;let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId)){if(signal?.aborted)return;remote.set(rel,item)}let uploads=[];for(let rel of[...dirty.keys()].sort()){let localSha=dirty.get(rel),baseSha=store.baseline.get(rel),existing=remote.get(rel);if(existing!==void 0&&existing.content_sha256===localSha){store.baseline.set(rel,existing.content_sha256),unsent.delete(rel);continue}if(existing!==void 0&&existing.content_sha256!==baseSha){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:rel,memory_store_id:store.memoryStoreId}),unsent.delete(rel);continue}uploads.push([rel,localSha,existing])}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_uploadAll).call(this,store,uploads,unsent,signal)};try{await settledOrAborted(push(),signal),signal?.aborted&&unsent.size>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`memory flush cut off part-way; ${unsent.size} of ${dirty.size} changed files had not finished uploading`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory flush failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_recover=async function(store,reason){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${reason}; re-downloading the memory store folder instead of syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId}),await store.files.createRoot(),await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store)},_SessionMemoryStores_stampAndPull=async function(store){store.baseline=new Map,store.pendingDeletes.clear(),await store.files.put(MARKER_PATH,`version ${MARKER_VERSION}
|
|
7
|
+
${store.memoryStoreId}`);for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId,"full"))await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},_SessionMemoryStores_syncPath=async function(store,rel,remote,localSha,pulls){let baseSha=store.baseline.get(rel);if(localSha!==void 0&&store.pendingDeletes.delete(rel),!remote){if(localSha===void 0){store.pendingDeletes.delete(rel);return}if(baseSha!==void 0){if(localSha===baseSha){let fresh=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_removeLocal).call(this,store,rel,baseSha);if(fresh===void 0)return;if(fresh===baseSha)return baseSha;localSha=fresh}store.readOnly?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:rel,memory_store_id:store.memoryStoreId}):store.refusedShas.get(rel)!==localSha&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:rel,memory_store_id:store.memoryStoreId})}return store.readOnly||store.refusedShas.get(rel)===localSha?void 0:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,void 0)}let remoteSha=remote.content_sha256,remoteChanged=remoteSha!==baseSha,locallyEdited=localSha!==void 0&&localSha!==baseSha&&localSha!==remoteSha,localChanged=!store.readOnly&&locallyEdited;return localSha===void 0&&baseSha!==void 0?(remoteChanged&&(__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:rel,memory_store_id:store.memoryStoreId}),store.pendingDeletes.delete(rel),pulls.push([rel,remote])),baseSha):remoteChanged?localSha===remoteSha?remoteSha:(locallyEdited&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}),pulls.push([rel,remote]),baseSha):localChanged?store.refusedShas.get(rel)===localSha?remoteSha:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,remote)??remoteSha:remoteSha},_SessionMemoryStores_removeLocal=async function(store,rel,expectSha){let freshSha;try{freshSha=await store.files.hashFile(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return expectSha}if(freshSha!==null){if(freshSha!==expectSha)return freshSha;try{await store.files.remove(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove memory deleted remotely",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),expectSha}}},_SessionMemoryStores_write=async function(store,rel,content){try{await store.files.put(rel,content)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to write memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),!1}return!0},_SessionMemoryStores_pullAll=async function(store,pulls){if(pulls.length===0)return;let pullOne=async(rel,listed)=>{let item;try{item=await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.retrieve(listed.id,{memory_store_id:store.memoryStoreId,view:"full"})}catch(e){if(isStatus(e,404))return;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to fetch memory content",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},queue=pulls[Symbol.iterator](),worker=async()=>{for(let[rel,listed]of queue)await pullOne(rel,listed)};await Promise.all(Array.from({length:Math.min(FETCH_CONCURRENCY,pulls.length)},worker))},_SessionMemoryStores_uploadAll=async function(store,uploads,unsent,signal){let queue=uploads[Symbol.iterator](),worker=async()=>{for(let[rel,localSha,existing]of queue){if(signal?.aborted)return;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,existing);unsent.delete(rel),sha!==void 0&&store.baseline.set(rel,sha)}};await Promise.all(Array.from({length:Math.min(UPLOAD_CONCURRENCY,uploads.length)},worker))},_SessionMemoryStores_listMemories=async function*(memoryStoreId,view="basic"){let limit=view==="basic"?LIST_PAGE_SIZE:FULL_LIST_PAGE_SIZE;for await(let item of __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.list(memoryStoreId,{view,limit})){if(item.type!=="memory")continue;let rel=item.path.replace(/^\/+/,"");if(rel===MARKER_PATH){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server listed the reserved marker path; skipping",{path:item.path,memory_store_id:memoryStoreId});continue}yield[rel,item]}},_SessionMemoryStores_upload=async function _SessionMemoryStores_upload2(store,rel,localSha,existing){try{let data=await store.files.get(rel);if(data===null)return;let content=decodeUTF8(data),item=existing?await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.update(existing.id,{memory_store_id:store.memoryStoreId,content,precondition:{type:"content_sha256",content_sha256:existing.content_sha256}}):await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.create(store.memoryStoreId,{path:"/"+rel,content});return store.refusedShas.delete(rel),item.content_sha256}catch(e){if(existing&&isStatus(e,404))return await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload2).call(this,store,rel,localSha,void 0);let permanent=e instanceof FileStoreError||isStatus(e,400)||isStatus(e,413);existing&&isStatus(e,409)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:rel,memory_store_id:store.memoryStoreId}):permanent&&localSha!==void 0?(store.refusedShas.set(rel,localSha),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:rel,memory_store_id:store.memoryStoreId,rejection:String(e)})):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to upload memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}},_SessionMemoryStores_corroboratedDelete=async function(store,rel,remote,baseSha,deletes){if(deletes.mode==="disabled")return deletes.suppressed++,baseSha;let firstAbsent=store.pendingDeletes.get(rel);if(firstAbsent===void 0&&(firstAbsent=Date.now(),store.pendingDeletes.set(rel,firstAbsent)),!deletes.waiveWindow&&Date.now()-firstAbsent<DELETE_CORROBORATION_MS)return baseSha;let markerOk,stillAbsent;try{markerOk=await store.files.hashFile(MARKER_PATH)===markerSha(store.memoryStoreId),stillAbsent=await store.files.hashFile(rel)===null}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;markerOk=stillAbsent=!1}if(!markerOk)return baseSha;if(!stillAbsent)return store.pendingDeletes.delete(rel),baseSha;if(!deletes.takeSlot())return baseSha;if(deletes.mode==="log_only")return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("log-only: sync would delete this memory on the server",{path:rel,memory_store_id:store.memoryStoreId}),baseSha;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_deleteRemote).call(this,store,rel,remote,baseSha);return sha===void 0&&store.pendingDeletes.delete(rel),sha},_SessionMemoryStores_deleteRemote=async function(store,rel,remote,baseSha){try{await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.delete(remote.id,{memory_store_id:store.memoryStoreId,expected_content_sha256:baseSha})}catch(e){return isStatus(e,404)?void 0:(isStatus(e,409)||isStatus(e,412)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to delete memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),baseSha)}__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("propagated local deletion",{path:rel,memory_store_id:store.memoryStoreId})},SessionMemoryStores2})();function isErrno(e){return typeof e=="object"&&e!==null&&typeof e.code=="string"}async function settledOrAborted(p,signal){if(!signal){await p;return}let onAbort,aborted=new Promise(resolve2=>{onAbort=resolve2,signal.aborted&&resolve2()});signal.addEventListener("abort",onAbort,{once:!0});try{await Promise.race([p,aborted])}finally{signal.removeEventListener("abort",onAbort)}}var _BashSession_instances,_BashSession_proc,_BashSession_buf,_BashSession_truncated,_BashSession_closed,_BashSession_waiting,_BashSession_append,_LineRangeCollector_instances,_LineRangeCollector_filePath,_LineRangeCollector_startLine,_LineRangeCollector_endLine,_LineRangeCollector_start,_LineRangeCollector_end,_LineRangeCollector_limit,_LineRangeCollector_line,_LineRangeCollector_collected,_LineRangeCollector_collectedBytes,_LineRangeCollector_collect,_LineRangeCollector_overLimitError,BASH_OUTPUT_LIMIT=100*1024,BASH_DEFAULT_TIMEOUT_MS=12e4,DEFAULT_MAX_FILE_BYTES=256*1024,READ_STREAM_CHUNK_BYTES=64*1024,NEWLINE=Buffer.from(`
|
|
8
|
+
`),GREP_OUTPUT_LIMIT=100*1024,GREP_MAX_LINE_LENGTH=2e3,GLOB_RESULT_LIMIT=200,BashTimeoutError=class extends AnthropicError{constructor(timeoutMs){super(`bash command timed out after ${timeoutMs}ms`),this.name="BashTimeoutError",this.timeoutMs=timeoutMs}},ANSI_RE=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,fsGlob=fs4.glob;function resolveMaxBytes(configured){return configured===void 0?DEFAULT_MAX_FILE_BYTES:configured}function rejectUnrestrictedPaths(value){if(value!==void 0)throw new AnthropicError("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function betaAgentToolset20260401(ctx){return[betaBashTool(ctx),betaReadTool(ctx),betaWriteTool(ctx),betaEditTool(ctx),betaGlobTool(ctx),betaGrepTool(ctx)]}async function resolvePath(ctx,p){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),confineToRoot(ctx.workdir,p,{allowedRoots:ctx.allowedRoots??[]})}function readOnlyRootFor(ctx,target){return containingRoot(ctx.readOnlyRoots??[],target)}function scrubbedShellEnv(){let env={};for(let[key,value]of Object.entries(process.env))key.startsWith("ANTHROPIC_")||(env[key]=value);return env}var BashSession=(()=>{class BashSession2{constructor(dir,env=scrubbedShellEnv()){_BashSession_instances.add(this),_BashSession_proc.set(this,void 0),_BashSession_buf.set(this,""),_BashSession_truncated.set(this,!1),_BashSession_closed.set(this,!1),_BashSession_waiting.set(this,null),__classPrivateFieldSet(this,_BashSession_proc,cp.spawn("/bin/bash",["--noprofile","--norc"],{cwd:dir,env:{...env,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").once("close",()=>{__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve()})}get closed(){return __classPrivateFieldGet(this,_BashSession_closed,"f")}async exec(command,opts={}){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))throw new AnthropicError("bash session terminated");let timeoutMs=opts.timeoutMs??BASH_DEFAULT_TIMEOUT_MS,signal=opts.signal;signal?.throwIfAborted(),__classPrivateFieldSet(this,_BashSession_buf,"","f"),__classPrivateFieldSet(this,_BashSession_truncated,!1,"f");let sentinel=`__ANT_CMD_${crypto2.randomUUID()}_DONE__`,sentinelSplit=`${sentinel.slice(0,8)}''${sentinel.slice(8)}`,wrapped=`{ ${command}
|
|
9
|
+
} </dev/null 2>&1; printf '\\n${sentinelSplit}%d\\n' $?
|
|
10
|
+
`;if(__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.write(wrapped),__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel)<0){let{promise:sentinelSeen,resolve:resolve2}=promiseWithResolvers();__classPrivateFieldSet(this,_BashSession_waiting,{sentinel,resolve:resolve2},"f");let timer,onAbort;try{await Promise.race([sentinelSeen,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BashTimeoutError(timeoutMs)),timeoutMs)}),new Promise((_,reject)=>{signal&&(onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0}))})])}finally{timer&&clearTimeout(timer),onAbort&&signal&&signal.removeEventListener("abort",onAbort),__classPrivateFieldSet(this,_BashSession_waiting,null,"f")}}let idx=__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel);if(idx<0)throw new AnthropicError("bash session terminated");let m=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(idx+sentinel.length).match(/^(-?\d+)/),exitCode=m?parseInt(m[1],10):-1,out=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(0,idx).replace(ANSI_RE,"").replace(/\n+$/,"");return __classPrivateFieldGet(this,_BashSession_truncated,"f")&&(out=`[output truncated]
|
|
11
|
+
${out}`),{output:out,exitCode}}close(){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))return;__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.destroy();try{process.kill(-__classPrivateFieldGet(this,_BashSession_proc,"f").pid,"SIGKILL")}catch{__classPrivateFieldGet(this,_BashSession_proc,"f").kill("SIGKILL")}__classPrivateFieldGet(this,_BashSession_proc,"f").unref()}}return _BashSession_proc=new WeakMap,_BashSession_buf=new WeakMap,_BashSession_truncated=new WeakMap,_BashSession_closed=new WeakMap,_BashSession_waiting=new WeakMap,_BashSession_instances=new WeakSet,_BashSession_append=function(d){if(__classPrivateFieldSet(this,_BashSession_buf,__classPrivateFieldGet(this,_BashSession_buf,"f")+d,"f"),__classPrivateFieldGet(this,_BashSession_buf,"f").length>BASH_OUTPUT_LIMIT&&(__classPrivateFieldSet(this,_BashSession_buf,__classPrivateFieldGet(this,_BashSession_buf,"f").slice(__classPrivateFieldGet(this,_BashSession_buf,"f").length-BASH_OUTPUT_LIMIT),"f"),__classPrivateFieldSet(this,_BashSession_truncated,!0,"f")),__classPrivateFieldGet(this,_BashSession_waiting,"f")&&__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(__classPrivateFieldGet(this,_BashSession_waiting,"f").sentinel)>=0){let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w.resolve()}},BashSession2})();function betaBashTool(ctx){rejectUnrestrictedPaths(ctx.unrestrictedPaths);let session,tail=Promise.resolve();return betaTool({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command,restart,timeout_ms},context)=>{let prev=tail,gate=promiseWithResolvers();tail=gate.promise;try{await prev}catch{}try{if(restart&&(session?.close(),session=void 0),!command){if(restart)return"bash session restarted";throw new ToolError("bash: command is required")}session??(session=new BashSession(ctx.workdir,ctx.env));try{let{output,exitCode}=await session.exec(command,{timeoutMs:timeout_ms??BASH_DEFAULT_TIMEOUT_MS,signal:context?.signal});if(exitCode!==0)throw new ToolError(output||`exit ${exitCode}`);return output}catch(e){throw e instanceof ToolError?e:(session.close(),session=void 0,new ToolError(`bash: ${e instanceof Error?e.message:String(e)}`))}}finally{gate.resolve()}},close:()=>{session?.close(),session=void 0}})}function betaReadTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path,view_range})=>{if(!file_path)throw new ToolError("read: file_path is required");let abs=await resolvePath(ctx,file_path);if(view_range?.length&&view_range.length!==2)throw new ToolError("read: view_range must be [start_line, end_line]");let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`read: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit){if(!view_range?.length)throw new ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[startLine2,endLine2]=view_range;return await readRangeStreaming(abs,file_path,startLine2,endLine2,limit)}data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`read: ${fsErrorMessage(e,file_path)}`)}if(!view_range?.length)return data;let[startLine,endLine]=view_range,lines=data.split(`
|
|
12
|
+
`),start=Math.max(0,startLine-1),end=endLine>0?endLine:lines.length;return lines.slice(start,end).join(`
|
|
13
|
+
`)}})}async function readRangeStreaming(abs,filePath,startLine,endLine,limit){let lines=new LineRangeCollector(filePath,startLine,endLine,limit);if(lines.rangeIsEmpty())return"";let stream2=fssync.createReadStream(abs,{highWaterMark:READ_STREAM_CHUNK_BYTES});try{for await(let chunk of stream2)if(lines.collectFrom(chunk),lines.rangeIsCollected())break}finally{stream2.destroy()}return lines.text()}var LineRangeCollector=(()=>{class LineRangeCollector2{constructor(filePath,startLine,endLine,limit){_LineRangeCollector_instances.add(this),_LineRangeCollector_filePath.set(this,void 0),_LineRangeCollector_startLine.set(this,void 0),_LineRangeCollector_endLine.set(this,void 0),_LineRangeCollector_start.set(this,void 0),_LineRangeCollector_end.set(this,void 0),_LineRangeCollector_limit.set(this,void 0),_LineRangeCollector_line.set(this,0),_LineRangeCollector_collected.set(this,[]),_LineRangeCollector_collectedBytes.set(this,0),__classPrivateFieldSet(this,_LineRangeCollector_filePath,filePath,"f"),__classPrivateFieldSet(this,_LineRangeCollector_startLine,startLine,"f"),__classPrivateFieldSet(this,_LineRangeCollector_endLine,endLine,"f"),__classPrivateFieldSet(this,_LineRangeCollector_start,Math.max(0,startLine-1),"f"),__classPrivateFieldSet(this,_LineRangeCollector_end,endLine>0?endLine:1/0,"f"),__classPrivateFieldSet(this,_LineRangeCollector_limit,limit,"f")}rangeIsEmpty(){return __classPrivateFieldGet(this,_LineRangeCollector_end,"f")<=__classPrivateFieldGet(this,_LineRangeCollector_start,"f")}rangeIsCollected(){return __classPrivateFieldGet(this,_LineRangeCollector_line,"f")>=__classPrivateFieldGet(this,_LineRangeCollector_end,"f")}collectFrom(chunk){var _a;let lineStart=0;for(;lineStart<chunk.length&&!this.rangeIsCollected();){let newline=chunk.indexOf(10,lineStart),lineEnd=newline<0?chunk.length:newline;if(__classPrivateFieldGet(this,_LineRangeCollector_line,"f")>=__classPrivateFieldGet(this,_LineRangeCollector_start,"f")&&__classPrivateFieldGet(this,_LineRangeCollector_instances,"m",_LineRangeCollector_collect).call(this,chunk.subarray(lineStart,lineEnd),newline>=0),newline<0)break;__classPrivateFieldSet(this,_LineRangeCollector_line,(_a=__classPrivateFieldGet(this,_LineRangeCollector_line,"f"),_a++,_a),"f"),lineStart=newline+1}}text(){return Buffer.concat(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f"),__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")).toString("utf8")}}return _LineRangeCollector_filePath=new WeakMap,_LineRangeCollector_startLine=new WeakMap,_LineRangeCollector_endLine=new WeakMap,_LineRangeCollector_start=new WeakMap,_LineRangeCollector_end=new WeakMap,_LineRangeCollector_limit=new WeakMap,_LineRangeCollector_line=new WeakMap,_LineRangeCollector_collected=new WeakMap,_LineRangeCollector_collectedBytes=new WeakMap,_LineRangeCollector_instances=new WeakSet,_LineRangeCollector_collect=function(lineBytes,newlineTerminated){if(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f").push(lineBytes),__classPrivateFieldSet(this,_LineRangeCollector_collectedBytes,__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")+lineBytes.length,"f"),newlineTerminated&&__classPrivateFieldGet(this,_LineRangeCollector_line,"f")+1<__classPrivateFieldGet(this,_LineRangeCollector_end,"f")&&(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f").push(NEWLINE),__classPrivateFieldSet(this,_LineRangeCollector_collectedBytes,__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")+NEWLINE.length,"f")),__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")>__classPrivateFieldGet(this,_LineRangeCollector_limit,"f"))throw __classPrivateFieldGet(this,_LineRangeCollector_instances,"m",_LineRangeCollector_overLimitError).call(this)},_LineRangeCollector_overLimitError=function(){return __classPrivateFieldGet(this,_LineRangeCollector_end,"f")-__classPrivateFieldGet(this,_LineRangeCollector_start,"f")===1?new ToolError(`read: line ${__classPrivateFieldGet(this,_LineRangeCollector_start,"f")+1} of ${__classPrivateFieldGet(this,_LineRangeCollector_filePath,"f")} alone exceeds ${__classPrivateFieldGet(this,_LineRangeCollector_limit,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`):new ToolError(`read: view_range [${__classPrivateFieldGet(this,_LineRangeCollector_startLine,"f")}, ${__classPrivateFieldGet(this,_LineRangeCollector_endLine,"f")}] of ${__classPrivateFieldGet(this,_LineRangeCollector_filePath,"f")} exceeds ${__classPrivateFieldGet(this,_LineRangeCollector_limit,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)},LineRangeCollector2})();function betaWriteTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path,content})=>{if(!file_path)throw new ToolError("write: file_path is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`write: ${file_path} is inside read-only directory ${ro}`);try{await fs4.mkdir(path2.dirname(abs),{recursive:!0,mode:DIR_CREATE_MODE}),await atomicWriteFile(abs,content??"")}catch(e){throw new ToolError(`write: ${fsErrorMessage(e,file_path)}`)}return`wrote ${Buffer.byteLength(content??"")} bytes to ${file_path}`}})}function betaEditTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path,old_string,new_string,replace_all})=>{if(!file_path)throw new ToolError("edit: file_path is required");if(!old_string)throw new ToolError("edit: old_string is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`edit: ${file_path} is inside read-only directory ${ro}`);let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`edit: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit)throw new ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`edit: ${fsErrorMessage(e,file_path)}`)}let count=data.split(old_string).length-1;if(count===0)throw new ToolError(`edit: old_string not found in ${file_path}`);let updated;if(replace_all)updated=data.split(old_string).join(new_string);else{if(count>1)throw new ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`);updated=data.replace(old_string,()=>new_string)}try{await atomicWriteFile(abs,updated)}catch(e){throw new ToolError(`edit: write: ${fsErrorMessage(e,file_path)}`)}return`edited ${file_path} (${replace_all?count:1} replacement(s))`}})}function patternCanAscend(pattern){return pattern.split(/[\\/{},]/).includes("..")}function betaGlobTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern,path:searchPath})=>{if(!pattern)throw new ToolError("glob: pattern is required");if(path2.isAbsolute(pattern))throw new ToolError("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(patternCanAscend(pattern))throw new ToolError('glob: ".." is not permitted in the pattern');let root=searchPath?await resolvePath(ctx,searchPath):path2.resolve(ctx.workdir),realRoot=searchPath?root:await canonicalize(root),matches=[],remaining=WALK_MAX_ENTRIES;try{for await(let entry of fsGlob(pattern,{cwd:root,withFileTypes:!0,exclude:d=>d.name===".git"||d.name==="node_modules"})){if(remaining--<=0)break;if(!entry.isFile())continue;let full=path2.join(entry.parentPath,entry.name),real;try{real=await fs4.realpath(full)}catch{continue}if(!isWithin(realRoot,real))continue;let mtime=0;try{mtime=(await fs4.stat(full)).mtimeMs}catch{}matches.push({path:full,mtime})}}catch(e){throw new ToolError(`glob: ${e instanceof Error?e.message:String(e)}`)}return matches.length===0?"no matches":(matches.sort((a,b)=>b.mtime-a.mtime),matches.slice(0,GLOB_RESULT_LIMIT).map(m=>m.path).join(`
|
|
14
|
+
`))}})}function betaGrepTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern,path:p},context)=>{if(!pattern)throw new ToolError("grep: pattern is required");let searchPath=path2.resolve(ctx.workdir);p&&(searchPath=await resolvePath(ctx,p));let rg=await findRg();return rg?runRipgrep(rg,pattern,searchPath,context?.signal):runWalkGrep(pattern,searchPath,context?.signal)}})}function runRipgrep(rg,pattern,searchPath,signal){return new Promise((resolve2,reject)=>{let proc=cp.spawn(rg,["-n","--no-heading","-e",pattern,"--",searchPath],{...signal?{signal}:{}}),out="",errOut="",truncated=!1;proc.stdout.on("data",d=>{truncated||(out+=d,out.length>GREP_OUTPUT_LIMIT&&(truncated=!0,out=out.slice(0,GREP_OUTPUT_LIMIT),proc.kill("SIGKILL")))}),proc.stderr.on("data",d=>errOut+=d),proc.on("close",code=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));if(truncated)return resolve2(out+`
|
|
15
|
+
[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);if(code===0)return resolve2(out);if(code===1)return resolve2("no matches");reject(new ToolError(`grep: rg failed: ${errOut||`exit ${code}`}`))}),proc.on("error",e=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));reject(new ToolError(`grep: rg failed: ${e.message}`))})})}async function runWalkGrep(pattern,root,signal){let re;try{re=new RegExp(pattern)}catch(e){throw new ToolError(`grep: invalid regex: ${e instanceof Error?e.message:String(e)}`)}let hits=[],budget=GREP_OUTPUT_LIMIT,push=line=>(budget-=line.length+1,budget<0?(hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`),!1):(hits.push(line),!0));if((await fs4.stat(root).catch(()=>null))?.isFile()?await grepFile(root,re,push):await walk2(root,"",rel=>grepFile(path2.join(root,rel),re,push),signal),signal?.aborted)throw new ToolError("grep: aborted");return hits.length===0?"no matches":hits.join(`
|
|
16
|
+
`)}async function grepFile(file,re,push){let stream2=fssync.createReadStream(file,{encoding:"utf8"}),rl=readline.createInterface({input:stream2,crlfDelay:1/0}),i=0;try{for await(let line of rl)if(i++,!(line.length>GREP_MAX_LINE_LENGTH)&&re.test(line)&&!push(`${file}:${i}:${line}`))return!1}catch{}finally{stream2.destroy()}return!0}var WALK_MAX_DEPTH=40,WALK_MAX_ENTRIES=5e4;async function walk2(root,rel,fn,signal){let remaining=WALK_MAX_ENTRIES;async function inner(rel2,depth){if(depth>WALK_MAX_DEPTH)return!0;if(signal?.aborted)return!1;let entries;try{entries=await fs4.readdir(path2.join(root,rel2),{withFileTypes:!0})}catch{return!0}for(let e of entries){if(e.name===".git"||e.name==="node_modules")continue;if(remaining--<=0||signal?.aborted)return!1;let childRel=rel2?path2.join(rel2,e.name):e.name;if(e.isDirectory()){if(!await inner(childRel,depth+1))return!1}else if(e.isFile()&&await fn(childRel)===!1)return!1}return!0}await inner(rel,0)}async function findRg(){let dirs=(process.env.PATH??"").split(path2.delimiter);for(let d of dirs){let candidate=path2.join(d,"rg");try{return await fs4.access(candidate,fssync.constants.X_OK),candidate}catch{}}return null}export{BashSession,BashTimeoutError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MARKER_PATH,MEMORY_FLUSH_TIMEOUT_MS,MIN_MEMORY_SYNC_INTERVAL_MS,SessionMemoryError,SessionMemoryStores,betaAgentToolset20260401,betaBashTool,betaEditTool,betaGlobTool,betaGrepTool,betaReadTool,betaWriteTool,extractSkillArchive,resolvePath,setupSkills};
|
|
@@ -72,4 +72,4 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
|
|
|
72
72
|
${details?`<div class="details">${details}</div>`:""}
|
|
73
73
|
</main>
|
|
74
74
|
</body>
|
|
75
|
-
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var DYNAMIC_CLIENT_ID="dynamic_agent_client",AGENT_NAME_HINT="Pi",UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,AUTHORIZE_URL="https://auth.openai.com/api/accounts/authorize",TOKEN_URL="https://auth.openai.com/api/accounts/oauth/token",RESOURCE="https://api.openai.com/v1",CALLBACK_HOST=getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1",CALLBACK_PORT=1455,CALLBACK_PATH="/auth/callback",REDIRECT_URI=`http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`,DIRECT_TOKEN_SCOPE="chatgpt.tokens.use.direct",SCOPE=`openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`,EXPIRY_MARGIN_MS=180*1e3;function randomValue(){return randomBytes(32).toString("base64url")}function authorizationResultFromCallback(url,expectedState){let code=url.searchParams.get("code");if(!code)throw new Error("Missing authorization code");let state=url.searchParams.get("state");if(!state)throw new Error("Missing OAuth state");if(state!==expectedState)throw new Error("OAuth state mismatch");let clientId=url.searchParams.get("client_id")?.trim();if(!clientId)throw new Error("OpenAI OAuth registration callback did not contain an issued client ID");return{code,clientId}}function authorizationResultFromManualInput(input,expectedState){let url;try{url=new URL(input.trim())}catch{throw new Error("Paste the full callback URL from the browser")}let expected=new URL(REDIRECT_URI);if(url.origin!==expected.origin||url.pathname!==expected.pathname)throw new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);let error=url.searchParams.get("error");if(error)throw new Error(`ChatGPT authorization failed: ${error}`);return authorizationResultFromCallback(url,expectedState)}function sendHtml(response,status,body){response.writeHead(status,{"Content-Type":"text/html; charset=utf-8"}),response.end(body)}function startCallbackServer(expectedState){return new Promise((resolve,reject)=>{let resolveResult,rejectResult,result=new Promise((resolveAuthorization,rejectAuthorization)=>{resolveResult=resolveAuthorization,rejectResult=rejectAuthorization}),server=createServer((request,response)=>{try{let url=new URL(request.url||"",REDIRECT_URI);if(url.pathname!==CALLBACK_PATH){sendHtml(response,404,oauthErrorHtml("Callback route not found."));return}let error=url.searchParams.get("error");if(error){sendHtml(response,400,oauthErrorHtml("ChatGPT was not connected.",`Error: ${error}`)),rejectResult(new Error(`ChatGPT authorization failed: ${error}`));return}let authorizationResult;try{authorizationResult=authorizationResultFromCallback(url,expectedState)}catch(error2){let message=error2 instanceof Error?error2.message:"Invalid callback";sendHtml(response,400,oauthErrorHtml(message));return}sendHtml(response,200,oauthSuccessHtml("ChatGPT authentication completed. You can close this window.")),resolveResult(authorizationResult)}catch{sendHtml(response,500,oauthErrorHtml("Internal error while processing the callback."))}});server.once("error",reject),server.listen(CALLBACK_PORT,CALLBACK_HOST,()=>{server.removeListener("error",reject),server.on("error",rejectResult),resolve({server,result})})})}async function requestToken(body,signal){let response=await fetch(TOKEN_URL,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body,signal});if(!response.ok){let responseBody=await response.text().catch(()=>"");throw new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody||response.statusText}`)}let data=await response.json();if(typeof data!="object"||data===null||Array.isArray(data))throw new Error("OpenAI OAuth token response must be an object");return data}function requireTokenString(value,field){if(typeof value!="string"||value.trim().length===0)throw new Error(`OpenAI OAuth token response has invalid ${field}`);return value}function credentialFromTokenResponse(token,clientId){let access=requireTokenString(token.access_token,"access_token"),refresh=requireTokenString(token.refresh_token,"refresh_token"),scope=requireTokenString(token.scope,"scope");if(typeof token.expires_in!="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw new Error("OpenAI OAuth token response has invalid expires_in");let scopes=scope.trim().split(/\s+/).filter(Boolean);if(!scopes.includes(DIRECT_TOKEN_SCOPE))throw new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);return{type:"oauth",access,refresh,expires:Date.now()+token.expires_in*1e3-EXPIRY_MARGIN_MS,clientId,scopes}}async function exchangeAuthorizationCode(code,verifier,clientId,signal){let token=await requestToken(new URLSearchParams({grant_type:"authorization_code",client_id:clientId,code,code_verifier:verifier,redirect_uri:REDIRECT_URI,resource:RESOURCE}),signal);if(typeof token.id_token!="string"||token.id_token.trim().length===0)throw new Error("OpenAI OAuth token response did not contain an ID token");return credentialFromTokenResponse(token,clientId)}async function refreshAccessToken(credential,signal){let clientId=credential.clientId;if(typeof clientId!="string"||clientId.trim().length===0)throw new Error("Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT");let token=await requestToken(new URLSearchParams({grant_type:"refresh_token",client_id:clientId,refresh_token:credential.refresh,resource:RESOURCE}),signal);return credentialFromTokenResponse(token,clientId)}function agentHostId(deviceId){if(!deviceId||!UUID_PATTERN.test(deviceId))throw new Error("Sign in with ChatGPT requires a device ID (UUID) for this installation");return`urn:uuid:${deviceId.toLowerCase()}`}async function loginOpenAIChatGPT(interaction,options){let hostId=agentHostId(options?.getDeviceId?.()),{verifier,challenge}=await generatePKCE(),state=randomValue(),nonce=randomValue(),callback
|
|
75
|
+
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var DYNAMIC_CLIENT_ID="dynamic_agent_client",AGENT_NAME_HINT="Pi",UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,AUTHORIZE_URL="https://auth.openai.com/api/accounts/authorize",TOKEN_URL="https://auth.openai.com/api/accounts/oauth/token",RESOURCE="https://api.openai.com/v1",CALLBACK_HOST=getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1",CALLBACK_PORT=1455,CALLBACK_PATH="/auth/callback",REDIRECT_URI=`http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`,DIRECT_TOKEN_SCOPE="chatgpt.tokens.use.direct",SCOPE=`openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`,EXPIRY_MARGIN_MS=180*1e3;function randomValue(){return randomBytes(32).toString("base64url")}function authorizationResultFromCallback(url,expectedState){let code=url.searchParams.get("code");if(!code)throw new Error("Missing authorization code");let state=url.searchParams.get("state");if(!state)throw new Error("Missing OAuth state");if(state!==expectedState)throw new Error("OAuth state mismatch");let clientId=url.searchParams.get("client_id")?.trim();if(!clientId)throw new Error("OpenAI OAuth registration callback did not contain an issued client ID");return{code,clientId}}function authorizationResultFromManualInput(input,expectedState){let url;try{url=new URL(input.trim())}catch{throw new Error("Paste the full callback URL from the browser")}let expected=new URL(REDIRECT_URI);if(url.origin!==expected.origin||url.pathname!==expected.pathname)throw new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);let error=url.searchParams.get("error");if(error)throw new Error(`ChatGPT authorization failed: ${error}`);return authorizationResultFromCallback(url,expectedState)}function sendHtml(response,status,body){response.writeHead(status,{"Content-Type":"text/html; charset=utf-8"}),response.end(body)}function startCallbackServer(expectedState){return new Promise((resolve,reject)=>{let resolveResult,rejectResult,result=new Promise((resolveAuthorization,rejectAuthorization)=>{resolveResult=resolveAuthorization,rejectResult=rejectAuthorization}),server=createServer((request,response)=>{try{let url=new URL(request.url||"",REDIRECT_URI);if(url.pathname!==CALLBACK_PATH){sendHtml(response,404,oauthErrorHtml("Callback route not found."));return}let error=url.searchParams.get("error");if(error){sendHtml(response,400,oauthErrorHtml("ChatGPT was not connected.",`Error: ${error}`)),rejectResult(new Error(`ChatGPT authorization failed: ${error}`));return}let authorizationResult;try{authorizationResult=authorizationResultFromCallback(url,expectedState)}catch(error2){let message=error2 instanceof Error?error2.message:"Invalid callback";sendHtml(response,400,oauthErrorHtml(message));return}sendHtml(response,200,oauthSuccessHtml("ChatGPT authentication completed. You can close this window.")),resolveResult(authorizationResult)}catch{sendHtml(response,500,oauthErrorHtml("Internal error while processing the callback."))}});server.once("error",reject),server.listen(CALLBACK_PORT,CALLBACK_HOST,()=>{server.removeListener("error",reject),server.on("error",rejectResult),resolve({server,result})})})}async function requestToken(body,signal){let response=await fetch(TOKEN_URL,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body,signal});if(!response.ok){let responseBody=await response.text().catch(()=>"");throw new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody||response.statusText}`)}let data=await response.json();if(typeof data!="object"||data===null||Array.isArray(data))throw new Error("OpenAI OAuth token response must be an object");return data}function requireTokenString(value,field){if(typeof value!="string"||value.trim().length===0)throw new Error(`OpenAI OAuth token response has invalid ${field}`);return value}function credentialFromTokenResponse(token,clientId){let access=requireTokenString(token.access_token,"access_token"),refresh=requireTokenString(token.refresh_token,"refresh_token"),scope=requireTokenString(token.scope,"scope");if(typeof token.expires_in!="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw new Error("OpenAI OAuth token response has invalid expires_in");let scopes=scope.trim().split(/\s+/).filter(Boolean);if(!scopes.includes(DIRECT_TOKEN_SCOPE))throw new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);return{type:"oauth",access,refresh,expires:Date.now()+token.expires_in*1e3-EXPIRY_MARGIN_MS,clientId,scopes}}async function exchangeAuthorizationCode(code,verifier,clientId,signal){let token=await requestToken(new URLSearchParams({grant_type:"authorization_code",client_id:clientId,code,code_verifier:verifier,redirect_uri:REDIRECT_URI,resource:RESOURCE}),signal);if(typeof token.id_token!="string"||token.id_token.trim().length===0)throw new Error("OpenAI OAuth token response did not contain an ID token");return credentialFromTokenResponse(token,clientId)}async function refreshAccessToken(credential,signal){let clientId=credential.clientId;if(typeof clientId!="string"||clientId.trim().length===0)throw new Error("Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT");let token=await requestToken(new URLSearchParams({grant_type:"refresh_token",client_id:clientId,refresh_token:credential.refresh,resource:RESOURCE}),signal);return credentialFromTokenResponse(token,clientId)}function agentHostId(deviceId){if(!deviceId||!UUID_PATTERN.test(deviceId))throw new Error("Sign in with ChatGPT requires a device ID (UUID) for this installation");return`urn:uuid:${deviceId.toLowerCase()}`}async function loginOpenAIChatGPT(interaction,options){let hostId=agentHostId(options?.getDeviceId?.()),{verifier,challenge}=await generatePKCE(),state=randomValue(),nonce=randomValue(),callback=await startCallbackServer(state).catch(error=>{throw error instanceof Error&&"code"in error&&error.code==="EADDRINUSE"?new Error(`Port ${CALLBACK_PORT} is in use, probably by an unfinished login in another pi session or by the Codex CLI. Cancel that login and try again.`):error}),authorizationUrl=new URL(AUTHORIZE_URL);authorizationUrl.search=new URLSearchParams({client_id:DYNAMIC_CLIENT_ID,agent_name_hint:AGENT_NAME_HINT,ext_agent_host_id:hostId,response_type:"code",redirect_uri:REDIRECT_URI,resource:RESOURCE,scope:SCOPE,state,code_challenge:challenge,code_challenge_method:"S256",nonce}).toString(),interaction.notify({type:"auth_url",url:authorizationUrl.toString(),instructions:"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here."});let manualAbort=new AbortController,manualCode=interaction.prompt({type:"manual_code",message:"Complete login in your browser, or paste the final redirect URL here:",placeholder:REDIRECT_URI,signal:AbortSignal.any([manualAbort.signal,interaction.signal])}).then(input=>authorizationResultFromManualInput(input,state));try{let result=await Promise.race([callback.result,manualCode]);return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(result.code,verifier,result.clientId,interaction.signal)}catch(error){throw interaction.signal.aborted?new Error("Login cancelled"):error}finally{manualAbort.abort(),callback.server.close(),callback.server.closeAllConnections()}}var openaiChatGPTOAuth={name:"OpenAI (ChatGPT subscription)",isSubscription:!0,loginLabel:"Sign in with ChatGPT",login:loginOpenAIChatGPT,refresh:refreshAccessToken,async toAuth(credential){return{apiKey:credential.access}}};export{openaiChatGPTOAuth};
|
package/dist/bundle/chunks/{openai-codex-responses-GK67DQQJ.js → openai-codex-responses-TC3OK7B4.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{registerSessionResourceCleanup,uuidv7}from"./chunk-USJZMAIR.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-2VNGUWBO.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-6D7LHLKG.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import"./chunk-TRDNDS6A.js";import{clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,resolveTranscriptTools}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";function combineAbortSignals(signals){let activeSignals=signals.filter(signal=>signal!==void 0);if(activeSignals.length===0)return{cleanup:()=>{}};if(activeSignals.length===1)return{signal:activeSignals[0],cleanup:()=>{}};let controller=new AbortController,listeners=[],abort=signal=>{controller.signal.aborted||controller.abort(signal.reason)};for(let signal of activeSignals){if(signal.aborted){abort(signal);break}let listener=()=>abort(signal);signal.addEventListener("abort",listener,{once:!0}),listeners.push({signal,listener})}return{signal:controller.signal,cleanup:()=>{for(let{signal,listener}of listeners)signal.removeEventListener("abort",listener)}}}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env){let noProxy=getProxyEnv("no_proxy",env).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",JWT_CLAIM_PATH="https://api.openai.com/auth",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE=1009,WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}function getRetryAfterDelayMs(headers){let retryAfterMs=headers.get("retry-after-ms");if(retryAfterMs!==null){let millis=Number(retryAfterMs);if(Number.isFinite(millis))return Math.max(0,millis)}let retryAfter=headers.get("retry-after");if(!retryAfter)return;let seconds=Number(retryAfter);if(Number.isFinite(seconds))return Math.max(0,seconds*1e3);let date=Date.parse(retryAfter);if(!Number.isNaN(date))return Math.max(0,date-Date.now())}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return new Uint8Array(compressed.buffer,compressed.byteOffset,compressed.byteLength)}catch{return null}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",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:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,normalizedContext,options,codexSessionId,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart||(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,...websocketStarted?{}:{fallbackTransport:"sse"},eventsEmitted:websocketStarted,phase:websocketStarted?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error),websocketStarted))throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody??bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=getRetryAfterDelayMs(response.headers),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse);throw new Error(info.friendlyMessage||info.message)}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function buildRequestBody(model,context,options,cacheSessionId,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,supportsAdditionalTools||supportsToolSearch),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),initialSystemMessage=getInitialSystemMessage(context.messages),instructions=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",body={model:model.id,store:!1,stream:!0,instructions:instructions||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:cacheSessionId,tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};if(options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),transcriptTools.requestTools.length>0&&(body.tools=convertResponsesTools(transcriptTools.requestTools,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools})),options?.reasoningEffort!==void 0){let effort=options.reasoningEffort==="none"?model.thinkingLevelMap?.off===void 0?"none":model.thinkingLevelMap.off:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;effort!==null&&(body.reasoning={effort,summary:options.reasoningSummary??"auto"})}else model.reasoning&&model.thinkingLevelMap?.off!==null&&(body.reasoning={effort:model.thinkingLevelMap?.off??"none"});return body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output,model,options?.onProviderStreamEvent),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{code;payload;constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{payload;constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}},ProviderStreamEventCallbackError=class extends Error{constructor(cause){super(formatThrownValue(cause)),this.name="ProviderStreamEventCallbackError",this.cause=cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError||error instanceof ProviderStreamEventCallbackError}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function extractCodexEventError(event){let nested=event.error&&typeof event.error=="object"?event.error:void 0;return{code:typeof event.code=="string"?event.code:typeof nested?.code=="string"?nested.code:void 0,message:typeof event.message=="string"?event.message:typeof nested?.message=="string"?nested.message:void 0}}async function*mapCodexEvents(events,output,model,onProviderStreamEvent){for await(let event of events){try{await onProviderStreamEvent?.(event,model)}catch(error){throw new ProviderStreamEventCallbackError(error)}let type=typeof event.type=="string"?event.type:void 0;if(type){if(type==="error"){let{code,message}=extractCodexEventError(event);throw new CodexApiError(`Codex error: ${message||code||JSON.stringify(event)}`,{code,payload:event})}if(type==="response.failed"){let response=event.response,code=response?.error?.code,message=response?.error?.message;throw new CodexApiError(message||"Codex response failed",{code,payload:event})}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield event}}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
|
|
2
|
+
import{registerSessionResourceCleanup,uuidv7}from"./chunk-USJZMAIR.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-BYB6ZAAQ.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-IKZJX7ZT.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import"./chunk-TRDNDS6A.js";import{clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,resolveTranscriptTools}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";function combineAbortSignals(signals){let activeSignals=signals.filter(signal=>signal!==void 0);if(activeSignals.length===0)return{cleanup:()=>{}};if(activeSignals.length===1)return{signal:activeSignals[0],cleanup:()=>{}};let controller=new AbortController,listeners=[],abort=signal=>{controller.signal.aborted||controller.abort(signal.reason)};for(let signal of activeSignals){if(signal.aborted){abort(signal);break}let listener=()=>abort(signal);signal.addEventListener("abort",listener,{once:!0}),listeners.push({signal,listener})}return{signal:controller.signal,cleanup:()=>{for(let{signal,listener}of listeners)signal.removeEventListener("abort",listener)}}}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env){let noProxy=getProxyEnv("no_proxy",env).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",JWT_CLAIM_PATH="https://api.openai.com/auth",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE=1009,WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}function getRetryAfterDelayMs(headers){let retryAfterMs=headers.get("retry-after-ms");if(retryAfterMs!==null){let millis=Number(retryAfterMs);if(Number.isFinite(millis))return Math.max(0,millis)}let retryAfter=headers.get("retry-after");if(!retryAfter)return;let seconds=Number(retryAfter);if(Number.isFinite(seconds))return Math.max(0,seconds*1e3);let date=Date.parse(retryAfter);if(!Number.isNaN(date))return Math.max(0,date-Date.now())}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return new Uint8Array(compressed.buffer,compressed.byteOffset,compressed.byteLength)}catch{return null}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",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:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,normalizedContext,options,codexSessionId,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart||(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,...websocketStarted?{}:{fallbackTransport:"sse"},eventsEmitted:websocketStarted,phase:websocketStarted?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error),websocketStarted))throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody??bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=getRetryAfterDelayMs(response.headers),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse);throw new Error(info.friendlyMessage||info.message)}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function buildRequestBody(model,context,options,cacheSessionId,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,supportsAdditionalTools||supportsToolSearch),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),initialSystemMessage=getInitialSystemMessage(context.messages),instructions=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",body={model:model.id,store:!1,stream:!0,instructions:instructions||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:cacheSessionId,tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};if(options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),transcriptTools.requestTools.length>0&&(body.tools=convertResponsesTools(transcriptTools.requestTools,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools})),options?.reasoningEffort!==void 0){let effort=options.reasoningEffort==="none"?model.thinkingLevelMap?.off===void 0?"none":model.thinkingLevelMap.off:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;effort!==null&&(body.reasoning={effort,summary:options.reasoningSummary??"auto"})}else model.reasoning&&model.thinkingLevelMap?.off!==null&&(body.reasoning={effort:model.thinkingLevelMap?.off??"none"});return body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output,model,options?.onProviderStreamEvent),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{code;payload;constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{payload;constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}},ProviderStreamEventCallbackError=class extends Error{constructor(cause){super(formatThrownValue(cause)),this.name="ProviderStreamEventCallbackError",this.cause=cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError||error instanceof ProviderStreamEventCallbackError}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function extractCodexEventError(event){let nested=event.error&&typeof event.error=="object"?event.error:void 0;return{code:typeof event.code=="string"?event.code:typeof nested?.code=="string"?nested.code:void 0,message:typeof event.message=="string"?event.message:typeof nested?.message=="string"?nested.message:void 0}}async function*mapCodexEvents(events,output,model,onProviderStreamEvent){for await(let event of events){try{await onProviderStreamEvent?.(event,model)}catch(error){throw new ProviderStreamEventCallbackError(error)}let type=typeof event.type=="string"?event.type:void 0;if(type){if(type==="error"){let{code,message}=extractCodexEventError(event);throw new CodexApiError(`Codex error: ${message||code||JSON.stringify(event)}`,{code,payload:event})}if(type==="response.failed"){let response=event.response,code=response?.error?.code,message=response?.error?.message;throw new CodexApiError(message||"Codex response failed",{code,payload:event})}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield event}}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
|
|
3
3
|
|
|
4
4
|
`);let idx=buffer.indexOf(`
|
|
5
5
|
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-H3QXYIF7.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{retryProviderRequest}from"./chunk-LD2P6SFZ.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,getPiUserAgent,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(field){return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={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:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,apiKey,options?.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,hasFinishReason=!1,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},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},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},ensureTextBlock=()=>(textBlock||(textBlock={type:"text",text:""},blocks.push(textBlock),stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output})),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output})),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output})}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(choice){if(!chunk.usage&&choice.usage&&(output.usage=parseChunkUsage(choice.usage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}let reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)isOpenAIReasoningDetail(detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail))}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
|
+
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),compat.supportsOpenAIGrammarTools)){let transcriptTools=resolveTranscriptTools(context.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),messages=convertMessages(model,context,compat,{grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),params={model:model.id,messages,stream:!0,prompt_cache_key:model.baseUrl.includes("api.openai.com")&&cacheRetention!=="none"||cacheRetention==="long"&&compat.supportsLongCacheRetention?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature),transcriptTools.requestTools.length>0?(params.tools=convertTools(transcriptTools.requestTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice),compat.vllmPriority!==void 0&&(params.priority=compat.vllmPriority);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let mappedEffort=model.thinkingLevelMap?.[options.reasoningEffort],effort=mappedEffort===void 0?options.reasoningEffort:mappedEffort;typeof effort=="string"&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;typeof effort=="string"&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat.chatTemplateArgs,thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?model.thinkingLevelMap?.[requestedEffort]:model.thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)options?.reasoningEffort?params.thinking={type:"enabled"}:model.thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"}),options?.reasoningEffort&&compat.supportsReasoningEffort&&(params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort);else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;options?.reasoningEffort?openRouterParams.reasoning={effort:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort}:model.thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:model.thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort&&(togetherParams.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort)}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning){let stringThinkingParams=params;options?.reasoningEffort?stringThinkingParams.thinking=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:model.thinkingLevelMap?.off!==null&&(stringThinkingParams.thinking=model.thinkingLevelMap?.off??"none")}else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort)params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=model.thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}let samplingParams=resolveSamplingParams(model,options?.reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let mappedValue=reasoningEffort?model.thinkingLevelMap?.[reasoningEffort]:model.thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function convertMessages(model,context,compat,options){let normalizedContext=resolveTranscript(context,compat.supportsMidConvoSystemMessages),params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`}return model.provider==="openai"&&id.length>40?id.slice(0,40):id},transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeToolCallId(id)),transcriptTools=resolveTranscriptTools(normalizedContext.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),instructionRole=model.reasoning&&compat.supportsDeveloperRole?"developer":"system",lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&¶ms.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="system"){let addedTools=i>0&&transcriptTools.anchorsAdditions?msg.toolsAdded??[]:[];if(addedTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(addedTools,compat)};params.push(kimiToolMessage)}let text=i===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&¶ms.push({role:instructionRole,content:sanitizeSurrogates(text)})}else if(msg.role==="user")if(typeof msg.content=="string")params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let content=msg.content.filter(item=>item.type!=="text"||item.text.length>0).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;params.push({role:"user",content})}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0){if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
|
+
|
|
5
|
+
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else if(assistantText.length>0&&(assistantMsg.content=assistantText),!preservedReasoningDetails){let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature&&isOpenAICompletionsReasoningField(signature)&&(assistantMsg[signature]=nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|
|
6
|
+
`))}}else assistantText.length>0&&(assistantMsg.content=assistantText);toolCalls.length>0&&(assistantMsg.tool_calls=toolCalls.map(tc=>{let customInputProperty=options?.grammarToolInputProperties?.get(tc.name);return customInputProperty!==void 0?{id:tc.id,type:"custom",custom:{name:tc.name,input:sanitizeSurrogates(getGrammarToolInput(tc.name,tc.arguments,customInputProperty))}}:{id:tc.id,type:"function",function:{name:tc.name,arguments:JSON.stringify(tc.arguments)}}})),preservedReasoningDetails&&(assistantMsg.reasoning_details=preservedReasoningDetails),compat.requiresReasoningContentOnAssistantMessages&&model.reasoning&&assistantMsg.reasoning_content===void 0&&(assistantMsg.reasoning_content="");let content=assistantMsg.content;if(!(content!=null&&content.length>0)&&!assistantMsg.tool_calls)continue;params.push(assistantMsg)}else if(msg.role==="toolResult"){let imageBlocks=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";j++){let toolMsg=transformedMessages[j],textResult=toolMsg.content.filter(isTextContentBlock).map(block=>block.text).join(`
|
|
7
|
+
`),hasImages=toolMsg.content.some(c=>c.type==="image"),toolResultText=textResult.length>0?textResult:hasImages?"(see attached image)":"(no tool output)",toolResultMsg={role:"tool",content:sanitizeSurrogates(toolResultText),tool_call_id:toolMsg.toolCallId};if(compat.requiresToolResultName&&toolMsg.toolName&&(toolResultMsg.name=toolMsg.toolName),params.push(toolResultMsg),hasImages&&model.input.includes("image"))for(let block of toolMsg.content)isImageContentBlock(block)&&imageBlocks.push({type:"image_url",image_url:{url:`data:${block.mimeType};base64,${block.data}`}})}i=j-1,imageBlocks.length>0?(compat.requiresAssistantAfterToolResult&¶ms.push({role:"assistant",content:"I have processed the tool results."}),params.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...imageBlocks]}),lastRole="user"):lastRole="toolResult";continue}lastRole=msg.role}return params}function convertTools(tools,compat){return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,compat.supportsOpenAIGrammarTools);if(grammar)return{type:"custom",custom:{name:tool.name,description:tool.description,format:{type:"grammar",grammar:{syntax:grammar.format,definition:grammar.definition}}}};let strict=resolveJsonSchemaStrictSampling(tool,compat.supportsStrictMode!==!1);return{type:"function",function:{name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict),...compat.supportsStrictMode!==!1&&{strict:strict??!1}}}})}function parseChunkUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,cacheReadTokens=rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.prompt_cache_hit_tokens??rawUsage.cached_tokens??0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens||0,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),outputTokens=rawUsage.completion_tokens||0,usage={input,output:outputTokens,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens,reasoning:rawUsage.completion_tokens_details?.reasoning_tokens||0,totalTokens:input+outputTokens+cacheReadTokens+cacheWriteTokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}function mapStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${reason}`}}}function detectCompat(model){let provider=model.provider,baseUrl=model.baseUrl,isZai=provider==="zai"||provider==="zai-coding-cn"||baseUrl.includes("api.z.ai")||baseUrl.includes("open.bigmodel.cn"),isTogether=provider==="together"||baseUrl.includes("api.together.ai")||baseUrl.includes("api.together.xyz"),isMoonshot=provider==="moonshotai"||provider==="moonshotai-cn"||baseUrl.includes("api.moonshot."),isOpenRouter=provider==="openrouter"||baseUrl.includes("openrouter.ai"),isCloudflareWorkersAI=provider==="cloudflare-workers-ai"||baseUrl.includes("api.cloudflare.com"),isCloudflareAiGateway=provider==="cloudflare-ai-gateway"||baseUrl.includes("gateway.ai.cloudflare.com"),isNvidia=provider==="nvidia"||baseUrl.includes("integrate.api.nvidia.com"),isAntLing=provider==="ant-ling"||baseUrl.includes("api.ant-ling.com"),isCerebras=provider==="cerebras"||baseUrl.includes("cerebras.ai"),isDeepSeek=provider==="deepseek"||baseUrl.toLowerCase().includes("deepseek.com"),isNonStandard=isNvidia||isCerebras||provider==="xai"||baseUrl.includes("api.x.ai")||isTogether||baseUrl.includes("chutes.ai")||isDeepSeek||isZai||isMoonshot||provider==="opencode"||baseUrl.includes("opencode.ai")||isCloudflareWorkersAI||isCloudflareAiGateway||isAntLing,useMaxTokens=baseUrl.includes("chutes.ai")||isDeepSeek||isMoonshot||isCloudflareAiGateway||isTogether||isNvidia||isAntLing||isZai,isGrok=provider==="xai"||baseUrl.includes("api.x.ai"),isOpenRouterDeveloperRoleModel=isOpenRouter&&(model.id.startsWith("anthropic/")||model.id.startsWith("openai/")),cacheControlFormat=provider==="openrouter"&&model.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!isNonStandard,supportsDeveloperRole:isOpenRouterDeveloperRoleModel||!isNonStandard&&!isOpenRouter,supportsReasoningEffort:!isGrok&&!isZai&&!isMoonshot&&!isTogether&&!isCloudflareAiGateway&&!isNvidia&&!isAntLing,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:useMaxTokens?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:isDeepSeek,thinkingFormat:isDeepSeek?"deepseek":isZai?"zai":isTogether?"together":isAntLing?"ant-ling":isOpenRouter?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat,sendSessionAffinityHeaders:isOpenRouter,sessionAffinityFormat:isOpenRouter?"openrouter":"openai",supportsLongCacheRetention:!(isTogether||isCloudflareWorkersAI||isCloudflareAiGateway||isNvidia||isAntLing)}}function getCompat(model){let detected=detectCompat(model);return model.compat?{supportsStore:model.compat.supportsStore??detected.supportsStore,supportsDeveloperRole:model.compat.supportsDeveloperRole??detected.supportsDeveloperRole,supportsReasoningEffort:model.compat.supportsReasoningEffort??detected.supportsReasoningEffort,supportsUsageInStreaming:model.compat.supportsUsageInStreaming??detected.supportsUsageInStreaming,supportsFinishReason:model.compat.supportsFinishReason??detected.supportsFinishReason,maxTokensField:model.compat.maxTokensField??detected.maxTokensField,requiresToolResultName:model.compat.requiresToolResultName??detected.requiresToolResultName,requiresAssistantAfterToolResult:model.compat.requiresAssistantAfterToolResult??detected.requiresAssistantAfterToolResult,requiresThinkingAsText:model.compat.requiresThinkingAsText??detected.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:model.compat.requiresReasoningContentOnAssistantMessages??detected.requiresReasoningContentOnAssistantMessages,thinkingFormat:model.compat.thinkingFormat??detected.thinkingFormat,openRouterRouting:model.compat.openRouterRouting??{},vercelGatewayRouting:model.compat.vercelGatewayRouting??detected.vercelGatewayRouting,chatTemplateKwargs:model.compat.chatTemplateKwargs??detected.chatTemplateKwargs,chatTemplateArgs:model.compat.chatTemplateArgs??detected.chatTemplateArgs,zaiToolStream:model.compat.zaiToolStream??detected.zaiToolStream,supportsThinkingTokenBudget:model.compat.supportsThinkingTokenBudget??detected.supportsThinkingTokenBudget,thinkingTokenBudgetField:model.compat.thinkingTokenBudgetField??detected.thinkingTokenBudgetField,supportsStrictMode:model.compat.supportsStrictMode??detected.supportsStrictMode,supportsOpenAIGrammarTools:model.compat.supportsOpenAIGrammarTools??detected.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:model.compat.supportsMidConvoSystemMessages??detected.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:model.compat.supportsMidConvoToolAdditions??detected.supportsMidConvoToolAdditions,cacheControlFormat:model.compat.cacheControlFormat??detected.cacheControlFormat,sendSessionAffinityHeaders:model.compat.sendSessionAffinityHeaders??detected.sendSessionAffinityHeaders,sessionAffinityFormat:model.compat.sessionAffinityFormat??detected.sessionAffinityFormat,supportsLongCacheRetention:model.compat.supportsLongCacheRetention??detected.supportsLongCacheRetention,vllmPriority:model.compat.vllmPriority}:detected}export{convertMessages,stream,streamSimple};
|