import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
import{headersToRecord,providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic}from"./chunk-UAQELI3K.js";import"./chunk-4L3WN2XY.js";var PiMessagesResponseError=class extends Error{code;diagnosticDetails;constructor(message,code,diagnosticDetails){super(message),this.name="PiMessagesResponseError",this.code=code,this.diagnosticDetails=diagnosticDetails}};function parsePiMessagesErrorBody(body){try{let parsed=JSON.parse(body),error=parsed?.error;return parsed&&typeof error=="object"&&error!==null&&!Array.isArray(error)?parsed:void 0}catch{return}}function truncateDiagnosticString(value){return value.length>8192?`${value.slice(0,8192)}\u2026`:value}function formatPiMessagesResponseError(response,body,errorBody){let message=typeof errorBody?.error?.message=="string"?errorBody.error.message:void 0,code=typeof errorBody?.error?.code=="string"?errorBody.error.code:void 0,suffix=message??body,codeSuffix=code?` (${code})`:"";return`${response.status} ${response.statusText}: ${suffix}${codeSuffix}`}function createPiMessagesResponseError(model,url,response,body){let errorBody=parsePiMessagesErrorBody(body),code=typeof errorBody?.error?.code=="string"?errorBody.error.code:void 0;return new PiMessagesResponseError(formatPiMessagesResponseError(response,body,errorBody),code,{version:1,provider:model.provider,model:model.id,url:url.toString(),status:response.status,statusText:response.statusText,error:errorBody?.error,body:errorBody?void 0:truncateDiagnosticString(body),timestampMs:Date.now()})}function createEmptyUsage(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function appendRewriteDiagnostic(message,rewrite){rewrite&&appendAssistantMessageDiagnostic(message,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...rewrite}})}function createEventConverter(model){let partial={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:createEmptyUsage(),stopReason:"pending",timestamp:Date.now()},toolJson=new Map;return event=>{switch(event.type){case"done":return Object.assign(partial,{stopReason:event.reason,usage:event.usage,responseId:event.responseId}),appendRewriteDiagnostic(partial,event.rewrite),{type:"done",reason:event.reason,message:partial};case"error":return Object.assign(partial,{stopReason:event.reason,usage:event.usage,errorMessage:event.errorMessage,responseId:event.responseId}),appendRewriteDiagnostic(partial,event.rewrite),{type:"error",reason:event.reason,error:partial};case"start":break;case"text_start":partial.content[event.contentIndex]={type:"text",text:""};break;case"text_delta":partial.content[event.contentIndex].text+=event.delta;break;case"text_end":Object.assign(partial.content[event.contentIndex],{text:event.content,textSignature:event.contentSignature});break;case"thinking_start":partial.content[event.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":partial.content[event.contentIndex].thinking+=event.delta;break;case"thinking_end":Object.assign(partial.content[event.contentIndex],{thinking:event.content,thinkingSignature:event.contentSignature,redacted:event.redacted});break;case"toolcall_start":partial.content[event.contentIndex]={type:"toolCall",id:event.id,name:event.toolName,arguments:{}},toolJson.set(event.contentIndex,"");break;case"toolcall_delta":{let json=`${toolJson.get(event.contentIndex)??""}${event.delta}`;toolJson.set(event.contentIndex,json),partial.content[event.contentIndex].arguments=parseStreamingJson(json);break}case"toolcall_end":return Object.assign(partial.content[event.contentIndex],event.toolCall),toolJson.delete(event.contentIndex),{type:"toolcall_end",contentIndex:event.contentIndex,toolCall:partial.content[event.contentIndex],partial}}return{...event,partial}}}async function*readPiMessagesEvents(stream2){let decoder=new TextDecoder,reader=stream2.getReader(),buffer="";try{for(;;){let{done,value}=await reader.read();buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),buffer=buffer.replace(/\r\n/g,`
`);let split=buffer.indexOf(`

`);for(;split!==-1;){let event=parsePiMessagesEvent(buffer.slice(0,split));event&&(yield event),buffer=buffer.slice(split+2),split=buffer.indexOf(`

`)}if(done)break}if(buffer.trim()){let event=parsePiMessagesEvent(buffer);event&&(yield event)}}finally{reader.releaseLock()}}function parsePiMessagesEvent(raw){let data=raw.split(`
`).find(line=>line.startsWith("data:"))?.slice(5).trim();return data&&data!=="[DONE]"?JSON.parse(data):void 0}function createErrorEvent(model,error,aborted){let reason=aborted?"aborted":"error",assistantMessage={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:createEmptyUsage(),stopReason:reason,errorMessage:error instanceof Error?error.message:String(error),timestamp:Date.now()};return!aborted&&error instanceof PiMessagesResponseError&&appendAssistantMessageDiagnostic(assistantMessage,createAssistantMessageDiagnostic("pi_messages_response_failure",error,error.diagnosticDetails)),{type:"error",reason,error:assistantMessage}}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":void 0)}var stream=(model,context,options)=>{let eventStream=new AssistantMessageEventStream,convertEvent=createEventConverter(model);return(async()=>{try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key provided for provider "${model.provider}"`);let url=new URL(`${model.baseUrl.replace(/\/+$/u,"")}/messages`);options?.debug&&url.searchParams.set("debug","1");let payload={model:model.id,context,options:{temperature:options?.temperature,maxTokens:options?.maxTokens,reasoning:options?.reasoning,cacheRetention:resolveCacheRetention(options?.cacheRetention,options?.env),sessionId:options?.sessionId,toolChoice:options?.toolChoice}},nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers:{authorization:`Bearer ${apiKey}`,accept:"text/event-stream","content-type":"application/json",...providerHeadersToRecord(options?.headers)},body:JSON.stringify(payload),signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw createPiMessagesResponseError(model,url,response,body)}if(!response.body)throw new Error(`${model.provider} response has no body`);for await(let piEvent of readPiMessagesEvents(response.body)){let event=convertEvent(piEvent);if(eventStream.push(event),event.type==="done"||event.type==="error")return}throw new Error(`${model.provider} stream ended without a terminal event`)}catch(error){eventStream.push(createErrorEvent(model,error,options?.signal?.aborted??!1))}})(),eventStream},streamSimple=(model,context,options)=>{let extra=options;return stream(model,context,{...options,reasoning:options?.reasoning,toolChoice:options?.toolChoice,debug:extra?.debug})};export{PiMessagesResponseError,stream,streamSimple};
