@korallis/k-pi 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/chunks/anthropic-messages-YPDJT7UM.js +6 -0
- package/dist/bundle/chunks/{azure-openai-responses-GUUG57CZ.js → azure-openai-responses-MTUAI5MH.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +41 -38
- package/dist/bundle/chunks/chunk-6A7XFRBG.js +44 -0
- package/dist/bundle/chunks/chunk-72KO4OMP.js +2 -0
- package/dist/bundle/chunks/chunk-B6RWH7WU.js +4 -0
- package/dist/bundle/chunks/{chunk-NBBFIJUL.js → chunk-CNVK4YTO.js} +1 -1
- package/dist/bundle/chunks/chunk-FZQAG3QJ.js +31 -0
- package/dist/bundle/chunks/chunk-PWUXXUIP.js +42 -0
- package/dist/bundle/chunks/chunk-QA44GMU3.js +1662 -0
- package/dist/bundle/chunks/chunk-WJZ4KLGL.js +2 -0
- package/dist/bundle/chunks/es-26SL22VU.js +9 -0
- package/dist/bundle/chunks/{google-generative-ai-YRXF7C4I.js → google-generative-ai-UIIDDRFY.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-BVZ6VBRQ.js → google-vertex-UGTKZCAT.js} +1 -1
- package/dist/bundle/chunks/https-proxy-agent-KDWAGLQB.js +16 -0
- package/dist/bundle/chunks/{mistral-conversations-Q3AWZJAZ.js → mistral-conversations-IRKPOWEP.js} +1 -1
- package/dist/bundle/chunks/node-Z6U4VVLX.js +16 -0
- package/dist/bundle/chunks/{openai-codex-responses-GJVBJXLB.js → openai-codex-responses-TNDMXNYP.js} +2 -2
- package/dist/bundle/chunks/{openai-completions-OICQQ5JB.js → openai-completions-MOQKHPPN.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-P5LIZTXX.js → openai-responses-JEPPDARY.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-XTKS2AS3.js → openrouter-images-K3CBAFEC.js} +1 -1
- package/dist/bundle/chunks/pi-messages-XKMXBA4S.js +8 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/kpi/graphs/coding-loop.auto.json +2 -2
- package/dist/kpi/graphs/coding-loop.gated.json +3 -3
- package/dist/kpi/kstack/UPSTREAM.md +2 -2
- package/dist/kpi/kstack/generated/skills/setup-kstack/SKILL.md +7 -2
- package/dist/kpi/kstack/provenance.json +3 -3
- package/dist/kpi/prompts/ship.md +2 -2
- package/dist/kpi/skills/conventional-commit/SKILL.md +5 -3
- package/dist/kpi/templates/APPEND_SYSTEM.md +2 -0
- package/dist/kpi/templates/policy.json +3 -1
- package/examples/extensions/custom-provider-anthropic/package.json +17 -17
- package/examples/extensions/sandbox/package.json +1 -1
- package/package.json +2 -2
- package/dist/bundle/chunks/anthropic-messages-IBCPCIJO.js +0 -45
- package/dist/bundle/chunks/chunk-HOFU6X66.js +0 -50
- package/dist/bundle/chunks/chunk-MNAIPA3J.js +0 -2
- package/dist/bundle/chunks/chunk-NUHFSC37.js +0 -25
- package/dist/bundle/chunks/chunk-UAQELI3K.js +0 -2
- package/dist/bundle/chunks/chunk-X5QHCKY4.js +0 -1653
- package/dist/bundle/chunks/chunk-XDUWOHPL.js +0 -6
- package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +0 -13
- package/dist/bundle/chunks/lib-HGQMNYVT.js +0 -9
- package/dist/bundle/chunks/pi-messages-TPFH44NP.js +0 -8
package/dist/bundle/chunks/{google-generative-ai-YRXF7C4I.js → google-generative-ai-UIIDDRFY.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-
|
|
2
|
+
import{GoogleGenAI,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-6A7XFRBG.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-CO7LIZG5.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-AXIIZGTV.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-4L3WN2XY.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",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 Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options,failed=>options?.onResponse?.(failed,model));stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){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 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 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};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),googleModel=model;return isGemini3ProModel(googleModel)||isGemini3FlashModel(googleModel)||isGemma4Model(googleModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getThinkingLevel(resolvedLevel,googleModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(googleModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemma4Model(model){return/gemma-?4/.test(model.id.toLowerCase())}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:"LOW"}:isGemini3FlashModel(model)?{thinkingLevel:"MINIMAL"}:isGemma4Model(model)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function getThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(isGemma4Model(model))switch(effort){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,ResourceScope,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-HOFU6X66.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-AXIIZGTV.js";import"./chunk-CO7LIZG5.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{calculateCost,clampThinkingLevel}from"./chunk-MNAIPA3J.js";import{AssistantMessageEventStream}from"./chunk-UAQELI3K.js";import"./chunk-4L3WN2XY.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options,failed=>options?.onResponse?.(failed,model));stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){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),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),geminiModel=model;return isGemini3ProModel(geminiModel)||isGemini3FlashModel(geminiModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,geminiModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(geminiModel,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),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=THINKING_LEVEL_MAP[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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){let geminiModel=model;return isGemini3ProModel(geminiModel)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(geminiModel)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-6A7XFRBG.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-CO7LIZG5.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-AXIIZGTV.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-4L3WN2XY.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options,failed=>options?.onResponse?.(failed,model));stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){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),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),geminiModel=model;return isGemini3ProModel(geminiModel)||isGemini3FlashModel(geminiModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,geminiModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(geminiModel,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),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=THINKING_LEVEL_MAP[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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){let geminiModel=model;return isGemini3ProModel(geminiModel)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(geminiModel)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{__commonJS,__esm,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_ms=__commonJS({"node_modules/ms/index.js"(exports,module){var s=1e3,m=s*60,h=m*60,d=h*24,w=d*7,y=d*365.25;module.exports=function(val,options){options=options||{};var type=typeof val;if(type==="string"&&val.length>0)return parse(val);if(type==="number"&&isFinite(val))return options.long?fmtLong(val):fmtShort(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse(str){if(str=String(str),!(str.length>100)){var match=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);if(match){var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"weeks":case"week":case"w":return n*w;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(ms){var msAbs=Math.abs(ms);return msAbs>=d?Math.round(ms/d)+"d":msAbs>=h?Math.round(ms/h)+"h":msAbs>=m?Math.round(ms/m)+"m":msAbs>=s?Math.round(ms/s)+"s":ms+"ms"}function fmtLong(ms){var msAbs=Math.abs(ms);return msAbs>=d?plural(ms,msAbs,d,"day"):msAbs>=h?plural(ms,msAbs,h,"hour"):msAbs>=m?plural(ms,msAbs,m,"minute"):msAbs>=s?plural(ms,msAbs,s,"second"):ms+" ms"}function plural(ms,msAbs,n,name){var isPlural=msAbs>=n*1.5;return Math.round(ms/n)+" "+name+(isPlural?"s":"")}}});var require_common=__commonJS({"node_modules/debug/src/common.js"(exports,module){function setup(env){createDebug3.debug=createDebug3,createDebug3.default=createDebug3,createDebug3.coerce=coerce,createDebug3.disable=disable,createDebug3.enable=enable,createDebug3.enabled=enabled,createDebug3.humanize=require_ms(),createDebug3.destroy=destroy,Object.keys(env).forEach(key=>{createDebug3[key]=env[key]}),createDebug3.names=[],createDebug3.skips=[],createDebug3.formatters={};function selectColor(namespace){let hash=0;for(let i=0;i<namespace.length;i++)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return createDebug3.colors[Math.abs(hash)%createDebug3.colors.length]}createDebug3.selectColor=selectColor;function createDebug3(namespace){let prevTime,enableOverride=null,namespacesCache,enabledCache;function debug3(...args){if(!debug3.enabled)return;let self=debug3,curr=Number(new Date),ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug3.coerce(args[0]),typeof args[0]!="string"&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if(match==="%%")return"%";index++;let formatter=createDebug3.formatters[format];if(typeof formatter=="function"){let val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug3.formatArgs.call(self,args),(self.log||createDebug3.log).apply(self,args)}return debug3.namespace=namespace,debug3.useColors=createDebug3.useColors(),debug3.color=createDebug3.selectColor(namespace),debug3.extend=extend,debug3.destroy=createDebug3.destroy,Object.defineProperty(debug3,"enabled",{enumerable:!0,configurable:!1,get:()=>enableOverride!==null?enableOverride:(namespacesCache!==createDebug3.namespaces&&(namespacesCache=createDebug3.namespaces,enabledCache=createDebug3.enabled(namespace)),enabledCache),set:v=>{enableOverride=v}}),typeof createDebug3.init=="function"&&createDebug3.init(debug3),debug3}function extend(namespace,delimiter){let newDebug=createDebug3(this.namespace+(typeof delimiter>"u"?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function enable(namespaces){createDebug3.save(namespaces),createDebug3.namespaces=namespaces,createDebug3.names=[],createDebug3.skips=[];let split=(typeof namespaces=="string"?namespaces:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let ns of split)ns[0]==="-"?createDebug3.skips.push(ns.slice(1)):createDebug3.names.push(ns)}function matchesTemplate(search,template){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;for(;searchIndex<search.length;)if(templateIndex<template.length&&(template[templateIndex]===search[searchIndex]||template[templateIndex]==="*"))template[templateIndex]==="*"?(starIndex=templateIndex,matchIndex=searchIndex,templateIndex++):(searchIndex++,templateIndex++);else if(starIndex!==-1)templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex;else return!1;for(;templateIndex<template.length&&template[templateIndex]==="*";)templateIndex++;return templateIndex===template.length}function disable(){let namespaces=[...createDebug3.names,...createDebug3.skips.map(namespace=>"-"+namespace)].join(",");return createDebug3.enable(""),namespaces}function enabled(name){for(let skip of createDebug3.skips)if(matchesTemplate(name,skip))return!1;for(let ns of createDebug3.names)if(matchesTemplate(name,ns))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}function destroy(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return createDebug3.enable(createDebug3.load()),createDebug3}module.exports=setup}});var require_browser=__commonJS({"node_modules/debug/src/browser.js"(exports,module){exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=localstorage();exports.destroy=(()=>{let warned=!1;return()=>{warned||(warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let m;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(m=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{match!=="%%"&&(index++,match==="%c"&&(lastC=index))}),args.splice(lastC,0,c)}exports.log=console.debug||console.log||(()=>{});function save(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch{}}function load(){let r;try{r=exports.storage.getItem("debug")||exports.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function localstorage(){try{return localStorage}catch{}}module.exports=require_common()(exports);var{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}});var require_has_flag=__commonJS({"node_modules/has-flag/index.js"(exports,module){"use strict";module.exports=(flag,argv=process.argv)=>{let prefix=flag.startsWith("-")?"":flag.length===1?"-":"--",position=argv.indexOf(prefix+flag),terminatorPosition=argv.indexOf("--");return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)}}});var require_supports_color=__commonJS({"node_modules/supports-color/index.js"(exports,module){"use strict";var os=__require("os"),tty=__require("tty"),hasFlag=require_has_flag(),{env}=process,forceColor;hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never")?forceColor=0:(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))&&(forceColor=1);"FORCE_COLOR"in env&&(env.FORCE_COLOR==="true"?forceColor=1:env.FORCE_COLOR==="false"?forceColor=0:forceColor=env.FORCE_COLOR.length===0?1:Math.min(parseInt(env.FORCE_COLOR,10),3));function translateLevel(level){return level===0?!1:{level,hasBasic:!0,has256:level>=2,has16m:level>=3}}function supportsColor(haveStream,streamIsTTY){if(forceColor===0)return 0;if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2;if(haveStream&&!streamIsTTY&&forceColor===void 0)return 0;let min=forceColor||0;if(env.TERM==="dumb")return min;if(process.platform==="win32"){let osRelease=os.release().split(".");return Number(osRelease[0])>=10&&Number(osRelease[2])>=10586?Number(osRelease[2])>=14931?3:2:1}if("CI"in env)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(sign=>sign in env)||env.CI_NAME==="codeship"?1:min;if("TEAMCITY_VERSION"in env)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0;if(env.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in env){let version=parseInt((env.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return version>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(env.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)||"COLORTERM"in env?1:min}function getSupportLevel(stream){let level=supportsColor(stream,stream&&stream.isTTY);return translateLevel(level)}module.exports={supportsColor:getSupportLevel,stdout:translateLevel(supportsColor(!0,tty.isatty(1))),stderr:translateLevel(supportsColor(!0,tty.isatty(2)))}}});var require_node=__commonJS({"node_modules/debug/src/node.js"(exports,module){var tty=__require("tty"),util=__require("util");exports.init=init;exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.destroy=util.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");exports.colors=[6,2,3,4,5,1];try{let supportsColor=require_supports_color();supportsColor&&(supportsColor.stderr||supportsColor).level>=2&&(exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}exports.inspectOpts=Object.keys(process.env).filter(key=>/^debug_/i.test(key)).reduce((obj,key)=>{let prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_,k)=>k.toUpperCase()),val=process.env[key];return/^(yes|on|true|enabled)$/i.test(val)?val=!0:/^(no|off|false|disabled)$/i.test(val)?val=!1:val==="null"?val=null:val=Number(val),obj[prop]=val,obj},{});function useColors(){return"colors"in exports.inspectOpts?!!exports.inspectOpts.colors:tty.isatty(process.stderr.fd)}function formatArgs(args){let{namespace:name,useColors:useColors2}=this;if(useColors2){let c=this.color,colorCode="\x1B[3"+(c<8?c:"8;5;"+c),prefix=` ${colorCode};1m${name} \x1B[0m`;args[0]=prefix+args[0].split(`
|
|
3
|
+
`).join(`
|
|
4
|
+
`+prefix),args.push(colorCode+"m+"+module.exports.humanize(this.diff)+"\x1B[0m")}else args[0]=getDate()+name+" "+args[0]}function getDate(){return exports.inspectOpts.hideDate?"":new Date().toISOString()+" "}function log(...args){return process.stderr.write(util.formatWithOptions(exports.inspectOpts,...args)+`
|
|
5
|
+
`)}function save(namespaces){namespaces?process.env.DEBUG=namespaces:delete process.env.DEBUG}function load(){return process.env.DEBUG}function init(debug3){debug3.inspectOpts={};let keys=Object.keys(exports.inspectOpts);for(let i=0;i<keys.length;i++)debug3.inspectOpts[keys[i]]=exports.inspectOpts[keys[i]]}module.exports=require_common()(exports);var{formatters}=module.exports;formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split(`
|
|
6
|
+
`).map(str=>str.trim()).join(" ")};formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)}}});var require_src=__commonJS({"node_modules/debug/src/index.js"(exports,module){typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?module.exports=require_browser():module.exports=require_node()}});var init_helpers=__esm({"node_modules/agent-base/dist/helpers.js"(){}});import*as net from"net";import*as http from"http";import{Agent as HttpsAgent}from"https";var INTERNAL,Agent2,init_dist=__esm({"node_modules/agent-base/dist/index.js"(){init_helpers();INTERNAL=Symbol("AgentBaseInternalState"),Agent2=class extends http.Agent{constructor(opts){super(opts),this[INTERNAL]={}}isSecureEndpoint(options){if(options){if(typeof options.secureEndpoint=="boolean")return options.secureEndpoint;if(typeof options.protocol=="string")return options.protocol==="https:"}let{stack}=new Error;return typeof stack!="string"?!1:stack.split(`
|
|
7
|
+
`).some(l=>l.indexOf("(https.js:")!==-1||l.indexOf("node:https:")!==-1)}incrementSockets(name){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[name]||(this.sockets[name]=[]);let fakeSocket=new net.Socket({writable:!1});return this.sockets[name].push(fakeSocket),this.totalSocketCount++,fakeSocket}decrementSockets(name,socket){if(!this.sockets[name]||socket===null)return;let sockets=this.sockets[name],index=sockets.indexOf(socket);index!==-1&&(sockets.splice(index,1),this.totalSocketCount--,sockets.length===0&&delete this.sockets[name])}getName(options){return this.isSecureEndpoint(options)?HttpsAgent.prototype.getName.call(this,options):super.getName(options)}createSocket(req,options,cb){let connectOpts={...options,secureEndpoint:this.isSecureEndpoint(options)},name=this.getName(connectOpts),fakeSocket=this.incrementSockets(name);Promise.resolve().then(()=>this.connect(req,connectOpts)).then(socket=>{if(this.decrementSockets(name,fakeSocket),typeof socket.addRequest=="function")try{return socket.addRequest(req,connectOpts)}catch(err){return cb(err)}this[INTERNAL].currentSocket=socket,super.createSocket(req,options,cb)},err=>{this.decrementSockets(name,fakeSocket),cb(err)})}createConnection(){let socket=this[INTERNAL].currentSocket;if(this[INTERNAL].currentSocket=void 0,!socket)throw new Error("No socket was returned in the `connect()` function");return socket}get defaultPort(){return this[INTERNAL].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(v){this[INTERNAL]&&(this[INTERNAL].defaultPort=v)}get protocol(){return this[INTERNAL].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(v){this[INTERNAL]&&(this[INTERNAL].protocol=v)}}}});function parseProxyResponse(socket){return new Promise((resolve,reject)=>{let buffersLength=0,buffers=[];function read(){let b=socket.read();b?ondata(b):socket.once("readable",read)}function cleanup(){socket.removeListener("end",onend),socket.removeListener("error",onerror),socket.removeListener("readable",read)}function onend(){cleanup(),debug("onend"),reject(new Error("Proxy connection ended before receiving CONNECT response"))}function onerror(err){cleanup(),debug("onerror %o",err),reject(err)}function ondata(b){buffers.push(b),buffersLength+=b.length;let buffered=Buffer.concat(buffers,buffersLength),endOfHeaders=buffered.indexOf(`\r
|
|
8
|
+
\r
|
|
9
|
+
`);if(endOfHeaders===-1){debug("have not received end of HTTP headers yet..."),read();return}let headerParts=buffered.slice(0,endOfHeaders).toString("ascii").split(`\r
|
|
10
|
+
`),firstLine=headerParts.shift();if(!firstLine)return socket.destroy(),reject(new Error("No header received from proxy CONNECT response"));let firstLineParts=firstLine.split(" "),statusCode=+firstLineParts[1],statusText=firstLineParts.slice(2).join(" "),headers={};for(let header of headerParts){if(!header)continue;let firstColon=header.indexOf(":");if(firstColon===-1)return socket.destroy(),reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));let key=header.slice(0,firstColon).toLowerCase(),value=header.slice(firstColon+1).trimStart(),current=headers[key];typeof current=="string"?headers[key]=[current,value]:Array.isArray(current)?current.push(value):headers[key]=value}debug("got proxy server response: %o %o",firstLine,headers),cleanup(),resolve({connect:{statusCode,statusText,headers},buffered})}socket.on("error",onerror),socket.on("end",onend),read()})}var import_debug,debug,init_parse_proxy_response=__esm({"node_modules/https-proxy-agent/dist/parse-proxy-response.js"(){import_debug=__toESM(require_src(),1),debug=(0,import_debug.default)("https-proxy-agent:parse-proxy-response")}});function createNegotiateAuth(){return async({response,scheme})=>{if(scheme.toLowerCase()!=="negotiate")throw new Error(`Expected Negotiate scheme but got "${scheme}"`);let kerberos;try{kerberos=await import("kerberos")}catch{throw new Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let proxyAuthenticate=response.headers["proxy-authenticate"]||"",challengeHeader=Array.isArray(proxyAuthenticate)?proxyAuthenticate[0]:proxyAuthenticate,serverToken=typeof challengeHeader=="string"&&challengeHeader.includes(" ")?challengeHeader.split(" ").slice(1).join(" "):void 0,token=await(await kerberos.initializeClient("HTTP@proxy",{mechOID:kerberos.GSS_MECH_OID_SPNEGO})).step(serverToken||"");if(!token)throw new Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${token}`}}}}var init_dist2=__esm({"node_modules/proxy-agent-negotiate/dist/index.js"(){}});import*as net2 from"net";import*as tls from"tls";import assert from"assert";import{URL}from"url";function resume(socket){setImmediate(()=>{socket.resume()})}function omit(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}var import_debug2,debug2,setServernameFromNonIpHost,HttpsProxyAgent,init_dist3=__esm({"node_modules/https-proxy-agent/dist/index.js"(){import_debug2=__toESM(require_src(),1);init_dist();init_parse_proxy_response();init_dist2();debug2=(0,import_debug2.default)("https-proxy-agent"),setServernameFromNonIpHost=options=>options.servername===void 0&&options.host&&!net2.isIP(options.host)?{...options,servername:options.host}:options,HttpsProxyAgent=class extends Agent2{constructor(proxy,opts){super(opts),this.options={path:void 0},this.proxy=typeof proxy=="string"?new URL(proxy):proxy,this.proxyHeaders=opts?.headers??{},debug2("Creating new HttpsProxyAgent instance: %o",this.proxy.href),opts?.negotiate?this.onProxyAuth=createNegotiateAuth():opts?.onProxyAuth&&(this.onProxyAuth=opts.onProxyAuth);let host=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),port=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...opts?omit(opts,"headers","onProxyAuth","negotiate"):null,host,port}}async connect(req,opts){let{proxy}=this;if(!opts.host)throw new TypeError('No "host" provided');let socket;proxy.protocol==="https:"?(debug2("Creating `tls.Socket`: %o",this.connectOpts),socket=tls.connect(setServernameFromNonIpHost(this.connectOpts))):(debug2("Creating `net.Socket`: %o",this.connectOpts),socket=net2.connect(this.connectOpts));let headers=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},host=net2.isIPv6(opts.host)?`[${opts.host}]`:opts.host,payload=`CONNECT ${host}:${opts.port} HTTP/1.1\r
|
|
11
|
+
`;if(proxy.username||proxy.password){let auth=`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;headers["Proxy-Authorization"]=`Basic ${Buffer.from(auth).toString("base64")}`}headers.Host=`${host}:${opts.port}`,headers["Proxy-Connection"]||(headers["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let name of Object.keys(headers))payload+=`${name}: ${headers[name]}\r
|
|
12
|
+
`;let proxyResponsePromise=parseProxyResponse(socket);socket.write(`${payload}\r
|
|
13
|
+
`);let{connect:connect3,buffered}=await proxyResponsePromise;if(req.emit("proxyConnect",connect3),this.emit("proxyConnect",connect3,req),req.emit("proxy",{proxy:this.proxy.href,socket}),connect3.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug2("Upgrading socket connection to TLS"),tls.connect({...omit(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;if(connect3.statusCode===407&&this.onProxyAuth){debug2("Got 407 response, invoking onProxyAuth callback"),socket.destroy();let proxyAuthenticate=connect3.headers["proxy-authenticate"]||"",scheme=Array.isArray(proxyAuthenticate)?proxyAuthenticate[0].split(/\s/)[0]:proxyAuthenticate.split(/\s/)[0],authResponse=await this.onProxyAuth({response:connect3,scheme});return this._connectWithAuth(req,opts,authResponse.headers)}socket.destroy();let fakeSocket=new net2.Socket({writable:!1});return fakeSocket.readable=!0,req.once("socket",s=>{debug2("Replaying proxy buffer for failed request"),assert(s.listenerCount("data")>0),s.push(buffered),s.push(null)}),fakeSocket}async _connectWithAuth(req,opts,authHeaders){let{proxy}=this,socket;proxy.protocol==="https:"?socket=tls.connect(setServernameFromNonIpHost(this.connectOpts)):socket=net2.connect(this.connectOpts);let headers=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},host=net2.isIPv6(opts.host)?`[${opts.host}]`:opts.host,payload=`CONNECT ${host}:${opts.port} HTTP/1.1\r
|
|
14
|
+
`;if(proxy.username||proxy.password){let auth=`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;headers["Proxy-Authorization"]=`Basic ${Buffer.from(auth).toString("base64")}`}Object.assign(headers,authHeaders),headers.Host=`${host}:${opts.port}`,headers["Proxy-Connection"]||(headers["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let name of Object.keys(headers))payload+=`${name}: ${headers[name]}\r
|
|
15
|
+
`;let proxyResponsePromise=parseProxyResponse(socket);socket.write(`${payload}\r
|
|
16
|
+
`);let{connect:connect3}=await proxyResponsePromise;if(req.emit("proxyConnect",connect3),this.emit("proxyConnect",connect3,req),connect3.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug2("Upgrading socket connection to TLS"),tls.connect({...omit(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;throw socket.destroy(),new Error(`Proxy authentication failed with status ${connect3.statusCode} after retry`)}};HttpsProxyAgent.protocols=["http","https"]}});var init_https_proxy_agent=__esm({"https-proxy-agent-named-export:https-proxy-agent"(){init_dist3()}});init_https_proxy_agent();export{HttpsProxyAgent};
|
package/dist/bundle/chunks/{mistral-conversations-Q3AWZJAZ.js → mistral-conversations-IRKPOWEP.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-AXIIZGTV.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,clampThinkingLevel}from"./chunk-
|
|
2
|
+
import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-AXIIZGTV.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.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;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(context.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,context,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?.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,shouldUseReasoning=model.reasoning&&reasoning!==void 0;return stream(model,context,{...base,promptMode:shouldUseReasoning&&usesPromptModeReasoning(model)?"reasoning":void 0,reasoningEffort:shouldUseReasoning&&usesReasoningEffort(model)?mapReasoningEffort(model,reasoning):void 0})};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{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"))};return context.tools?.length&&(payload.tools=toFunctionTools(context.tools)),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),context.systemPrompt&&payload.messages.unshift({role:"system",content:sanitizeSurrogates(context.systemPrompt)}),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){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(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);(!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??"");(!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 msg of messages){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 usesReasoningEffort(model){return model.id==="mistral-small-2603"||model.id==="mistral-small-latest"||model.id==="mistral-medium-3.5"}function usesPromptModeReasoning(model){return model.reasoning&&!usesReasoningEffort(model)}function mapReasoningEffort(model,level){return model.thinkingLevelMap?.[level]??"high"}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{AnthropicError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MIN_MEMORY_SYNC_INTERVAL_MS,ToolError,__classPrivateFieldGet,__classPrivateFieldSet,checkMemorySyncInterval,decodeUTF8,encodeUTF8,isStatus,loggerFor,promiseWithResolvers}from"./chunk-PWUXXUIP.js";import"./chunk-4L3WN2XY.js";import*as fs3 from"node:fs/promises";import*as fssync2 from"node:fs";import*as path5 from"node:path";import*as cp from"node:child_process";import*as crypto 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}:{}}}import*as fs from"node:fs/promises";import*as path from"node:path";import{randomUUID}from"node:crypto";var DIR_CREATE_MODE=493,FILE_CREATE_MODE=420;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 fs.realpath(prefix)}catch(realpathErr){let isLink;try{isLink=(await fs.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 fs.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}-${randomUUID()}`),handle;try{handle=await fs.open(tempPath,"wx",FILE_CREATE_MODE),await handle.writeFile(content,"utf-8"),await handle.sync(),await handle.close(),handle=void 0,await fs.rename(tempPath,targetPath)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fs.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"}`}}import*as fs2 from"node:fs/promises";import*as fssync from"node:fs";import*as path2 from"node:path";import{execFile}from"node:child_process";import{promisify}from"node:util";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var execFileAsync=promisify(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=path2.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}),dirname5=path2.basename(version.name.trim());(dirname5===""||dirname5==="."||dirname5==="..")&&(dirname5=skill.skill_id);let dest=path2.resolve(skillsRoot,dirname5);if(dest!==skillsRoot&&!dest.startsWith(skillsRoot+path2.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 fs2.rm(dest,{recursive:!0,force:!0}),await fs2.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 fs2.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&&(path2.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 fs2.readdir(dir,{withFileTypes:!0}))if(entry.isDirectory())await assertOnlyPlainEntries(path2.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=path2.join(dest,`.skill-archive-${process.pid}-${Date.now()}`);if(!resp.body)throw new AnthropicError("skill download response had no body");await pipeline(Readable.fromWeb(resp.body),fssync.createWriteStream(tmp));let stage=path2.join(path2.dirname(dest),`.skill-stage-${process.pid}-${Date.now()}`),excludeFile=path2.join(path2.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 fs2.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?path2.join(stage,top):stage,entries=await fs2.readdir(srcRoot).catch(e=>{throw errnoCode(e)==="ENOENT"?new AnthropicError(INCONSISTENT_LISTING):e});for(let entry of entries)await fs2.rename(path2.join(srcRoot,entry),path2.join(dest,entry))}finally{await fs2.rm(tmp,{force:!0}),await fs2.rm(excludeFile,{force:!0}),await fs2.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 fs2.writeFile(excludeFile,patterns.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",archive,"-C",stage,"-X",excludeFile])}async function readHead(file,n){let handle=await fs2.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()}}import*as path4 from"node:path";import{createHash as createHash2}from"node:crypto";import*as fsp from"node:fs/promises";import*as path3 from"node:path";import{constants as C}from"node:fs";import{createHash,randomBytes}from"node:crypto";var 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 extends Error{constructor(reason,relPath){super(`path ${JSON.stringify(relPath)} ${reason}`),this.name="FileStoreError",this.reason=reason,this.relPath=relPath}};FileStoreError.ESCAPES_ROOT="escapes the store root";FileStoreError.IS_A_SYMLINK="is a symlink";FileStoreError.NOT_A_FILE="is not a regular file";FileStoreError.NOT_A_DIRECTORY="is not a directory";FileStoreError.NOT_UTF8="is not valid utf-8";FileStoreError.MOVE_DESTINATION_EXISTS="already exists";function isPathLegal(p){return p.startsWith("/")&&!p.split("/").includes("..")}var FileStore=class _FileStore{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 _FileStore(path3.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,path3.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=path3.relative(this.rootPath,dest).split(path3.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,path3.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(path3.posix.isAbsolute(norm)||parts.includes(".."))throw new FileStoreError(FileStoreError.ESCAPES_ROOT,relPath);return parts.length===0?this.rootPath:path3.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}};FileStore.isPathLegal=isPathLegal;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=path3.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=path3.relative(root,dir);if(below==="")return;let current=root;for(let part of below.split(path3.sep)){current=path3.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=path3.join(path3.dirname(dest),`.fs-${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=createHash("sha256"),handle=await openRegularFile(path3.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([path3.relative(root,full).split(path3.sep).join("/"),full])}),out.sort(),out}async function symlinksInDir(root,under,base){let relOf=full=>path3.relative(root,full).split(path3.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=path3.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 createHash2("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{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})}}};_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 path4.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})};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(resolve5=>{onAbort=resolve5,signal.aborted&&resolve5()});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=fs3.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{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_${crypto.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:resolve5}=promiseWithResolvers();__classPrivateFieldSet(this,_BashSession_waiting,{sentinel,resolve:resolve5},"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()}};_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()}};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 fs3.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 fs3.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 stream=fssync2.createReadStream(abs,{highWaterMark:READ_STREAM_CHUNK_BYTES});try{for await(let chunk of stream)if(lines.collectFrom(chunk),lines.rangeIsCollected())break}finally{stream.destroy()}return lines.text()}var LineRangeCollector=class{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")}};_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.`)};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 fs3.mkdir(path5.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 fs3.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 fs3.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(path5.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):path5.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=path5.join(entry.parentPath,entry.name),real;try{real=await fs3.realpath(full)}catch{continue}if(!isWithin(realRoot,real))continue;let mtime=0;try{mtime=(await fs3.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=path5.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((resolve5,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 resolve5(out+`
|
|
15
|
+
[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);if(code===0)return resolve5(out);if(code===1)return resolve5("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 fs3.stat(root).catch(()=>null))?.isFile()?await grepFile(root,re,push):await walk2(root,"",rel=>grepFile(path5.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 stream=fssync2.createReadStream(file,{encoding:"utf8"}),rl=readline.createInterface({input:stream,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{stream.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 fs3.readdir(path5.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?path5.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(path5.delimiter);for(let d of dirs){let candidate=path5.join(d,"rg");try{return await fs3.access(candidate,fssync2.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};
|