hummin-cli 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/bundle/chunks/anthropic-messages-RS73YAAL.js +6 -0
- package/dist/bundle/chunks/anthropic.js +75 -0
- package/dist/bundle/chunks/azure-openai-responses-WDUJVP6K.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +78 -0
- package/dist/bundle/chunks/chunk-4L3WN2XY.js +2 -0
- package/dist/bundle/chunks/chunk-6CYCI3EJ.js +12 -0
- package/dist/bundle/chunks/chunk-6R7UI4IY.js +2 -0
- package/dist/bundle/chunks/chunk-7ZC4UXSL.js +2 -0
- package/dist/bundle/chunks/chunk-A3JYRWB6.js +2 -0
- package/dist/bundle/chunks/chunk-AXIIZGTV.js +2 -0
- package/dist/bundle/chunks/chunk-DRQDKNXA.js +2 -0
- package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +42 -0
- package/dist/bundle/chunks/chunk-GMWCTUPB.js +2 -0
- package/dist/bundle/chunks/chunk-GTBU4EAF.js +2 -0
- package/dist/bundle/chunks/chunk-L2ZPNLYD.js +2 -0
- package/dist/bundle/chunks/chunk-NUHFSC37.js +25 -0
- package/dist/bundle/chunks/chunk-NV6PWB3O.js +11 -0
- package/dist/bundle/chunks/chunk-OENBO5ZB.js +1589 -0
- package/dist/bundle/chunks/chunk-PGXDEOVV.js +2 -0
- package/dist/bundle/chunks/chunk-PJACZCIR.js +2 -0
- package/dist/bundle/chunks/chunk-PRRNXB7S.js +2 -0
- package/dist/bundle/chunks/chunk-TEPMHNKQ.js +2 -0
- package/dist/bundle/chunks/chunk-TRDNDS6A.js +4 -0
- package/dist/bundle/chunks/chunk-USJZMAIR.js +2 -0
- package/dist/bundle/chunks/chunk-WG5HGQZU.js +44 -0
- package/dist/bundle/chunks/chunk-XDUWOHPL.js +6 -0
- package/dist/bundle/chunks/chunk-XNGRGP62.js +2 -0
- package/dist/bundle/chunks/github-copilot.js +2 -0
- package/dist/bundle/chunks/google-generative-ai-BZMAU2ZY.js +2 -0
- package/dist/bundle/chunks/google-vertex-PW4J25VW.js +2 -0
- package/dist/bundle/chunks/https-proxy-agent-NITCU2PD.js +13 -0
- package/dist/bundle/chunks/image-resize-worker.js +2 -0
- package/dist/bundle/chunks/kimi-coding.js +2 -0
- package/dist/bundle/chunks/lib-HGQMNYVT.js +9 -0
- package/dist/bundle/chunks/mistral-conversations-KKK7YQAI.js +5 -0
- package/dist/bundle/chunks/multipart-parser-SQ6GDJL7.js +3 -0
- package/dist/bundle/chunks/node-O3RIBJRH.js +16 -0
- package/dist/bundle/chunks/node-TWVVAGPO.js +2 -0
- package/dist/bundle/chunks/openai-codex-responses-Y5ODP57V.js +10 -0
- package/dist/bundle/chunks/openai-codex.js +75 -0
- package/dist/bundle/chunks/openai-completions-EIF77N53.js +7 -0
- package/dist/bundle/chunks/openai-responses-3W4DADHO.js +2 -0
- package/dist/bundle/chunks/openrouter-images-N4XVVFSD.js +2 -0
- package/dist/bundle/chunks/openrouter.js +75 -0
- package/dist/bundle/chunks/pi-messages-ZRYGTSON.js +8 -0
- package/dist/bundle/chunks/radius.js +75 -0
- package/dist/bundle/chunks/src-UK77SYZE.js +4 -0
- package/dist/bundle/chunks/xai.js +2 -0
- package/dist/bundle/cli.js +3 -0
- package/dist/bundle/index.js +2 -0
- package/dist/bundle/rpc-entry.js +3 -0
- package/package.json +32 -0
|
@@ -0,0 +1,5 @@
|
|
|
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-GTBU4EAF.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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{statusCode;body;constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
3
|
+
`).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
|
+
`),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
|
+
[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.startsWith("mistral-medium-")||model.id==="zai-glm-5-2"}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,3 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{FormData,file_default,init_esm_min,init_from}from"./chunk-6CYCI3EJ.js";import{__esm}from"./chunk-4L3WN2XY.js";function _fileName(headerValue){let m=headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!m)return;let match=m[2]||m[3]||"",filename=match.slice(match.lastIndexOf("\\")+1);return filename=filename.replace(/%22/g,'"'),filename=filename.replace(/&#(\d{4});/g,(m2,code)=>String.fromCharCode(code)),filename}async function toFormData(Body,ct){if(!/multipart/i.test(ct))throw new TypeError("Failed to fetch");let m=ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!m)throw new TypeError("no or bad content-type header, no multipart boundary");let parser=new MultipartParser(m[1]||m[2]),headerField,headerValue,entryValue,entryName,contentType,filename,entryChunks=[],formData=new FormData,onPartData=ui8a=>{entryValue+=decoder.decode(ui8a,{stream:!0})},appendToFile=ui8a=>{entryChunks.push(ui8a)},appendFileToFormData=()=>{let file=new file_default(entryChunks,filename,{type:contentType});formData.append(entryName,file)},appendEntryToFormData=()=>{formData.append(entryName,entryValue)},decoder=new TextDecoder("utf-8");decoder.decode(),parser.onPartBegin=function(){parser.onPartData=onPartData,parser.onPartEnd=appendEntryToFormData,headerField="",headerValue="",entryValue="",entryName="",contentType="",filename=null,entryChunks.length=0},parser.onHeaderField=function(ui8a){headerField+=decoder.decode(ui8a,{stream:!0})},parser.onHeaderValue=function(ui8a){headerValue+=decoder.decode(ui8a,{stream:!0})},parser.onHeaderEnd=function(){if(headerValue+=decoder.decode(),headerField=headerField.toLowerCase(),headerField==="content-disposition"){let m2=headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m2&&(entryName=m2[2]||m2[3]||""),filename=_fileName(headerValue),filename&&(parser.onPartData=appendToFile,parser.onPartEnd=appendFileToFormData)}else headerField==="content-type"&&(contentType=headerValue);headerValue="",headerField=""};for await(let chunk of Body)parser.write(chunk);return parser.end(),formData}var s,S,f,F,LF,CR,SPACE,HYPHEN,COLON,A,Z,lower,noop,MultipartParser,init_multipart_parser=__esm({"node_modules/node-fetch/src/utils/multipart-parser.js"(){init_from();init_esm_min();s=0,S={START_BOUNDARY:s++,HEADER_FIELD_START:s++,HEADER_FIELD:s++,HEADER_VALUE_START:s++,HEADER_VALUE:s++,HEADER_VALUE_ALMOST_DONE:s++,HEADERS_ALMOST_DONE:s++,PART_DATA_START:s++,PART_DATA:s++,END:s++},f=1,F={PART_BOUNDARY:f,LAST_BOUNDARY:f*=2},LF=10,CR=13,SPACE=32,HYPHEN=45,COLON=58,A=97,Z=122,lower=c=>c|32,noop=()=>{},MultipartParser=class{constructor(boundary){this.index=0,this.flags=0,this.onHeaderEnd=noop,this.onHeaderField=noop,this.onHeadersEnd=noop,this.onHeaderValue=noop,this.onPartBegin=noop,this.onPartData=noop,this.onPartEnd=noop,this.boundaryChars={},boundary=`\r
|
|
3
|
+
--`+boundary;let ui8a=new Uint8Array(boundary.length);for(let i=0;i<boundary.length;i++)ui8a[i]=boundary.charCodeAt(i),this.boundaryChars[ui8a[i]]=!0;this.boundary=ui8a,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=S.START_BOUNDARY}write(data){let i=0,length_=data.length,previousIndex=this.index,{lookbehind,boundary,boundaryChars,index,state,flags}=this,boundaryLength=this.boundary.length,boundaryEnd=boundaryLength-1,bufferLength=data.length,c,cl,mark=name=>{this[name+"Mark"]=i},clear=name=>{delete this[name+"Mark"]},callback=(callbackSymbol,start,end,ui8a)=>{(start===void 0||start!==end)&&this[callbackSymbol](ui8a&&ui8a.subarray(start,end))},dataCallback=(name,clear2)=>{let markSymbol=name+"Mark";markSymbol in this&&(clear2?(callback(name,this[markSymbol],i,data),delete this[markSymbol]):(callback(name,this[markSymbol],data.length,data),this[markSymbol]=0))};for(i=0;i<length_;i++)switch(c=data[i],state){case S.START_BOUNDARY:if(index===boundary.length-2){if(c===HYPHEN)flags|=F.LAST_BOUNDARY;else if(c!==CR)return;index++;break}else if(index-1===boundary.length-2){if(flags&F.LAST_BOUNDARY&&c===HYPHEN)state=S.END,flags=0;else if(!(flags&F.LAST_BOUNDARY)&&c===LF)index=0,callback("onPartBegin"),state=S.HEADER_FIELD_START;else return;break}c!==boundary[index+2]&&(index=-2),c===boundary[index+2]&&index++;break;case S.HEADER_FIELD_START:state=S.HEADER_FIELD,mark("onHeaderField"),index=0;case S.HEADER_FIELD:if(c===CR){clear("onHeaderField"),state=S.HEADERS_ALMOST_DONE;break}if(index++,c===HYPHEN)break;if(c===COLON){if(index===1)return;dataCallback("onHeaderField",!0),state=S.HEADER_VALUE_START;break}if(cl=lower(c),cl<A||cl>Z)return;break;case S.HEADER_VALUE_START:if(c===SPACE)break;mark("onHeaderValue"),state=S.HEADER_VALUE;case S.HEADER_VALUE:c===CR&&(dataCallback("onHeaderValue",!0),callback("onHeaderEnd"),state=S.HEADER_VALUE_ALMOST_DONE);break;case S.HEADER_VALUE_ALMOST_DONE:if(c!==LF)return;state=S.HEADER_FIELD_START;break;case S.HEADERS_ALMOST_DONE:if(c!==LF)return;callback("onHeadersEnd"),state=S.PART_DATA_START;break;case S.PART_DATA_START:state=S.PART_DATA,mark("onPartData");case S.PART_DATA:if(previousIndex=index,index===0){for(i+=boundaryEnd;i<bufferLength&&!(data[i]in boundaryChars);)i+=boundaryLength;i-=boundaryEnd,c=data[i]}if(index<boundary.length)boundary[index]===c?(index===0&&dataCallback("onPartData",!0),index++):index=0;else if(index===boundary.length)index++,c===CR?flags|=F.PART_BOUNDARY:c===HYPHEN?flags|=F.LAST_BOUNDARY:index=0;else if(index-1===boundary.length)if(flags&F.PART_BOUNDARY){if(index=0,c===LF){flags&=~F.PART_BOUNDARY,callback("onPartEnd"),callback("onPartBegin"),state=S.HEADER_FIELD_START;break}}else flags&F.LAST_BOUNDARY&&c===HYPHEN?(callback("onPartEnd"),state=S.END,flags=0):index=0;if(index>0)lookbehind[index-1]=c;else if(previousIndex>0){let _lookbehind=new Uint8Array(lookbehind.buffer,lookbehind.byteOffset,lookbehind.byteLength);callback("onPartData",0,previousIndex,_lookbehind),previousIndex=0,mark("onPartData"),i--}break;case S.END:break;default:throw new Error(`Unexpected state entered: ${state}`)}dataCallback("onHeaderField"),dataCallback("onHeaderValue"),dataCallback("onPartData"),this.index=index,this.state=state,this.flags=flags}end(){if(this.state===S.HEADER_FIELD_START&&this.index===0||this.state===S.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==S.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}}});init_multipart_parser();export{toFormData};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{child_process,crypto,fs,path,stream,util}from"./chunk-7ZC4UXSL.js";import{AnthropicError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MIN_MEMORY_SYNC_INTERVAL_MS,ToolError,__classPrivateFieldGet,__classPrivateFieldSet,checkMemorySyncInterval,decodeUTF8,encodeUTF8,isStatus,loggerFor,promiseWithResolvers}from"./chunk-DTD7JQ7Y.js";import"./chunk-4L3WN2XY.js";import*as fs4 from"node:fs/promises";import*as fssync from"node:fs";import*as path2 from"node:path";import*as cp from"node:child_process";import*as crypto2 from"node:crypto";import*as readline from"node:readline";function betaTool(options){if(options.inputSchema.type!=="object")throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`);return{type:"custom",name:options.name,input_schema:options.inputSchema,description:options.description,run:options.run,parse:content=>content,...options.close?{close:options.close}:{}}}var fs2=fs.promises,DIR_CREATE_MODE=448,FILE_CREATE_MODE=384;function isWithin(root,p){let rel=path.relative(root,p);return rel===""||!rel.startsWith(".."+path.sep)&&rel!==".."&&!path.isAbsolute(rel)}async function containingRoot(roots,target){for(let root of roots)if(isWithin(await canonicalize(path.resolve(root)),target))return root}var MAX_SYMLINK_HOPS=40;function errnoCode(err){let code=err?.code;return typeof code=="string"?code:void 0}async function canonicalize(abs){let tail=[],prefix=abs,hops=0;for(;;){let real;try{real=await fs2.realpath(prefix)}catch(realpathErr){let isLink;try{isLink=(await fs2.lstat(prefix)).isSymbolicLink()}catch(lstatErr){let code=errnoCode(lstatErr);if(code!=="ENOENT"&&code!=="ENOTDIR")throw lstatErr;let parent=path.dirname(prefix);if(parent===prefix)throw lstatErr;tail.push(path.basename(prefix)),prefix=parent;continue}if(!isLink)throw realpathErr;if(++hops>MAX_SYMLINK_HOPS)throw Object.assign(new Error("too many levels of symbolic links"),{code:"ELOOP"});prefix=path.resolve(path.dirname(prefix),await fs2.readlink(prefix));continue}return tail.length?path.join(real,...tail.reverse()):real}}async function confineToRoot(root,p,opts){let allowedRoots=opts?.allowedRoots??[],realRoot=await canonicalize(path.resolve(root)),real;try{real=await canonicalize(path.resolve(realRoot,p))}catch(err){throw new ToolError(fsErrorMessage(err,`path ${JSON.stringify(p)}`))}if(isWithin(realRoot,real)||await containingRoot(allowedRoots,real)!==void 0)return real;let permitted=allowedRoots.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new ToolError(`path ${JSON.stringify(p)} is outside ${permitted}`)}async function atomicWriteFile(targetPath,content){let dir=path.dirname(targetPath),tempPath=path.join(dir,`.tmp-${process.pid}-${crypto.randomUUID()}`),existingMode=await fs2.stat(targetPath).then(st=>st.mode&511,()=>{}),handle;try{handle=await fs2.open(tempPath,"wx",FILE_CREATE_MODE),existingMode!==void 0&&await handle.chmod(existingMode),await handle.writeFile(content,"utf-8"),await handle.sync(),await handle.close(),handle=void 0,await fs2.rename(tempPath,targetPath)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fs2.unlink(tempPath).catch(()=>{}),err}}function fsErrorMessage(err,file){let code=errnoCode(err);switch(code){case"ENOENT":return`${file}: no such file or directory`;case"EACCES":case"EPERM":return`${file}: permission denied`;case"ENOTDIR":return`${file}: not a directory`;case"EISDIR":return`${file}: is a directory`;case"ELOOP":return`${file}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${file}: file name too long`;case"ENOSPC":return`${file}: no space left on device`;case"EMFILE":case"ENFILE":return`${file}: too many open files`;default:return`${file}: ${code!==void 0?`i/o error (${code})`:"i/o error"}`}}var fs3=fs.promises,execFileAsync=util.promisify(child_process.execFile);async function setupSkills(ctx){let{client,sessionId}=ctx;if(!client)return async()=>{};let log=loggerFor(client),session=ctx.session;if(!session){if(sessionId===void 0)return async()=>{};log.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),session=await client.beta.sessions.retrieve(sessionId)}let skillsRoot=path.resolve(ctx.workdir,"skills"),created=[];for(let skill of session.agent.skills)try{let version=await client.beta.skills.versions.retrieve(skill.version,{skill_id:skill.skill_id}),dirname2=path.basename(version.name.trim());(dirname2===""||dirname2==="."||dirname2==="..")&&(dirname2=skill.skill_id);let dest=path.resolve(skillsRoot,dirname2);if(dest!==skillsRoot&&!dest.startsWith(skillsRoot+path.sep)){log.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:version.name});continue}let resp=await client.beta.skills.versions.download(version.id,{skill_id:skill.skill_id});await fs3.rm(dest,{recursive:!0,force:!0}),await fs3.mkdir(dest,{recursive:!0,mode:DIR_CREATE_MODE}),created.push(dest),await extractSkillArchive(resp,dest),log.info("downloaded skill",{component:"agent-tool-context",skill_id:skill.skill_id,version:version.id,dest})}catch(e){log.warn("failed to download skill",{component:"agent-tool-context",skill_id:skill.skill_id,error:String(e)})}return async()=>{for(let dest of created)await fs3.rm(dest,{recursive:!0,force:!0}).catch(e=>{log.warn("failed to clean up skill",{component:"agent-tool-context",dest,error:String(e)})})}}function assertSafeMemberNames(names){for(let raw of names){let entry=raw.trim();if(entry&&(path.isAbsolute(entry)||entry.split(/[\\/]/).includes("..")))throw new AnthropicError(`refusing to extract unsafe archive member: ${entry}`)}}var INCONSISTENT_LISTING="skill archive listing is inconsistent; refusing to extract",PLAIN_TYPE_CHARS={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function listingLines(listing){let lines=listing.split(`
|
|
3
|
+
`);return lines[lines.length-1]===""&&lines.pop(),lines}function canExcludeVerbatim(cmd,name){return/^[\x20-\x7E]+$/.test(name)&&!/[\\^#]/.test(name)&&!(cmd==="unzip"&&name.startsWith("-"))}function classifyArchiveListing(cmd,names,typed){let nameLines=listingLines(names),typedLines=listingLines(typed);if(nameLines.length!==typedLines.length)throw new AnthropicError(INCONSISTENT_LISTING);let plain=[],special=[];return nameLines.forEach((name,i)=>{if(PLAIN_TYPE_CHARS[cmd].has(typedLines[i].charAt(0))){plain.push(name);return}if(!canExcludeVerbatim(cmd,name))throw new AnthropicError(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(name)}`);special.push(name)}),{plain,special}}async function assertOnlyPlainEntries(dir){for(let entry of await fs3.readdir(dir,{withFileTypes:!0}))if(entry.isDirectory())await assertOnlyPlainEntries(path.join(dir,entry.name));else if(!entry.isFile())throw new AnthropicError(INCONSISTENT_LISTING)}async function runArchiveTool(cmd,args){try{let{stdout}=await execFileAsync(cmd,args);return stdout}catch(e){throw errnoCode(e)==="ENOENT"?new AnthropicError(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`):e}}function archiveTopDir(names){let top,nested=!1;for(let raw of names){let parts=raw.trim().split("/").filter(p=>p!==""&&p!==".");if(parts.length===0)continue;let first=parts[0];if(top===void 0)top=first;else if(first!==top)return"";parts.length>1&&(nested=!0)}return top!==void 0&&nested?top:""}async function extractSkillArchive(resp,dest){let tmp=path.join(dest,`.skill-archive-${process.pid}-${Date.now()}`);if(!resp.body)throw new AnthropicError("skill download response had no body");await stream.promises.pipeline(stream.Readable.fromWeb(resp.body),fs.createWriteStream(tmp));let stage=path.join(path.dirname(dest),`.skill-stage-${process.pid}-${Date.now()}`),excludeFile=path.join(path.dirname(dest),`.skill-exclude-${process.pid}-${Date.now()}`);try{let head=await readHead(tmp,4),isZip=head.length>=4&&head[0]===80&&head[1]===75&&head[2]===3&&head[3]===4,archiveCmd=isZip?"unzip":"tar",names=await runArchiveTool(archiveCmd,isZip?["-Z1",tmp]:["-tf",tmp]),typed=await runArchiveTool(archiveCmd,isZip?["-Z","--h","--t",tmp]:["-tvf",tmp]),{plain,special}=classifyArchiveListing(archiveCmd,names,typed);assertSafeMemberNames([...plain,...special]);let top=archiveTopDir(plain);await fs3.mkdir(stage,{recursive:!0,mode:DIR_CREATE_MODE}),plain.length>0&&await runArchiveTool(archiveCmd,await extractArgs(archiveCmd,tmp,stage,special,excludeFile)),await assertOnlyPlainEntries(stage);let srcRoot=top?path.join(stage,top):stage,entries=await fs3.readdir(srcRoot).catch(e=>{throw errnoCode(e)==="ENOENT"?new AnthropicError(INCONSISTENT_LISTING):e});for(let entry of entries)await fs3.rename(path.join(srcRoot,entry),path.join(dest,entry))}finally{await fs3.rm(tmp,{force:!0}),await fs3.rm(excludeFile,{force:!0}),await fs3.rm(stage,{recursive:!0,force:!0})}}async function extractArgs(cmd,archive,stage,special,excludeFile){let patterns=special.map(name=>name.replace(/[*?[\\]/g,"\\$&"));return cmd==="unzip"?["-oq",archive,"-d",stage,...patterns.length>0?["-x",...patterns]:[]]:patterns.length===0?["-xf",archive,"-C",stage]:(await fs3.writeFile(excludeFile,patterns.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",archive,"-C",stage,"-X",excludeFile])}async function readHead(file,n){let handle=await fs3.open(file,"r");try{let buf=Buffer.alloc(n),{bytesRead}=await handle.read(buf,0,n,0);return buf.subarray(0,bytesRead)}finally{await handle.close()}}var fsp=fs.promises,C=fs.constants,OWNER_ONLY_DIR_MODE=448,OWNER_ONLY_FILE_MODE=384,OWNER_ONLY_EXEC_MODE=448,O_NOFOLLOW=C.O_NOFOLLOW??0,O_NONBLOCK=C.O_NONBLOCK??0,FileStoreError=class 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(path.resolve(root),removedOnDispose,opts?.utf8??!1)}async createRoot(){await makeDirAndAncestors(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){this.removedOnDispose&&await fsp.rm(this.rootPath,{recursive:!0,force:!0})}async put(relPath,data,opts){let tail=relPath.replace(/\\/g,"/");if(tail.endsWith("/")||tail.endsWith("/.")||tail===""||tail===".")throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let dest=this.resolveUnderRoot(relPath),payload=typeof data=="string"?encodeUTF8(data):data;this.requireUtf8(relPath,payload),await makeDirsBelowRoot(this.rootPath,path.dirname(dest)),await replaceViaTemp(dest,payload,opts?.executable??!1)}async get(relPath){let dest=this.resolveUnderRoot(relPath),handle;try{handle=await openRegularFile(relPath,dest)}catch(e){if(e.code==="ENOENT")return null;throw e}let data;try{let buf=await handle.readFile();data=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}finally{await handle.close()}return this.requireUtf8(relPath,data),data}async ls(under="/"){let base=this.resolveUnderRoot(under);return new Set((await filenamesInDir(this.rootPath,under,base)).map(([rel])=>rel))}async findSymlinks(under="/"){let base=this.resolveUnderRoot(under);return symlinksInDir(this.rootPath,under,base)}async hashtree(under="/"){let base=this.resolveUnderRoot(under),walkStartNs=_internals.nowNs(),out=Object.create(null);for(let[rel,full]of await filenamesInDir(this.rootPath,under,base)){let sha=await this.hashViaCache(rel,full,walkStartNs);sha!==null&&(out[rel]=sha)}return out}async hashFile(relPath){let dest=this.resolveUnderRoot(relPath),st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(st.isSymbolicLink())throw new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath);if(!st.isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let rel=path.relative(this.rootPath,dest).split(path.sep).join("/");return this.hashViaCache(rel,dest,_internals.nowNs())}async move(src,dst){let s=this.resolveUnderRoot(src),d=this.resolveUnderRoot(dst);if(s===this.rootPath||d===this.rootPath)return;if(await fsp.stat(d).then(()=>!0,()=>!1))throw new FileStoreError(FileStoreError.MOVE_DESTINATION_EXISTS,dst);await makeDirsBelowRoot(this.rootPath,path.dirname(d)),await fsp.rename(s,d)}async remove(relPath){let dest=this.resolveUnderRoot(relPath);if(dest===this.rootPath)return;let st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}if(st.isDirectory())await fsp.rm(dest,{recursive:!0,force:!0});else try{await fsp.unlink(dest)}catch(e){if(e.code!=="ENOENT")throw e}}resolveUnderRoot(relPath){let norm=relPath.replace(/\\/g,"/").replace(/^\/+/,""),parts=norm.split("/").filter(p=>p!==""&&p!==".");if(path.posix.isAbsolute(norm)||parts.includes(".."))throw new FileStoreError(FileStoreError.ESCAPES_ROOT,relPath);return parts.length===0?this.rootPath:path.join(this.rootPath,...parts)}requireUtf8(relPath,data){if(this.decoder)try{this.decoder.decode(data)}catch{throw new FileStoreError(FileStoreError.NOT_UTF8,relPath)}}async hashViaCache(rel,full,walkStartNs){let st;try{st=await fsp.lstat(full,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(!st.isFile())return null;let cached=this.hashes.get(rel),sha;if(cached!==void 0&&unchangedSinceHashed(cached,st))sha=cached.sha;else try{sha=await _internals.hashFile(full)}catch(e){let code=e.code;if(code==="ENOENT"||e instanceof FileStoreError||code==="ELOOP"||code==="EMLINK")return null;throw e}return oldEnoughToCache(st,walkStartNs)&&this.hashes.set(rel,{mtimeNs:st.mtimeNs,ctimeNs:st.ctimeNs,size:st.size,sha}),sha}};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=path.dirname(current);if(parent===current)break;current=parent}for(let directory of missing.reverse())try{await fsp.mkdir(directory,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}async function makeDirsBelowRoot(root,dir){let below=path.relative(root,dir);if(below==="")return;let current=root;for(let part of below.split(path.sep)){current=path.join(current,part);try{await fsp.mkdir(current,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}}async function replaceViaTemp(dest,data,isExecutable){let mode=isExecutable?OWNER_ONLY_EXEC_MODE:OWNER_ONLY_FILE_MODE,tmp=path.join(path.dirname(dest),`.fs-${crypto.randomBytes(8).toString("hex")}.tmp`),handle;try{handle=await fsp.open(tmp,C.O_WRONLY|C.O_CREAT|C.O_EXCL|O_NOFOLLOW,mode),await handle.writeFile(data),await handle.close(),handle=void 0,await fsp.rename(tmp,dest)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fsp.unlink(tmp).catch(()=>{}),err}}async function openRegularFile(relPath,dest){let handle;try{handle=await fsp.open(dest,C.O_RDONLY|O_NOFOLLOW|O_NONBLOCK)}catch(e){let code=e.code;throw code==="ELOOP"||code==="EMLINK"?new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath):e}try{if(!(await handle.stat()).isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath)}catch(e){throw await handle.close().catch(()=>{}),e}return handle}async function hashFile(full){let digest=crypto.createHash("sha256"),handle=await openRegularFile(path.basename(full),full),buf=new Uint8Array(1024*1024);try{for(;;){let{bytesRead}=await handle.read(buf,0,buf.length);if(bytesRead===0)break;digest.update(buf.subarray(0,bytesRead))}}finally{await handle.close()}return digest.digest("hex")}async function filenamesInDir(root,under,base){if(!await requireDir(under,base))return[];let out=[];return await walk(base,(full,entry)=>{entry.isFile()&&out.push([path.relative(root,full).split(path.sep).join("/"),full])}),out.sort(),out}async function symlinksInDir(root,under,base){let relOf=full=>path.relative(root,full).split(path.sep).join("/"),st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return new Set;throw e}if(st.isSymbolicLink())return new Set([relOf(base)]);if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);let out=new Set;return await walk(base,(full,entry)=>{entry.isSymbolicLink()&&out.add(relOf(full))}),out}async function requireDir(under,base){let st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return!1;throw e}if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);return!0}async function walk(base,visit){let stack=[base];for(;stack.length;){let dir=stack.pop(),entries;try{entries=await fsp.readdir(dir,{withFileTypes:!0})}catch(e){if(e.code==="ENOENT")continue;throw e}for(let entry of entries){let full=path.join(dir,entry.name);visit(full,entry),entry.isDirectory()&&!entry.isSymbolicLink()&&stack.push(full)}}}function unchangedSinceHashed(cached,st){return st.mtimeNs===cached.mtimeNs&&st.ctimeNs===cached.ctimeNs&&st.size===cached.size}function oldEnoughToCache(st,walkStartNs){return(st.mtimeNs>st.ctimeNs?st.mtimeNs:st.ctimeNs)<walkStartNs-_internals.timestampTrustMarginNs}var TIMESTAMP_TRUST_MARGIN_NS=2000000000n,_internals={hashFile,timestampTrustMarginNs:TIMESTAMP_TRUST_MARGIN_NS,nowNs:()=>BigInt(Date.now())*1000000n},LocalFileStore=FileStore,asyncDispose=Symbol.asyncDispose;asyncDispose&&Object.defineProperty(FileStore.prototype,asyncDispose,{value:FileStore.prototype.dispose,configurable:!0,writable:!0});var _SessionMemoryStores_instances,_SessionMemoryStores_client,_SessionMemoryStores_workdir,_SessionMemoryStores_syncIntervalMs,_SessionMemoryStores_syncDeletions,_SessionMemoryStores_log,_SessionMemoryStores_lastSyncAt,_SessionMemoryStores_finished,_SessionMemoryStores_stores,_SessionMemoryStores_storeRoot,_SessionMemoryStores_scanMarker,_SessionMemoryStores_syncStore,_SessionMemoryStores_flushStore,_SessionMemoryStores_recover,_SessionMemoryStores_stampAndPull,_SessionMemoryStores_syncPath,_SessionMemoryStores_removeLocal,_SessionMemoryStores_write,_SessionMemoryStores_pullAll,_SessionMemoryStores_uploadAll,_SessionMemoryStores_listMemories,_SessionMemoryStores_upload,_SessionMemoryStores_corroboratedDelete,_SessionMemoryStores_deleteRemote,MEMORY_FLUSH_TIMEOUT_MS=3e4,MARKER_PATH=".anthropic-memory-store",MARKER_VERSION=1;function markerSha(memoryStoreId){return crypto.createHash("sha256").update(`version ${MARKER_VERSION}
|
|
6
|
+
${memoryStoreId}`,"utf-8").digest("hex")}var DELETE_CORROBORATION_MS=3e4,LIST_PAGE_SIZE=100,FULL_LIST_PAGE_SIZE=20,FETCH_CONCURRENCY=16,UPLOAD_CONCURRENCY=32,DELETE_CAP_FLOOR=8,DELETE_CAP_CEILING=50,SessionMemoryError=class extends AnthropicError{constructor(message,cause){super(message),this.name="SessionMemoryError",cause!==void 0&&(this.cause=cause)}},DeletePass=class{constructor(mode,cap,waiveWindow){this.mode=mode,this.cap=cap,this.waiveWindow=waiveWindow,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){return this.attempted>=this.cap?(this.capped++,!1):(this.attempted++,!0)}},SessionMemoryStores=class{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 path.join(__classPrivateFieldGet(this,_SessionMemoryStores_workdir,"f"),"memory",resource.name||resource.memory_store_id)},_SessionMemoryStores_scanMarker=async function(store){let local=await store.files.hashtree(),marker=local[MARKER_PATH];return delete local[MARKER_PATH],marker===markerSha(store.memoryStoreId)?{files:local,markerOk:!0,distrustReason:null}:{files:local,markerOk:!1,distrustReason:marker!==void 0?"the marker file does not match this store":"the marker file is gone"}},_SessionMemoryStores_syncStore=async function(store,final){try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store),local=scan.files;if(!scan.markerOk){if(Object.keys(local).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder as found and not syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"the folder or its marker is gone");return}if(Object.keys(local).length===0&&store.baseline.size>1){await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"every memory file is gone at once");return}let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId))remote.set(rel,item);let deletes=new DeletePass(__classPrivateFieldGet(this,_SessionMemoryStores_syncDeletions,"f"),Math.max(DELETE_CAP_FLOOR,Math.min(DELETE_CAP_CEILING,Math.floor(store.baseline.size/4))),final),pulls=[],baseline=new Map,paths=[...new Set([...remote.keys(),...Object.keys(local),...store.baseline.keys()])].sort();for(let rel of paths){let remoteItem=remote.get(rel),localSha=local[rel],baseSha=store.baseline.get(rel),sha;localSha===void 0&&baseSha!==void 0&&remoteItem!==void 0&&remoteItem.content_sha256===baseSha&&!store.readOnly?sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_corroboratedDelete).call(this,store,rel,remoteItem,baseSha,deletes):sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncPath).call(this,store,rel,remoteItem,localSha,pulls),sha!==void 0&&baseline.set(rel,sha)}store.baseline=baseline,await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_pullAll).call(this,store,pulls),deletes.suppressed>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:deletes.suppressed,memory_store_id:store.memoryStoreId}),deletes.capped>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`delete cap reached: ${deletes.mode==="log_only"?"would send":"sent"} ${deletes.attempted} deletes, held ${deletes.capped} for later syncs`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory sync failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_flushStore=async function(store,signal){let dirty=new Map,unsent=new Set,push=async()=>{if(store.readOnly)return;let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; not uploading anything from the memory store folder`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}for(let[rel,sha]of Object.entries(scan.files))sha!==store.baseline.get(rel)&&store.refusedShas.get(rel)!==sha&&(dirty.set(rel,sha),unsent.add(rel));if(dirty.size===0||signal?.aborted)return;let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId)){if(signal?.aborted)return;remote.set(rel,item)}let uploads=[];for(let rel of[...dirty.keys()].sort()){let localSha=dirty.get(rel),baseSha=store.baseline.get(rel),existing=remote.get(rel);if(existing!==void 0&&existing.content_sha256===localSha){store.baseline.set(rel,existing.content_sha256),unsent.delete(rel);continue}if(existing!==void 0&&existing.content_sha256!==baseSha){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:rel,memory_store_id:store.memoryStoreId}),unsent.delete(rel);continue}uploads.push([rel,localSha,existing])}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_uploadAll).call(this,store,uploads,unsent,signal)};try{await settledOrAborted(push(),signal),signal?.aborted&&unsent.size>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`memory flush cut off part-way; ${unsent.size} of ${dirty.size} changed files had not finished uploading`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory flush failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_recover=async function(store,reason){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${reason}; re-downloading the memory store folder instead of syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId}),await store.files.createRoot(),await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store)},_SessionMemoryStores_stampAndPull=async function(store){store.baseline=new Map,store.pendingDeletes.clear(),await store.files.put(MARKER_PATH,`version ${MARKER_VERSION}
|
|
7
|
+
${store.memoryStoreId}`);for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId,"full"))await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},_SessionMemoryStores_syncPath=async function(store,rel,remote,localSha,pulls){let baseSha=store.baseline.get(rel);if(localSha!==void 0&&store.pendingDeletes.delete(rel),!remote){if(localSha===void 0){store.pendingDeletes.delete(rel);return}if(baseSha!==void 0){if(localSha===baseSha){let fresh=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_removeLocal).call(this,store,rel,baseSha);if(fresh===void 0)return;if(fresh===baseSha)return baseSha;localSha=fresh}store.readOnly?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:rel,memory_store_id:store.memoryStoreId}):store.refusedShas.get(rel)!==localSha&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:rel,memory_store_id:store.memoryStoreId})}return store.readOnly||store.refusedShas.get(rel)===localSha?void 0:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,void 0)}let remoteSha=remote.content_sha256,remoteChanged=remoteSha!==baseSha,locallyEdited=localSha!==void 0&&localSha!==baseSha&&localSha!==remoteSha,localChanged=!store.readOnly&&locallyEdited;return localSha===void 0&&baseSha!==void 0?(remoteChanged&&(__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:rel,memory_store_id:store.memoryStoreId}),store.pendingDeletes.delete(rel),pulls.push([rel,remote])),baseSha):remoteChanged?localSha===remoteSha?remoteSha:(locallyEdited&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}),pulls.push([rel,remote]),baseSha):localChanged?store.refusedShas.get(rel)===localSha?remoteSha:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,remote)??remoteSha:remoteSha},_SessionMemoryStores_removeLocal=async function(store,rel,expectSha){let freshSha;try{freshSha=await store.files.hashFile(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return expectSha}if(freshSha!==null){if(freshSha!==expectSha)return freshSha;try{await store.files.remove(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove memory deleted remotely",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),expectSha}}},_SessionMemoryStores_write=async function(store,rel,content){try{await store.files.put(rel,content)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to write memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),!1}return!0},_SessionMemoryStores_pullAll=async function(store,pulls){if(pulls.length===0)return;let pullOne=async(rel,listed)=>{let item;try{item=await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.retrieve(listed.id,{memory_store_id:store.memoryStoreId,view:"full"})}catch(e){if(isStatus(e,404))return;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to fetch memory content",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},queue=pulls[Symbol.iterator](),worker=async()=>{for(let[rel,listed]of queue)await pullOne(rel,listed)};await Promise.all(Array.from({length:Math.min(FETCH_CONCURRENCY,pulls.length)},worker))},_SessionMemoryStores_uploadAll=async function(store,uploads,unsent,signal){let queue=uploads[Symbol.iterator](),worker=async()=>{for(let[rel,localSha,existing]of queue){if(signal?.aborted)return;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,existing);unsent.delete(rel),sha!==void 0&&store.baseline.set(rel,sha)}};await Promise.all(Array.from({length:Math.min(UPLOAD_CONCURRENCY,uploads.length)},worker))},_SessionMemoryStores_listMemories=async function*(memoryStoreId,view="basic"){let limit=view==="basic"?LIST_PAGE_SIZE:FULL_LIST_PAGE_SIZE;for await(let item of __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.list(memoryStoreId,{view,limit})){if(item.type!=="memory")continue;let rel=item.path.replace(/^\/+/,"");if(rel===MARKER_PATH){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server listed the reserved marker path; skipping",{path:item.path,memory_store_id:memoryStoreId});continue}yield[rel,item]}},_SessionMemoryStores_upload=async function _SessionMemoryStores_upload2(store,rel,localSha,existing){try{let data=await store.files.get(rel);if(data===null)return;let content=decodeUTF8(data),item=existing?await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.update(existing.id,{memory_store_id:store.memoryStoreId,content,precondition:{type:"content_sha256",content_sha256:existing.content_sha256}}):await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.create(store.memoryStoreId,{path:"/"+rel,content});return store.refusedShas.delete(rel),item.content_sha256}catch(e){if(existing&&isStatus(e,404))return await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload2).call(this,store,rel,localSha,void 0);let permanent=e instanceof FileStoreError||isStatus(e,400)||isStatus(e,413);existing&&isStatus(e,409)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:rel,memory_store_id:store.memoryStoreId}):permanent&&localSha!==void 0?(store.refusedShas.set(rel,localSha),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:rel,memory_store_id:store.memoryStoreId,rejection:String(e)})):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to upload memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}},_SessionMemoryStores_corroboratedDelete=async function(store,rel,remote,baseSha,deletes){if(deletes.mode==="disabled")return deletes.suppressed++,baseSha;let firstAbsent=store.pendingDeletes.get(rel);if(firstAbsent===void 0&&(firstAbsent=Date.now(),store.pendingDeletes.set(rel,firstAbsent)),!deletes.waiveWindow&&Date.now()-firstAbsent<DELETE_CORROBORATION_MS)return baseSha;let markerOk,stillAbsent;try{markerOk=await store.files.hashFile(MARKER_PATH)===markerSha(store.memoryStoreId),stillAbsent=await store.files.hashFile(rel)===null}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;markerOk=stillAbsent=!1}if(!markerOk)return baseSha;if(!stillAbsent)return store.pendingDeletes.delete(rel),baseSha;if(!deletes.takeSlot())return baseSha;if(deletes.mode==="log_only")return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("log-only: sync would delete this memory on the server",{path:rel,memory_store_id:store.memoryStoreId}),baseSha;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_deleteRemote).call(this,store,rel,remote,baseSha);return sha===void 0&&store.pendingDeletes.delete(rel),sha},_SessionMemoryStores_deleteRemote=async function(store,rel,remote,baseSha){try{await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.delete(remote.id,{memory_store_id:store.memoryStoreId,expected_content_sha256:baseSha})}catch(e){return isStatus(e,404)?void 0:(isStatus(e,409)||isStatus(e,412)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to delete memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),baseSha)}__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("propagated local deletion",{path:rel,memory_store_id:store.memoryStoreId})};function isErrno(e){return typeof e=="object"&&e!==null&&typeof e.code=="string"}async function settledOrAborted(p,signal){if(!signal){await p;return}let onAbort,aborted=new Promise(resolve2=>{onAbort=resolve2,signal.aborted&&resolve2()});signal.addEventListener("abort",onAbort,{once:!0});try{await Promise.race([p,aborted])}finally{signal.removeEventListener("abort",onAbort)}}var _BashSession_instances,_BashSession_proc,_BashSession_buf,_BashSession_truncated,_BashSession_closed,_BashSession_waiting,_BashSession_append,_LineRangeCollector_instances,_LineRangeCollector_filePath,_LineRangeCollector_startLine,_LineRangeCollector_endLine,_LineRangeCollector_start,_LineRangeCollector_end,_LineRangeCollector_limit,_LineRangeCollector_line,_LineRangeCollector_collected,_LineRangeCollector_collectedBytes,_LineRangeCollector_collect,_LineRangeCollector_overLimitError,BASH_OUTPUT_LIMIT=100*1024,BASH_DEFAULT_TIMEOUT_MS=12e4,DEFAULT_MAX_FILE_BYTES=256*1024,READ_STREAM_CHUNK_BYTES=64*1024,NEWLINE=Buffer.from(`
|
|
8
|
+
`),GREP_OUTPUT_LIMIT=100*1024,GREP_MAX_LINE_LENGTH=2e3,GLOB_RESULT_LIMIT=200,BashTimeoutError=class extends AnthropicError{constructor(timeoutMs){super(`bash command timed out after ${timeoutMs}ms`),this.name="BashTimeoutError",this.timeoutMs=timeoutMs}},ANSI_RE=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,fsGlob=fs4.glob;function resolveMaxBytes(configured){return configured===void 0?DEFAULT_MAX_FILE_BYTES:configured}function rejectUnrestrictedPaths(value){if(value!==void 0)throw new AnthropicError("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function betaAgentToolset20260401(ctx){return[betaBashTool(ctx),betaReadTool(ctx),betaWriteTool(ctx),betaEditTool(ctx),betaGlobTool(ctx),betaGrepTool(ctx)]}async function resolvePath(ctx,p){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),confineToRoot(ctx.workdir,p,{allowedRoots:ctx.allowedRoots??[]})}function readOnlyRootFor(ctx,target){return containingRoot(ctx.readOnlyRoots??[],target)}function scrubbedShellEnv(){let env={};for(let[key,value]of Object.entries(process.env))key.startsWith("ANTHROPIC_")||(env[key]=value);return env}var BashSession=class{constructor(dir,env=scrubbedShellEnv()){_BashSession_instances.add(this),_BashSession_proc.set(this,void 0),_BashSession_buf.set(this,""),_BashSession_truncated.set(this,!1),_BashSession_closed.set(this,!1),_BashSession_waiting.set(this,null),__classPrivateFieldSet(this,_BashSession_proc,cp.spawn("/bin/bash",["--noprofile","--norc"],{cwd:dir,env:{...env,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").once("close",()=>{__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve()})}get closed(){return __classPrivateFieldGet(this,_BashSession_closed,"f")}async exec(command,opts={}){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))throw new AnthropicError("bash session terminated");let timeoutMs=opts.timeoutMs??BASH_DEFAULT_TIMEOUT_MS,signal=opts.signal;signal?.throwIfAborted(),__classPrivateFieldSet(this,_BashSession_buf,"","f"),__classPrivateFieldSet(this,_BashSession_truncated,!1,"f");let sentinel=`__ANT_CMD_${crypto2.randomUUID()}_DONE__`,sentinelSplit=`${sentinel.slice(0,8)}''${sentinel.slice(8)}`,wrapped=`{ ${command}
|
|
9
|
+
} </dev/null 2>&1; printf '\\n${sentinelSplit}%d\\n' $?
|
|
10
|
+
`;if(__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.write(wrapped),__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel)<0){let{promise:sentinelSeen,resolve:resolve2}=promiseWithResolvers();__classPrivateFieldSet(this,_BashSession_waiting,{sentinel,resolve:resolve2},"f");let timer,onAbort;try{await Promise.race([sentinelSeen,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BashTimeoutError(timeoutMs)),timeoutMs)}),new Promise((_,reject)=>{signal&&(onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0}))})])}finally{timer&&clearTimeout(timer),onAbort&&signal&&signal.removeEventListener("abort",onAbort),__classPrivateFieldSet(this,_BashSession_waiting,null,"f")}}let idx=__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel);if(idx<0)throw new AnthropicError("bash session terminated");let m=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(idx+sentinel.length).match(/^(-?\d+)/),exitCode=m?parseInt(m[1],10):-1,out=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(0,idx).replace(ANSI_RE,"").replace(/\n+$/,"");return __classPrivateFieldGet(this,_BashSession_truncated,"f")&&(out=`[output truncated]
|
|
11
|
+
${out}`),{output:out,exitCode}}close(){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))return;__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.destroy();try{process.kill(-__classPrivateFieldGet(this,_BashSession_proc,"f").pid,"SIGKILL")}catch{__classPrivateFieldGet(this,_BashSession_proc,"f").kill("SIGKILL")}__classPrivateFieldGet(this,_BashSession_proc,"f").unref()}};_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 fs4.stat(abs);if(!st.isFile())throw new ToolError(`read: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit){if(!view_range?.length)throw new ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[startLine2,endLine2]=view_range;return await readRangeStreaming(abs,file_path,startLine2,endLine2,limit)}data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`read: ${fsErrorMessage(e,file_path)}`)}if(!view_range?.length)return data;let[startLine,endLine]=view_range,lines=data.split(`
|
|
12
|
+
`),start=Math.max(0,startLine-1),end=endLine>0?endLine:lines.length;return lines.slice(start,end).join(`
|
|
13
|
+
`)}})}async function readRangeStreaming(abs,filePath,startLine,endLine,limit){let lines=new LineRangeCollector(filePath,startLine,endLine,limit);if(lines.rangeIsEmpty())return"";let stream2=fssync.createReadStream(abs,{highWaterMark:READ_STREAM_CHUNK_BYTES});try{for await(let chunk of stream2)if(lines.collectFrom(chunk),lines.rangeIsCollected())break}finally{stream2.destroy()}return lines.text()}var LineRangeCollector=class{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 fs4.mkdir(path2.dirname(abs),{recursive:!0,mode:DIR_CREATE_MODE}),await atomicWriteFile(abs,content??"")}catch(e){throw new ToolError(`write: ${fsErrorMessage(e,file_path)}`)}return`wrote ${Buffer.byteLength(content??"")} bytes to ${file_path}`}})}function betaEditTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path,old_string,new_string,replace_all})=>{if(!file_path)throw new ToolError("edit: file_path is required");if(!old_string)throw new ToolError("edit: old_string is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`edit: ${file_path} is inside read-only directory ${ro}`);let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`edit: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit)throw new ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`edit: ${fsErrorMessage(e,file_path)}`)}let count=data.split(old_string).length-1;if(count===0)throw new ToolError(`edit: old_string not found in ${file_path}`);let updated;if(replace_all)updated=data.split(old_string).join(new_string);else{if(count>1)throw new ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`);updated=data.replace(old_string,()=>new_string)}try{await atomicWriteFile(abs,updated)}catch(e){throw new ToolError(`edit: write: ${fsErrorMessage(e,file_path)}`)}return`edited ${file_path} (${replace_all?count:1} replacement(s))`}})}function patternCanAscend(pattern){return pattern.split(/[\\/{},]/).includes("..")}function betaGlobTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern,path:searchPath})=>{if(!pattern)throw new ToolError("glob: pattern is required");if(path2.isAbsolute(pattern))throw new ToolError("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(patternCanAscend(pattern))throw new ToolError('glob: ".." is not permitted in the pattern');let root=searchPath?await resolvePath(ctx,searchPath):path2.resolve(ctx.workdir),realRoot=searchPath?root:await canonicalize(root),matches=[],remaining=WALK_MAX_ENTRIES;try{for await(let entry of fsGlob(pattern,{cwd:root,withFileTypes:!0,exclude:d=>d.name===".git"||d.name==="node_modules"})){if(remaining--<=0)break;if(!entry.isFile())continue;let full=path2.join(entry.parentPath,entry.name),real;try{real=await fs4.realpath(full)}catch{continue}if(!isWithin(realRoot,real))continue;let mtime=0;try{mtime=(await fs4.stat(full)).mtimeMs}catch{}matches.push({path:full,mtime})}}catch(e){throw new ToolError(`glob: ${e instanceof Error?e.message:String(e)}`)}return matches.length===0?"no matches":(matches.sort((a,b)=>b.mtime-a.mtime),matches.slice(0,GLOB_RESULT_LIMIT).map(m=>m.path).join(`
|
|
14
|
+
`))}})}function betaGrepTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern,path:p},context)=>{if(!pattern)throw new ToolError("grep: pattern is required");let searchPath=path2.resolve(ctx.workdir);p&&(searchPath=await resolvePath(ctx,p));let rg=await findRg();return rg?runRipgrep(rg,pattern,searchPath,context?.signal):runWalkGrep(pattern,searchPath,context?.signal)}})}function runRipgrep(rg,pattern,searchPath,signal){return new Promise((resolve2,reject)=>{let proc=cp.spawn(rg,["-n","--no-heading","-e",pattern,"--",searchPath],{...signal?{signal}:{}}),out="",errOut="",truncated=!1;proc.stdout.on("data",d=>{truncated||(out+=d,out.length>GREP_OUTPUT_LIMIT&&(truncated=!0,out=out.slice(0,GREP_OUTPUT_LIMIT),proc.kill("SIGKILL")))}),proc.stderr.on("data",d=>errOut+=d),proc.on("close",code=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));if(truncated)return resolve2(out+`
|
|
15
|
+
[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);if(code===0)return resolve2(out);if(code===1)return resolve2("no matches");reject(new ToolError(`grep: rg failed: ${errOut||`exit ${code}`}`))}),proc.on("error",e=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));reject(new ToolError(`grep: rg failed: ${e.message}`))})})}async function runWalkGrep(pattern,root,signal){let re;try{re=new RegExp(pattern)}catch(e){throw new ToolError(`grep: invalid regex: ${e instanceof Error?e.message:String(e)}`)}let hits=[],budget=GREP_OUTPUT_LIMIT,push=line=>(budget-=line.length+1,budget<0?(hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`),!1):(hits.push(line),!0));if((await fs4.stat(root).catch(()=>null))?.isFile()?await grepFile(root,re,push):await walk2(root,"",rel=>grepFile(path2.join(root,rel),re,push),signal),signal?.aborted)throw new ToolError("grep: aborted");return hits.length===0?"no matches":hits.join(`
|
|
16
|
+
`)}async function grepFile(file,re,push){let stream2=fssync.createReadStream(file,{encoding:"utf8"}),rl=readline.createInterface({input:stream2,crlfDelay:1/0}),i=0;try{for await(let line of rl)if(i++,!(line.length>GREP_MAX_LINE_LENGTH)&&re.test(line)&&!push(`${file}:${i}:${line}`))return!1}catch{}finally{stream2.destroy()}return!0}var WALK_MAX_DEPTH=40,WALK_MAX_ENTRIES=5e4;async function walk2(root,rel,fn,signal){let remaining=WALK_MAX_ENTRIES;async function inner(rel2,depth){if(depth>WALK_MAX_DEPTH)return!0;if(signal?.aborted)return!1;let entries;try{entries=await fs4.readdir(path2.join(root,rel2),{withFileTypes:!0})}catch{return!0}for(let e of entries){if(e.name===".git"||e.name==="node_modules")continue;if(remaining--<=0||signal?.aborted)return!1;let childRel=rel2?path2.join(rel2,e.name):e.name;if(e.isDirectory()){if(!await inner(childRel,depth+1))return!1}else if(e.isFile()&&await fn(childRel)===!1)return!1}return!0}await inner(rel,0)}async function findRg(){let dirs=(process.env.PATH??"").split(path2.delimiter);for(let d of dirs){let candidate=path2.join(d,"rg");try{return await fs4.access(candidate,fssync.constants.X_OK),candidate}catch{}}return null}export{BashSession,BashTimeoutError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MARKER_PATH,MEMORY_FLUSH_TIMEOUT_MS,MIN_MEMORY_SYNC_INTERVAL_MS,SessionMemoryError,SessionMemoryStores,betaAgentToolset20260401,betaBashTool,betaEditTool,betaGlobTool,betaGrepTool,betaReadTool,betaWriteTool,extractSkillArchive,resolvePath,setupSkills};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{registerSessionResourceCleanup,uuidv7}from"./chunk-USJZMAIR.js";import{splitDeferredTools}from"./chunk-GMWCTUPB.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-NV6PWB3O.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-AXIIZGTV.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import"./chunk-TRDNDS6A.js";import{clampThinkingLevel}from"./chunk-GTBU4EAF.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";function combineAbortSignals(signals){let activeSignals=signals.filter(signal=>signal!==void 0);if(activeSignals.length===0)return{cleanup:()=>{}};if(activeSignals.length===1)return{signal:activeSignals[0],cleanup:()=>{}};let controller=new AbortController,listeners=[],abort=signal=>{controller.signal.aborted||controller.abort(signal.reason)};for(let signal of activeSignals){if(signal.aborted){abort(signal);break}let listener=()=>abort(signal);signal.addEventListener("abort",listener,{once:!0}),listeners.push({signal,listener})}return{signal:controller.signal,cleanup:()=>{for(let{signal,listener}of listeners)signal.removeEventListener("abort",listener)}}}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env){let noProxy=getProxyEnv("no_proxy",env).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",JWT_CLAIM_PATH="https://api.openai.com/auth",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE=1009,WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}function getRetryAfterDelayMs(headers){let retryAfterMs=headers.get("retry-after-ms");if(retryAfterMs!==null){let millis=Number(retryAfterMs);if(Number.isFinite(millis))return Math.max(0,millis)}let retryAfter=headers.get("retry-after");if(!retryAfter)return;let seconds=Number(retryAfter);if(Number.isFinite(seconds))return Math.max(0,seconds*1e3);let date=Date.parse(retryAfter);if(!Number.isNaN(date))return Math.max(0,date-Date.now())}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return new Uint8Array(compressed.buffer,compressed.byteOffset,compressed.byteLength)}catch{return null}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,context,options,codexSessionId,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart||(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,fallbackTransport:websocketStarted?void 0:"sse",eventsEmitted:websocketStarted,phase:websocketStarted?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error),websocketStarted))throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody??bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=getRetryAfterDelayMs(response.headers),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse);throw new Error(info.friendlyMessage||info.message)}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function buildRequestBody(model,context,options,cacheSessionId,grammarToolInputProperties=createGrammarToolInputProperties(context.tools,model.compat?.supportsOpenAIGrammarTools??!1)){let supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,deferredToolsMode=model.compat?.supportsAdditionalTools?"additional-tools":model.compat?.supportsToolSearch?"tool-search":void 0,toolPlacement=splitDeferredTools(context,deferredToolsMode!==void 0),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties,deferredTools:toolPlacement.deferred,deferredToolsMode,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),body={model:model.id,store:!1,stream:!0,instructions:context.systemPrompt||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:cacheSessionId,tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};if(options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),toolPlacement.immediate.length>0&&(body.tools=convertResponsesTools(toolPlacement.immediate,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools})),options?.reasoningEffort!==void 0){let effort=options.reasoningEffort==="none"?model.thinkingLevelMap?.off===void 0?"none":model.thinkingLevelMap.off:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;effort!==null&&(body.reasoning={effort,summary:options.reasoningSummary??"auto"})}else model.reasoning&&model.thinkingLevelMap?.off!==null&&(body.reasoning={effort:model.thinkingLevelMap?.off??"none"});return body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{code;payload;constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{payload;constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function extractCodexEventError(event){let nested=event.error&&typeof event.error=="object"?event.error:void 0;return{code:typeof event.code=="string"?event.code:typeof nested?.code=="string"?nested.code:void 0,message:typeof event.message=="string"?event.message:typeof nested?.message=="string"?nested.message:void 0}}async function*mapCodexEvents(events,output){for await(let event of events){let type=typeof event.type=="string"?event.type:void 0;if(type){if(type==="error"){let{code,message}=extractCodexEventError(event);throw new CodexApiError(`Codex error: ${message||code||JSON.stringify(event)}`,{code,payload:event})}if(type==="response.failed"){let response=event.response,code=response?.error?.code,message=response?.error?.message;throw new CodexApiError(message||"Codex response failed",{code,payload:event})}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield event}}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
|
|
3
|
+
|
|
4
|
+
`);let idx=buffer.indexOf(`
|
|
5
|
+
|
|
6
|
+
`);for(;idx!==-1;){let chunk=buffer.slice(0,idx);buffer=buffer.slice(idx+2);let dataLines=chunk.split(`
|
|
7
|
+
`).filter(l=>l.startsWith("data:")).map(l=>l.slice(5).trim());if(dataLines.length>0){let data=dataLines.join(`
|
|
8
|
+
`).trim();if(data&&data!=="[DONE]")try{yield JSON.parse(data)}catch(cause){throw new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`,{cause,payload:data})}}idx=buffer.indexOf(`
|
|
9
|
+
|
|
10
|
+
`)}if(done)break}}finally{signal?.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}var OPENAI_BETA_RESPONSES_WEBSOCKETS="responses_websockets=2026-02-06",SESSION_WEBSOCKET_CACHE_TTL_MS=300*1e3,SESSION_WEBSOCKET_MAX_AGE_MS=3300*1e3,websocketSessionCache=new Map,websocketDebugStats=new Map,websocketSseFallbackSessions=new Set;function getOrCreateWebSocketDebugStats(sessionId){let stats=websocketDebugStats.get(sessionId);return stats||(stats={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},websocketDebugStats.set(sessionId,stats)),stats}function getOpenAICodexWebSocketDebugStats(sessionId){let stats=websocketDebugStats.get(sessionId);return stats?{...stats}:void 0}function resetOpenAICodexWebSocketDebugStats(sessionId){if(sessionId){websocketDebugStats.delete(sessionId),websocketSseFallbackSessions.delete(sessionId);return}websocketDebugStats.clear(),websocketSseFallbackSessions.clear()}function closeOpenAICodexWebSocketSessions(sessionId){let closeEntry=entry=>{entry.idleTimer&&clearTimeout(entry.idleTimer),closeWebSocketSilently(entry.socket,1e3,"debug_close")};if(sessionId){for(let entry of websocketSessionCache.get(sessionId)?.values()??[])closeEntry(entry);websocketSessionCache.delete(sessionId);return}for(let accountEntries of websocketSessionCache.values())for(let entry of accountEntries.values())closeEntry(entry);websocketSessionCache.clear()}registerSessionResourceCleanup(closeOpenAICodexWebSocketSessions);function isWebSocketSseFallbackActive(sessionId){return sessionId?websocketSseFallbackSessions.has(sessionId):!1}function recordWebSocketSseFallback(sessionId){if(!sessionId)return;let stats=getOrCreateWebSocketDebugStats(sessionId);stats.sseFallbacks++,stats.websocketFallbackActive=isWebSocketSseFallbackActive(sessionId)}function recordWebSocketFailure(sessionId,error){if(!sessionId)return;websocketSseFallbackSessions.add(sessionId);let stats=getOrCreateWebSocketDebugStats(sessionId);stats.websocketFailures++,stats.lastWebSocketError=formatThrownValue(error),stats.websocketFallbackActive=!0}var _cachedWebsocket=null;async function getWebSocketConstructor(env){if(!env&&_cachedWebsocket)return _cachedWebsocket;if(typeof process<"u"&&process.versions?.bun){let WebSocketWithProxy=class extends WebSocket{constructor(url,options){let _opts={};Array.isArray(options)||typeof options=="string"?_opts={protocols:options}:_opts={...options};let proxyUrl=resolveHttpProxyUrlForTarget(url.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),env);super(url,{..._opts,...proxyUrl?{proxy:proxyUrl.toString()}:{}})}};return env||(_cachedWebsocket=WebSocketWithProxy),WebSocketWithProxy}let ctor=globalThis.WebSocket;return typeof ctor!="function"?null:ctor}var WebSocketCloseError=class extends Error{code;reason;wasClean;constructor(message,options){super(message),this.name="WebSocketCloseError",this.code=options?.code,this.reason=options?.reason,this.wasClean=options?.wasClean}};function getWebSocketReadyState(socket){let readyState=socket.readyState;return typeof readyState=="number"?readyState:void 0}function isWebSocketReusable(socket){let readyState=getWebSocketReadyState(socket);return readyState===void 0||readyState===1}function isWebSocketSessionExpired(entry){return Date.now()-entry.createdAt>=SESSION_WEBSOCKET_MAX_AGE_MS}function closeWebSocketSilently(socket,code=1e3,reason="done"){try{socket.close(code,reason)}catch{}}function scheduleSessionWebSocketExpiry(sessionId,accountId,entry){entry.idleTimer&&clearTimeout(entry.idleTimer),entry.idleTimer=setTimeout(()=>{if(entry.busy)return;closeWebSocketSilently(entry.socket,1e3,"idle_timeout");let accountEntries=websocketSessionCache.get(sessionId);accountEntries?.get(accountId)===entry&&accountEntries.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId)},SESSION_WEBSOCKET_CACHE_TTL_MS)}async function connectWebSocket(url,headers,signal,connectTimeoutMs=DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS,env){let WebSocketCtor=await getWebSocketConstructor(env);if(!WebSocketCtor)throw new Error("WebSocket transport is not available in this runtime");let wsHeaders=headersToRecord(headers);return delete wsHeaders["OpenAI-Beta"],new Promise((resolve,reject)=>{let settled=!1,timeout,socket;try{socket=new WebSocketCtor(url,{headers:wsHeaders})}catch(error){reject(error instanceof Error?error:new Error(String(error)));return}let cleanup=()=>{timeout&&(clearTimeout(timeout),timeout=void 0),socket.removeEventListener("open",onOpen),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)},fail=(error,closeReason)=>{settled||(settled=!0,cleanup(),closeReason&&closeWebSocketSilently(socket,1e3,closeReason),reject(error))},onOpen=()=>{settled||(settled=!0,cleanup(),resolve(socket))},onError=event=>{fail(extractWebSocketError(event))},onClose=event=>{fail(extractWebSocketCloseError(event))},onAbort=()=>{fail(new Error("Request was aborted"),"aborted")};socket.addEventListener("open",onOpen),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort),connectTimeoutMs>0&&(timeout=setTimeout(()=>{fail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`),"connect_timeout")},connectTimeoutMs)),signal?.aborted&&onAbort()})}async function acquireWebSocket(url,headers,sessionId,accountId,signal,connectTimeoutMs,env){if(!sessionId){let socket2=await connectWebSocket(url,headers,signal,connectTimeoutMs,env);return{socket:socket2,reused:!1,release:()=>closeWebSocketSilently(socket2)}}let accountEntries=websocketSessionCache.get(sessionId),cached=accountEntries?.get(accountId);if(cached){if(cached.idleTimer&&(clearTimeout(cached.idleTimer),cached.idleTimer=void 0),!cached.busy&&isWebSocketSessionExpired(cached))closeWebSocketSilently(cached.socket,1e3,"connection_age_limit"),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId);else if(!cached.busy&&isWebSocketReusable(cached.socket))return cached.busy=!0,{socket:cached.socket,entry:cached,reused:!0,release:({keep}={})=>{if(!keep||!isWebSocketReusable(cached.socket)){closeWebSocketSilently(cached.socket);let currentEntries=websocketSessionCache.get(sessionId);currentEntries?.get(accountId)===cached&¤tEntries.delete(accountId),currentEntries?.size===0&&websocketSessionCache.delete(sessionId);return}cached.busy=!1,scheduleSessionWebSocketExpiry(sessionId,accountId,cached)}};if(cached.busy){let socket2=await connectWebSocket(url,headers,signal,connectTimeoutMs,env);return{socket:socket2,reused:!1,release:()=>{closeWebSocketSilently(socket2)}}}isWebSocketReusable(cached.socket)||(closeWebSocketSilently(cached.socket),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId))}let socket=await connectWebSocket(url,headers,signal,connectTimeoutMs,env),entry={socket,busy:!0,createdAt:Date.now()};return accountEntries=websocketSessionCache.get(sessionId),accountEntries||(accountEntries=new Map,websocketSessionCache.set(sessionId,accountEntries)),accountEntries.set(accountId,entry),{socket,entry,reused:!1,release:({keep}={})=>{if(!keep||!isWebSocketReusable(entry.socket)){closeWebSocketSilently(entry.socket),entry.idleTimer&&clearTimeout(entry.idleTimer);let currentEntries=websocketSessionCache.get(sessionId);currentEntries?.get(accountId)===entry&¤tEntries.delete(accountId),currentEntries?.size===0&&websocketSessionCache.delete(sessionId);return}entry.busy=!1,scheduleSessionWebSocketExpiry(sessionId,accountId,entry)}}}function extractWebSocketError(event){if(event&&typeof event=="object"){let message="message"in event?event.message:void 0;if(typeof message=="string"&&message.length>0)return new Error(message);let nestedError="error"in event?event.error:void 0;if(nestedError instanceof Error&&nestedError.message.length>0)return nestedError;if(nestedError&&typeof nestedError=="object"&&"message"in nestedError){let nestedMessage=nestedError.message;if(typeof nestedMessage=="string"&&nestedMessage.length>0)return new Error(nestedMessage)}}return new Error("WebSocket error")}function extractWebSocketCloseError(event){if(event&&typeof event=="object"){let code="code"in event?event.code:void 0,reason="reason"in event?event.reason:void 0,wasClean="wasClean"in event?event.wasClean:void 0,codeText=typeof code=="number"?` ${code}`:"",reasonText=typeof reason=="string"&&reason.length>0?` ${reason}`:"";return!reasonText&&code===WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE&&(reasonText=" message too big"),new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(),{code:typeof code=="number"?code:void 0,reason:typeof reason=="string"&&reason.length>0?reason:void 0,wasClean:typeof wasClean=="boolean"?wasClean:void 0})}return new Error("WebSocket closed")}async function decodeWebSocketData(data){if(typeof data=="string")return data;if(data instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(data));if(ArrayBuffer.isView(data)){let view=data;return new TextDecoder().decode(new Uint8Array(view.buffer,view.byteOffset,view.byteLength))}if(data&&typeof data=="object"&&"arrayBuffer"in data){let arrayBuffer=await data.arrayBuffer();return new TextDecoder().decode(new Uint8Array(arrayBuffer))}return null}async function*parseWebSocket(socket,signal,idleTimeoutMs){let queue=[],pending=null,done=!1,failed=null,sawCompletion=!1,wake=()=>{if(!pending)return;let resolve=pending;pending=null,resolve()},onMessage=event=>{(async()=>{let text=null;try{if(!event||typeof event!="object"||!("data"in event)||(text=await decodeWebSocketData(event.data),!text))return;let parsed=JSON.parse(text),type=typeof parsed.type=="string"?parsed.type:"";(type==="response.completed"||type==="response.done"||type==="response.incomplete")&&(sawCompletion=!0,done=!0),queue.push(parsed),wake()}catch(cause){failed=new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`,{cause,payload:text}),done=!0,wake()}})()},onError=event=>{failed=extractWebSocketError(event),done=!0,wake()},onClose=event=>{if(sawCompletion){done=!0,wake();return}failed||(failed=extractWebSocketCloseError(event)),done=!0,wake()},onAbort=()=>{failed=new Error("Request was aborted"),done=!0,wake()};socket.addEventListener("message",onMessage),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort);try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");if(queue.length>0){yield queue.shift();continue}if(done)break;let timeout;await new Promise((resolve,reject)=>{pending=resolve,idleTimeoutMs!==void 0&&idleTimeoutMs>0&&(timeout=setTimeout(()=>{let error=new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);failed=error,done=!0,pending=null,closeWebSocketSilently(socket,1e3,"idle_timeout"),reject(error)},idleTimeoutMs))}).finally(()=>{timeout&&clearTimeout(timeout)})}if(failed)throw failed;if(!sawCompletion)throw new Error("WebSocket stream closed before response.completed")}finally{socket.removeEventListener("message",onMessage),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)}}function requestBodyWithoutInput(body){let{input:_input,previous_response_id:_previousResponseId,...rest}=body;return rest}function responseInputsEqual(a,b){return JSON.stringify(a??[])===JSON.stringify(b??[])}function requestBodiesMatchExceptInput(a,b){return JSON.stringify(requestBodyWithoutInput(a))===JSON.stringify(requestBodyWithoutInput(b))}function getCachedWebSocketInputDelta(body,continuation){if(!requestBodiesMatchExceptInput(body,continuation.lastRequestBody))return;let currentInput=body.input??[],baseline=[...continuation.lastRequestBody.input??[],...continuation.lastResponseItems];if(currentInput.length<baseline.length)return;let prefix=currentInput.slice(0,baseline.length);if(responseInputsEqual(prefix,baseline))return currentInput.slice(baseline.length)}function buildCachedWebSocketRequestBody(entry,body){let continuation=entry.continuation;if(!continuation)return body;let delta=getCachedWebSocketInputDelta(body,continuation);return!delta||!continuation.lastResponseId?(entry.continuation=void 0,body):{...body,previous_response_id:continuation.lastResponseId,input:delta}}async function*startWebSocketOutputOnFirstEvent(events,onStart){let started=!1;for await(let event of events)started||(started=!0,onStart()),yield event}async function processWebSocketStream(url,body,headers,output,stream2,model,onStart,idleTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options){let{socket,entry,reused,release}=await acquireWebSocket(url,headers,cacheSessionId,accountId,options?.signal,websocketConnectTimeoutMs,options?.env),keepConnection=!0,useCachedContext=options?.transport==="websocket-cached"||options?.transport==="auto",fullBody=body,requestBody=useCachedContext&&entry?buildCachedWebSocketRequestBody(entry,fullBody):fullBody,stats=cacheSessionId?getOrCreateWebSocketDebugStats(cacheSessionId):void 0;stats&&(stats.requests++,reused?stats.connectionsReused++:stats.connectionsCreated++,useCachedContext&&stats.cachedContextRequests++,requestBody.store===!0&&stats.storeTrueRequests++,stats.lastInputItems=requestBody.input?.length??0,requestBody.previous_response_id?(stats.deltaRequests++,stats.lastDeltaInputItems=requestBody.input?.length??0,stats.lastPreviousResponseId=requestBody.previous_response_id):(stats.fullContextRequests++,stats.lastDeltaInputItems=void 0,stats.lastPreviousResponseId=void 0));try{if(socket.send(JSON.stringify({type:"response.create",...requestBody})),await processResponsesStream(startWebSocketOutputOnFirstEvent(mapCodexEvents(parseWebSocket(socket,options?.signal,idleTimeoutMs),output),onStart),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)}),options?.signal?.aborted)keepConnection=!1;else if(useCachedContext&&entry&&output.responseId){let responseItems=convertResponsesMessages(model,{messages:[output]},CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties}).filter(item=>item.type!=="function_call_output"&&item.type!=="custom_tool_call_output");entry.continuation={lastRequestBody:fullBody,lastResponseId:output.responseId,lastResponseItems:responseItems}}}catch(error){throw entry&&(entry.continuation=void 0),keepConnection=!1,error}finally{release({keep:keepConnection})}}async function parseErrorResponse(response){let raw=await response.text(),message=raw||response.statusText||"Request failed",friendlyMessage;try{let err=JSON.parse(raw)?.error;if(err){let code=err.code||err.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code)||response.status===429){let plan=err.plan_type?` (${err.plan_type.toLowerCase()} plan)`:"",mins=err.resets_at?Math.max(0,Math.round((err.resets_at*1e3-Date.now())/6e4)):void 0,when=mins!==void 0?` Try again in ~${mins} min.`:"";friendlyMessage=`You have hit your ChatGPT usage limit${plan}.${when}`.trim()}message=err.message||friendlyMessage||message}}catch{}return{message,friendlyMessage}}function extractAccountId(token){try{let parts=token.split(".");if(parts.length!==3)throw new Error("Invalid token");let accountId=JSON.parse(atob(parts[1]))?.[JWT_CLAIM_PATH]?.chatgpt_account_id;if(!accountId)throw new Error("No account ID in token");return accountId}catch{throw new Error("Failed to extract accountId from token")}}function buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token){let headers=new Headers(initHeaders);for(let[key,value]of Object.entries(additionalHeaders||{}))value===null?headers.delete(key):headers.set(key,value);return headers.set("Authorization",`Bearer ${token}`),headers.set("chatgpt-account-id",accountId),headers.set("originator","pi"),headers.set("User-Agent",getPiUserAgent()),headers}function buildSSEHeaders(initHeaders,additionalHeaders,accountId,token,sessionId){let headers=buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token);return headers.set("OpenAI-Beta","responses=experimental"),headers.set("accept","text/event-stream"),headers.set("content-type","application/json"),sessionId&&(headers.set("session-id",sessionId),headers.set("x-client-request-id",sessionId)),headers}function buildWebSocketHeaders(initHeaders,additionalHeaders,accountId,token,requestId){let headers=buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token);return headers.delete("accept"),headers.delete("content-type"),headers.delete("OpenAI-Beta"),headers.delete("openai-beta"),headers.set("OpenAI-Beta",OPENAI_BETA_RESPONSES_WEBSOCKETS),headers.set("x-client-request-id",requestId),headers.set("session-id",requestId),headers}export{closeOpenAICodexWebSocketSessions,getOpenAICodexWebSocketDebugStats,resetOpenAICodexWebSocketDebugStats,stream,streamSimple};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#fff" fill-rule="evenodd" d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"/><path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
|
|
3
|
+
<html lang="en">
|
|
4
|
+
<head>
|
|
5
|
+
<meta charset="utf-8" />
|
|
6
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
7
|
+
<title>${title}</title>
|
|
8
|
+
<style>
|
|
9
|
+
:root {
|
|
10
|
+
--text: #fafafa;
|
|
11
|
+
--text-dim: #a1a1aa;
|
|
12
|
+
--page-bg: #09090b;
|
|
13
|
+
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
14
|
+
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
15
|
+
}
|
|
16
|
+
* { box-sizing: border-box; }
|
|
17
|
+
html { color-scheme: dark; }
|
|
18
|
+
body {
|
|
19
|
+
margin: 0;
|
|
20
|
+
min-height: 100vh;
|
|
21
|
+
display: flex;
|
|
22
|
+
align-items: center;
|
|
23
|
+
justify-content: center;
|
|
24
|
+
padding: 24px;
|
|
25
|
+
background: var(--page-bg);
|
|
26
|
+
color: var(--text);
|
|
27
|
+
font-family: var(--font-sans);
|
|
28
|
+
text-align: center;
|
|
29
|
+
}
|
|
30
|
+
main {
|
|
31
|
+
width: 100%;
|
|
32
|
+
max-width: 560px;
|
|
33
|
+
display: flex;
|
|
34
|
+
flex-direction: column;
|
|
35
|
+
align-items: center;
|
|
36
|
+
justify-content: center;
|
|
37
|
+
}
|
|
38
|
+
.logo {
|
|
39
|
+
width: 72px;
|
|
40
|
+
height: 72px;
|
|
41
|
+
display: block;
|
|
42
|
+
margin-bottom: 24px;
|
|
43
|
+
}
|
|
44
|
+
h1 {
|
|
45
|
+
margin: 0 0 10px;
|
|
46
|
+
font-size: 28px;
|
|
47
|
+
line-height: 1.15;
|
|
48
|
+
font-weight: 650;
|
|
49
|
+
color: var(--text);
|
|
50
|
+
}
|
|
51
|
+
p {
|
|
52
|
+
margin: 0;
|
|
53
|
+
line-height: 1.7;
|
|
54
|
+
color: var(--text-dim);
|
|
55
|
+
font-size: 15px;
|
|
56
|
+
}
|
|
57
|
+
.details {
|
|
58
|
+
margin-top: 16px;
|
|
59
|
+
font-family: var(--font-mono);
|
|
60
|
+
font-size: 13px;
|
|
61
|
+
color: var(--text-dim);
|
|
62
|
+
white-space: pre-wrap;
|
|
63
|
+
word-break: break-word;
|
|
64
|
+
}
|
|
65
|
+
</style>
|
|
66
|
+
</head>
|
|
67
|
+
<body>
|
|
68
|
+
<main>
|
|
69
|
+
<div class="logo">${LOGO_SVG}</div>
|
|
70
|
+
<h1>${heading}</h1>
|
|
71
|
+
<p>${message}</p>
|
|
72
|
+
${details?`<div class="details">${details}</div>`:""}
|
|
73
|
+
</main>
|
|
74
|
+
</body>
|
|
75
|
+
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var _randomBytes=null,_http=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(import("node:crypto").then(m=>{_randomBytes=m.randomBytes}),import("node:http").then(m=>{_http=m}));var CLIENT_ID="app_EMoamEEZ73f0CkXaXp7hrann",AUTH_BASE_URL="https://auth.openai.com",AUTHORIZE_URL=`${AUTH_BASE_URL}/oauth/authorize`,TOKEN_URL=`${AUTH_BASE_URL}/oauth/token`,REDIRECT_URI="http://localhost:1455/auth/callback",DEVICE_USER_CODE_URL=`${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`,DEVICE_TOKEN_URL=`${AUTH_BASE_URL}/api/accounts/deviceauth/token`,DEVICE_VERIFICATION_URI=`${AUTH_BASE_URL}/codex/device`,DEVICE_REDIRECT_URI=`${AUTH_BASE_URL}/deviceauth/callback`,DEVICE_CODE_TIMEOUT_SECONDS=900,OPENAI_CODEX_BROWSER_LOGIN_METHOD="browser",OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD="device_code",SCOPE="openid profile email offline_access",JWT_CLAIM_PATH="https://api.openai.com/auth";function getCallbackHost(){return getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1"}function createState(){if(!_randomBytes)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");return _randomBytes(16).toString("hex")}function parseAuthorizationInput(input){let value=input.trim();if(!value)return{};try{let url=new URL(value);return{code:url.searchParams.get("code")??void 0,state:url.searchParams.get("state")??void 0}}catch{}if(value.includes("#")){let[code,state]=value.split("#",2);return{code,state}}if(value.includes("code=")){let params=new URLSearchParams(value);return{code:params.get("code")??void 0,state:params.get("state")??void 0}}return{code:value}}function decodeJwt(token){try{let parts=token.split(".");if(parts.length!==3)return null;let payload=parts[1]??"",decoded=atob(payload);return JSON.parse(decoded)}catch{return null}}async function fetchWithLoginCancellation(input,init){try{return await fetch(input,init)}catch(error){throw init.signal?.aborted?new Error("Login cancelled"):error}}async function readTokenResponse(response,operation){if(!response.ok){let text=await response.text().catch(()=>"");throw new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text||response.statusText}`)}let json=await response.json();if(!json?.access_token||!json.refresh_token||typeof json.expires_in!="number")throw new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);return{access:json.access_token,refresh:json.refresh_token,expires:Date.now()+json.expires_in*1e3}}async function exchangeAuthorizationCode(code,verifier,redirectUri,signal){let response=await fetchWithLoginCancellation(TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:CLIENT_ID,code,code_verifier:verifier,redirect_uri:redirectUri}),signal});return readTokenResponse(response,"exchange")}async function refreshAccessToken(refreshToken,signal){let response;try{response=await fetch(TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken,client_id:CLIENT_ID}),signal})}catch(error){throw new Error(`OpenAI Codex token refresh error: ${error instanceof Error?error.message:String(error)}`)}return readTokenResponse(response,"refresh")}async function startOpenAICodexDeviceAuth(signal){let response=await fetchWithLoginCancellation(DEVICE_USER_CODE_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:CLIENT_ID}),signal});if(!response.ok){if(response.status===404)throw new Error("OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.");let responseBody=await response.text().catch(()=>"");throw new Error(`OpenAI Codex device code request failed with status ${response.status}${responseBody?`: ${responseBody}`:""}`)}let json=await response.json(),intervalSeconds=typeof json?.interval=="string"?Number(json.interval.trim()):json?.interval;if(!json?.device_auth_id||!json.user_code||typeof intervalSeconds!="number"||!Number.isFinite(intervalSeconds)||intervalSeconds<0)throw new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);return{deviceAuthId:json.device_auth_id,userCode:json.user_code,intervalSeconds}}async function pollOpenAICodexDeviceAuth(device,signal){return pollOAuthDeviceCodeFlow({intervalSeconds:device.intervalSeconds,expiresInSeconds:DEVICE_CODE_TIMEOUT_SECONDS,signal,poll:async()=>{let response=await fetchWithLoginCancellation(DEVICE_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:device.deviceAuthId,user_code:device.userCode}),signal});if(response.ok){let json=await response.json();return!json?.authorization_code||!json.code_verifier?{status:"failed",message:`Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`}:{status:"complete",value:{authorizationCode:json.authorization_code,codeVerifier:json.code_verifier}}}if(response.status===403||response.status===404)return{status:"pending"};let responseBody=await response.text().catch(()=>""),errorCode;try{let error=JSON.parse(responseBody)?.error;errorCode=typeof error=="object"?error?.code:error}catch{}return errorCode==="deviceauth_authorization_pending"?{status:"pending"}:errorCode==="slow_down"?{status:"slow_down"}:{status:"failed",message:`OpenAI Codex device auth failed with status ${response.status}${responseBody?`: ${responseBody}`:""}`}}})}async function createAuthorizationFlow(originator="pi"){let{verifier,challenge}=await generatePKCE(),state=createState(),url=new URL(AUTHORIZE_URL);return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",CLIENT_ID),url.searchParams.set("redirect_uri",REDIRECT_URI),url.searchParams.set("scope",SCOPE),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("state",state),url.searchParams.set("id_token_add_organizations","true"),url.searchParams.set("codex_cli_simplified_flow","true"),url.searchParams.set("originator",originator),{verifier,state,url:url.toString()}}function startLocalOAuthServer(state){if(!_http)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");let settleWait,waitForCodePromise=new Promise(resolve=>{let settled=!1;settleWait=value=>{settled||(settled=!0,resolve(value))}}),server=_http.createServer((req,res)=>{try{let url=new URL(req.url||"","http://localhost");if(url.pathname!=="/auth/callback"){res.statusCode=404,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("Callback route not found."));return}if(url.searchParams.get("state")!==state){res.statusCode=400,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("State mismatch."));return}let code=url.searchParams.get("code");if(!code){res.statusCode=400,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("Missing authorization code."));return}res.statusCode=200,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthSuccessHtml("OpenAI authentication completed. You can close this window.")),settleWait?.({code})}catch{res.statusCode=500,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("Internal error while processing OAuth callback."))}});return new Promise(resolve=>{server.listen(1455,getCallbackHost(),()=>{resolve({close:()=>server.close(),cancelWait:()=>{settleWait?.(null)},waitForCode:()=>waitForCodePromise})}).on("error",_err=>{settleWait?.(null),resolve({close:()=>{try{server.close()}catch{}},cancelWait:()=>{},waitForCode:async()=>null})})})}function getAccountId(accessToken){let accountId=decodeJwt(accessToken)?.[JWT_CLAIM_PATH]?.chatgpt_account_id;return typeof accountId=="string"&&accountId.length>0?accountId:null}function credentialsFromToken(token){let accountId=getAccountId(token.access);if(!accountId)throw new Error("Failed to extract accountId from token");return{type:"oauth",access:token.access,refresh:token.refresh,expires:token.expires,accountId}}async function exchangeAuthorizationCodeForCredentials(code,verifier,redirectUri,signal){return credentialsFromToken(await exchangeAuthorizationCode(code,verifier,redirectUri,signal))}async function loginOpenAICodexDeviceCode(interaction){let device=await startOpenAICodexDeviceAuth(interaction.signal);interaction.notify({type:"device_code",userCode:device.userCode,verificationUri:DEVICE_VERIFICATION_URI,intervalSeconds:device.intervalSeconds,expiresInSeconds:DEVICE_CODE_TIMEOUT_SECONDS});let code=await pollOpenAICodexDeviceAuth(device,interaction.signal);return exchangeAuthorizationCodeForCredentials(code.authorizationCode,code.codeVerifier,DEVICE_REDIRECT_URI,interaction.signal)}async function loginOpenAICodex(interaction){let{verifier,state,url}=await createAuthorizationFlow(),server=await startLocalOAuthServer(state),manualAbort=new AbortController,onAbort=()=>server.cancelWait();interaction.signal.addEventListener("abort",onAbort,{once:!0}),interaction.signal.aborted&&onAbort();let code,manualCode,manualError;interaction.notify({type:"auth_url",url,instructions:"A browser window should open. Complete login to finish."});try{let manualPromise=interaction.prompt({type:"manual_code",message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:REDIRECT_URI,signal:manualAbort.signal}).then(input=>{manualCode=input,server.cancelWait()}).catch(error=>{manualError=error instanceof Error?error:new Error(String(error)),server.cancelWait()}),result=await server.waitForCode();if(manualError)throw manualError;if(result?.code)code=result.code;else if(manualCode){let parsed=parseAuthorizationInput(manualCode);if(parsed.state&&parsed.state!==state)throw new Error("State mismatch");code=parsed.code}if(!code){if(await manualPromise,manualError)throw manualError;if(manualCode){let parsed=parseAuthorizationInput(manualCode);if(parsed.state&&parsed.state!==state)throw new Error("State mismatch");code=parsed.code}}if(!code)throw new Error("Missing authorization code");return exchangeAuthorizationCodeForCredentials(code,verifier,REDIRECT_URI,interaction.signal)}finally{interaction.signal.removeEventListener("abort",onAbort),manualAbort.abort(),server.close()}}async function refreshOpenAICodexToken(refreshToken,signal){return credentialsFromToken(await refreshAccessToken(refreshToken,signal))}var openaiCodexOAuth={name:"OpenAI (ChatGPT Plus/Pro)",isSubscription:!0,async login(interaction){let method=await interaction.prompt({type:"select",message:"Select OpenAI Codex login method:",options:[{id:OPENAI_CODEX_BROWSER_LOGIN_METHOD,label:"Browser login (default)"},{id:OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD,label:"Device code login (headless)"}]});if(method===OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD)return loginOpenAICodexDeviceCode(interaction);if(method!==OPENAI_CODEX_BROWSER_LOGIN_METHOD)throw new Error(`Unknown OpenAI Codex login method: ${method}`);return loginOpenAICodex(interaction)},refresh:(credential,signal)=>refreshOpenAICodexToken(credential.refresh,signal),async toAuth(credential){return{apiKey:credential.access}}};export{openaiCodexOAuth};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{OpenAI}from"./chunk-NUHFSC37.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,getPiUserAgent,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,thinkingBudgetForLevel,transformMessages}from"./chunk-AXIIZGTV.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,clampThinkingLevel}from"./chunk-GTBU4EAF.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(field){return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,apiKey,options?.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,hasFinishReason=!1,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},ensureTextBlock=()=>(textBlock||(textBlock={type:"text",text:""},blocks.push(textBlock),stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output})),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output})),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output})}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block};for await(let chunk of openaiStream){if(!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(choice){if(!chunk.usage&&choice.usage&&(output.usage=parseChunkUsage(choice.usage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}let reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)isOpenAIReasoningDetail(detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail))}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
|
+
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools)){let messages=convertMessages(model,context,compat,{grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),params={model:model.id,messages,stream:!0,prompt_cache_key:model.baseUrl.includes("api.openai.com")&&cacheRetention!=="none"||cacheRetention==="long"&&compat.supportsLongCacheRetention?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature);let deferredToolNames=compat.deferredToolsMode==="kimi"?getDeferredToolNames(context.messages):new Set,activeTools=context.tools?.filter(tool=>!deferredToolNames.has(tool.name));activeTools&&activeTools.length>0?(params.tools=convertTools(activeTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice),compat.vllmPriority!==void 0&&(params.priority=compat.vllmPriority);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let mappedEffort=model.thinkingLevelMap?.[options.reasoningEffort],effort=mappedEffort===void 0?options.reasoningEffort:mappedEffort;typeof effort=="string"&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;typeof effort=="string"&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat.chatTemplateArgs,thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?model.thinkingLevelMap?.[requestedEffort]:model.thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)options?.reasoningEffort?params.thinking={type:"enabled"}:model.thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"}),options?.reasoningEffort&&compat.supportsReasoningEffort&&(params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort);else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;options?.reasoningEffort?openRouterParams.reasoning={effort:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort}:model.thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:model.thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort&&(togetherParams.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort)}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning){let stringThinkingParams=params;options?.reasoningEffort?stringThinkingParams.thinking=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:model.thinkingLevelMap?.off!==null&&(stringThinkingParams.thinking=model.thinkingLevelMap?.off??"none")}else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort)params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=model.thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}return options?.samplingParams&&Object.assign(params,options.samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let mappedValue=reasoningEffort?model.thinkingLevelMap?.[reasoningEffort]:model.thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function convertMessages(model,context,compat,options){let params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`}return model.provider==="openai"&&id.length>40?id.slice(0,40):id},transformedMessages=transformMessages(context.messages,model,id=>normalizeToolCallId(id));if(context.systemPrompt){let role=model.reasoning&&compat.supportsDeveloperRole?"developer":"system";params.push({role,content:sanitizeSurrogates(context.systemPrompt)})}let lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&¶ms.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="user")if(typeof msg.content=="string")params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let content=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;params.push({role:"user",content})}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0){if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
|
+
|
|
5
|
+
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else if(assistantText.length>0&&(assistantMsg.content=assistantText),!preservedReasoningDetails){let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature&&isOpenAICompletionsReasoningField(signature)&&(assistantMsg[signature]=nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|
|
6
|
+
`))}}else assistantText.length>0&&(assistantMsg.content=assistantText);toolCalls.length>0&&(assistantMsg.tool_calls=toolCalls.map(tc=>{let customInputProperty=options?.grammarToolInputProperties?.get(tc.name);return customInputProperty!==void 0?{id:tc.id,type:"custom",custom:{name:tc.name,input:sanitizeSurrogates(getGrammarToolInput(tc.name,tc.arguments,customInputProperty))}}:{id:tc.id,type:"function",function:{name:tc.name,arguments:JSON.stringify(tc.arguments)}}})),preservedReasoningDetails&&(assistantMsg.reasoning_details=preservedReasoningDetails),compat.requiresReasoningContentOnAssistantMessages&&model.reasoning&&assistantMsg.reasoning_content===void 0&&(assistantMsg.reasoning_content="");let content=assistantMsg.content;if(!(content!=null&&content.length>0)&&!assistantMsg.tool_calls)continue;params.push(assistantMsg)}else if(msg.role==="toolResult"){let imageBlocks=[],deferredToolNames=new Set,j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";j++){let toolMsg=transformedMessages[j],textResult=toolMsg.content.filter(isTextContentBlock).map(block=>block.text).join(`
|
|
7
|
+
`),hasImages=toolMsg.content.some(c=>c.type==="image"),toolResultText=textResult.length>0?textResult:hasImages?"(see attached image)":"(no tool output)",toolResultMsg={role:"tool",content:sanitizeSurrogates(toolResultText),tool_call_id:toolMsg.toolCallId};if(compat.requiresToolResultName&&toolMsg.toolName&&(toolResultMsg.name=toolMsg.toolName),params.push(toolResultMsg),compat.deferredToolsMode==="kimi")for(let name of toolMsg.addedToolNames??[])deferredToolNames.add(name);if(hasImages&&model.input.includes("image"))for(let block of toolMsg.content)isImageContentBlock(block)&&imageBlocks.push({type:"image_url",image_url:{url:`data:${block.mimeType};base64,${block.data}`}})}if(i=j-1,imageBlocks.length>0?(compat.requiresAssistantAfterToolResult&¶ms.push({role:"assistant",content:"I have processed the tool results."}),params.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...imageBlocks]}),lastRole="user"):lastRole="toolResult",deferredToolNames.size>0){let deferredTools=getToolsByName(context.tools,deferredToolNames);if(deferredTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(deferredTools,compat)};params.push(kimiToolMessage)}}continue}lastRole=msg.role}return params}function convertTools(tools,compat){return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,compat.supportsOpenAIGrammarTools);if(grammar)return{type:"custom",custom:{name:tool.name,description:tool.description,format:{type:"grammar",grammar:{syntax:grammar.format,definition:grammar.definition}}}};let strict=resolveJsonSchemaStrictSampling(tool,compat.supportsStrictMode!==!1);return{type:"function",function:{name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict),...compat.supportsStrictMode!==!1&&{strict:strict??!1}}}})}function parseChunkUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,cacheReadTokens=rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.prompt_cache_hit_tokens??rawUsage.cached_tokens??0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens||0,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),outputTokens=rawUsage.completion_tokens||0,usage={input,output:outputTokens,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens,reasoning:rawUsage.completion_tokens_details?.reasoning_tokens||0,totalTokens:input+outputTokens+cacheReadTokens+cacheWriteTokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}function mapStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${reason}`}}}function detectCompat(model){let provider=model.provider,baseUrl=model.baseUrl,isZai=provider==="zai"||provider==="zai-coding-cn"||baseUrl.includes("api.z.ai")||baseUrl.includes("open.bigmodel.cn"),isTogether=provider==="together"||baseUrl.includes("api.together.ai")||baseUrl.includes("api.together.xyz"),isMoonshot=provider==="moonshotai"||provider==="moonshotai-cn"||baseUrl.includes("api.moonshot."),isOpenRouter=provider==="openrouter"||baseUrl.includes("openrouter.ai"),isCloudflareWorkersAI=provider==="cloudflare-workers-ai"||baseUrl.includes("api.cloudflare.com"),isCloudflareAiGateway=provider==="cloudflare-ai-gateway"||baseUrl.includes("gateway.ai.cloudflare.com"),isNvidia=provider==="nvidia"||baseUrl.includes("integrate.api.nvidia.com"),isAntLing=provider==="ant-ling"||baseUrl.includes("api.ant-ling.com"),isDeepSeek=provider==="deepseek"||baseUrl.toLowerCase().includes("deepseek.com"),isNonStandard=isNvidia||provider==="cerebras"||baseUrl.includes("cerebras.ai")||provider==="xai"||baseUrl.includes("api.x.ai")||isTogether||baseUrl.includes("chutes.ai")||isDeepSeek||isZai||isMoonshot||provider==="opencode"||baseUrl.includes("opencode.ai")||isCloudflareWorkersAI||isCloudflareAiGateway||isAntLing,useMaxTokens=baseUrl.includes("chutes.ai")||isDeepSeek||isMoonshot||isCloudflareAiGateway||isTogether||isNvidia||isAntLing||isZai,isGrok=provider==="xai"||baseUrl.includes("api.x.ai"),isOpenRouterDeveloperRoleModel=isOpenRouter&&(model.id.startsWith("anthropic/")||model.id.startsWith("openai/")),cacheControlFormat=provider==="openrouter"&&model.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!isNonStandard,supportsDeveloperRole:isOpenRouterDeveloperRoleModel||!isNonStandard&&!isOpenRouter,supportsReasoningEffort:!isGrok&&!isZai&&!isMoonshot&&!isTogether&&!isCloudflareAiGateway&&!isNvidia&&!isAntLing,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:useMaxTokens?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:isDeepSeek,thinkingFormat:isDeepSeek?"deepseek":isZai?"zai":isTogether?"together":isAntLing?"ant-ling":isOpenRouter?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!isMoonshot&&!isTogether&&!isCloudflareAiGateway&&!isNvidia,supportsOpenAIGrammarTools:!1,cacheControlFormat,sendSessionAffinityHeaders:isOpenRouter,deferredToolsMode:void 0,sessionAffinityFormat:isOpenRouter?"openrouter":"openai",supportsLongCacheRetention:!(isTogether||isCloudflareWorkersAI||isCloudflareAiGateway||isNvidia||isAntLing)}}function getCompat(model){let detected=detectCompat(model);return model.compat?{supportsStore:model.compat.supportsStore??detected.supportsStore,supportsDeveloperRole:model.compat.supportsDeveloperRole??detected.supportsDeveloperRole,supportsReasoningEffort:model.compat.supportsReasoningEffort??detected.supportsReasoningEffort,supportsUsageInStreaming:model.compat.supportsUsageInStreaming??detected.supportsUsageInStreaming,supportsFinishReason:model.compat.supportsFinishReason??detected.supportsFinishReason,maxTokensField:model.compat.maxTokensField??detected.maxTokensField,requiresToolResultName:model.compat.requiresToolResultName??detected.requiresToolResultName,requiresAssistantAfterToolResult:model.compat.requiresAssistantAfterToolResult??detected.requiresAssistantAfterToolResult,requiresThinkingAsText:model.compat.requiresThinkingAsText??detected.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:model.compat.requiresReasoningContentOnAssistantMessages??detected.requiresReasoningContentOnAssistantMessages,thinkingFormat:model.compat.thinkingFormat??detected.thinkingFormat,openRouterRouting:model.compat.openRouterRouting??{},vercelGatewayRouting:model.compat.vercelGatewayRouting??detected.vercelGatewayRouting,chatTemplateKwargs:model.compat.chatTemplateKwargs??detected.chatTemplateKwargs,chatTemplateArgs:model.compat.chatTemplateArgs??detected.chatTemplateArgs,zaiToolStream:model.compat.zaiToolStream??detected.zaiToolStream,supportsThinkingTokenBudget:model.compat.supportsThinkingTokenBudget??detected.supportsThinkingTokenBudget,thinkingTokenBudgetField:model.compat.thinkingTokenBudgetField??detected.thinkingTokenBudgetField,supportsStrictMode:model.compat.supportsStrictMode??detected.supportsStrictMode,supportsOpenAIGrammarTools:model.compat.supportsOpenAIGrammarTools??detected.supportsOpenAIGrammarTools,cacheControlFormat:model.compat.cacheControlFormat??detected.cacheControlFormat,sendSessionAffinityHeaders:model.compat.sendSessionAffinityHeaders??detected.sendSessionAffinityHeaders,deferredToolsMode:model.compat.deferredToolsMode??detected.deferredToolsMode,sessionAffinityFormat:model.compat.sessionAffinityFormat??detected.sessionAffinityFormat,supportsLongCacheRetention:model.compat.supportsLongCacheRetention??detected.supportsLongCacheRetention,vllmPriority:model.compat.vllmPriority}:detected}export{convertMessages,stream,streamSimple};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{splitDeferredTools}from"./chunk-GMWCTUPB.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-NV6PWB3O.js";import{OpenAI}from"./chunk-NUHFSC37.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PJACZCIR.js";import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-AXIIZGTV.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import"./chunk-TRDNDS6A.js";import{clampThinkingLevel}from"./chunk-GTBU4EAF.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var OPENAI_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function detectSessionAffinityFormat(model){return model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCompat(model){return{supportsDeveloperRole:model.compat?.supportsDeveloperRole??!0,sessionAffinityFormat:model.compat?.sessionAffinityFormat??detectSessionAffinityFormat(model),supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,supportsStrictMode:model.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:model.compat?.supportsAdditionalTools??!1,supportsToolSearch:model.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:model.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:model.compat?.supportsMaxOutputTokens??!0}}function getPromptCacheRetention(compat,cacheRetention){return cacheRetention==="long"&&compat.supportsLongCacheRetention&&!compat.supportsExplicitPromptCacheMode?"24h":void 0}function getPromptCacheOptions(compat,cacheRetention){if(compat.supportsExplicitPromptCacheMode){if(cacheRetention==="none")return{mode:"explicit"};if(cacheRetention==="long"&&compat.supportsLongCacheRetention)return{ttl:"30m"}}}function formatOpenAIResponsesError(error){return formatProviderError(normalizeProviderError(error),"OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools),client=createClient(model,context,apiKey,options?.headers,options?.fetch,cacheSessionId),params=buildParams(model,context,options,compat,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop 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.index,delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatOpenAIResponsesError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId){let compat=getCompat(model),headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools)){let deferredToolsMode=compat.supportsAdditionalTools?"additional-tools":compat.supportsToolSearch?"tool-search":void 0,toolPlacement=splitDeferredTools(context,deferredToolsMode!==void 0),messages=convertResponsesMessages(model,context,OPENAI_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,deferredTools:toolPlacement.deferred,deferredToolsMode,toolOptions:{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools}}),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),params={model:model.id,input:messages,stream:!0,prompt_cache_key:cacheRetention==="none"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),prompt_cache_retention:getPromptCacheRetention(compat,cacheRetention),prompt_cache_options:getPromptCacheOptions(compat,cacheRetention),store:!1};if(options?.maxTokens&&compat.supportsMaxOutputTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),options?.serviceTier!==void 0&&(params.service_tier=options.serviceTier),toolPlacement.immediate.length>0&&(params.tools=convertResponsesTools(toolPlacement.immediate,{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice),model.reasoning){if(options?.reasoningEffort||options?.reasoningSummary){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:"medium";params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.provider!=="github-copilot"&&model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});model.provider==="xai"&&(params.include=["reasoning.encrypted_content"])}return options?.samplingParams&&Object.assign(params,options.samplingParams),params}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}export{stream,streamSimple};
|