@averyyy/pi-coding-agent 1.4.0-piclient.7 → 1.4.0-piclient.9

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.
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-OSZFX42P.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PMRZO46Y.js";import{buildBaseOptions}from"./chunk-WVXVPMMO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-D3OXAPLU.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-H76KZMOI.js";import"./chunk-JXWJOIH4.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers,options?.identity),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders,identity){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord(getIdentityHeaders(model,identity),model.headers,optionsHeaders);return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
2
+ import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-MKWEYCNF.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PMRZO46Y.js";import{buildBaseOptions}from"./chunk-WVXVPMMO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-D3OXAPLU.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-H76KZMOI.js";import"./chunk-JXWJOIH4.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers,options?.identity),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders,identity){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord(getIdentityHeaders(model,identity),model.headers,optionsHeaders);return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-OSZFX42P.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PMRZO46Y.js";import{buildBaseOptions}from"./chunk-WVXVPMMO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-D3OXAPLU.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-H76KZMOI.js";import"./chunk-JXWJOIH4.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers,options?.identity):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env,options?.identity),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env,identity){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders,identity)})}function createClientWithApiKey(model,apiKey,optionsHeaders,identity){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders,identity)})}function buildHttpOptions(model,optionsHeaders,identity){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord(getIdentityHeaders(model,identity),model.headers,optionsHeaders);return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
2
+ import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-MKWEYCNF.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PMRZO46Y.js";import{buildBaseOptions}from"./chunk-WVXVPMMO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-D3OXAPLU.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-H76KZMOI.js";import"./chunk-JXWJOIH4.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers,options?.identity):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env,options?.identity),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env,identity){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders,identity)})}function createClientWithApiKey(model,apiKey,optionsHeaders,identity){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders,identity)})}function buildHttpOptions(model,optionsHeaders,identity){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord(getIdentityHeaders(model,identity),model.headers,optionsHeaders);return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{dist_exports as dist_exports3}from"./chunk-CC2NYFQY.js";import{all_exports,compat_exports,compile_exports,dist_exports as dist_exports2,value_exports}from"./chunk-6C5IXBS7.js";import{build_exports}from"./chunk-BRYV63PL.js";import"./chunk-3EGEEHMN.js";import{dist_exports}from"./chunk-H2UJDH5M.js";import"./chunk-PG7P2LUM.js";import"./chunk-VYYRESZJ.js";import"./chunk-H2AI7MFJ.js";import"./chunk-6QGV3IWD.js";import"./chunk-3LTMO2WY.js";import"./chunk-USJZMAIR.js";import"./chunk-5AGIVGSV.js";import"./chunk-UKVNB6C4.js";import"./chunk-TMTOQ7H7.js";import"./chunk-7DDKXS2Q.js";import"./chunk-3V45WARH.js";import{models_exports}from"./chunk-D3OXAPLU.js";import"./chunk-LPXNMA2W.js";import"./chunk-H76KZMOI.js";import"./chunk-JXWJOIH4.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/models":models_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-works/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/models":models_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
2
+ import{dist_exports as dist_exports3}from"./chunk-3NEJV7UG.js";import{all_exports,compat_exports,compile_exports,dist_exports as dist_exports2,value_exports}from"./chunk-K47GPRYD.js";import{build_exports}from"./chunk-BRYV63PL.js";import"./chunk-3EGEEHMN.js";import{dist_exports}from"./chunk-H2UJDH5M.js";import"./chunk-PG7P2LUM.js";import"./chunk-VYYRESZJ.js";import"./chunk-H2AI7MFJ.js";import"./chunk-6QGV3IWD.js";import"./chunk-3LTMO2WY.js";import"./chunk-USJZMAIR.js";import"./chunk-5AGIVGSV.js";import"./chunk-UKVNB6C4.js";import"./chunk-TMTOQ7H7.js";import"./chunk-7DDKXS2Q.js";import"./chunk-3V45WARH.js";import{models_exports}from"./chunk-D3OXAPLU.js";import"./chunk-LPXNMA2W.js";import"./chunk-H76KZMOI.js";import"./chunk-JXWJOIH4.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/models":models_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-works/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/models":models_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-6C5IXBS7.js";import"./chunks/chunk-BRYV63PL.js";import"./chunks/chunk-3EGEEHMN.js";import"./chunks/chunk-H2UJDH5M.js";import"./chunks/chunk-PG7P2LUM.js";import"./chunks/chunk-VYYRESZJ.js";import"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-D3OXAPLU.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-H76KZMOI.js";import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-K47GPRYD.js";import"./chunks/chunk-BRYV63PL.js";import"./chunks/chunk-3EGEEHMN.js";import"./chunks/chunk-H2UJDH5M.js";import"./chunks/chunk-PG7P2LUM.js";import"./chunks/chunk-VYYRESZJ.js";import"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-D3OXAPLU.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-H76KZMOI.js";import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-CC2NYFQY.js";import{AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingToolDefinitions,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createMcpExtension,createReadOnlyToolDefinitions,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-6C5IXBS7.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatReadLineRange,formatSize,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-BRYV63PL.js";import{ArminComponent}from"./chunks/chunk-3EGEEHMN.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-H2UJDH5M.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-PG7P2LUM.js";import{readStoredCredential}from"./chunks/chunk-VYYRESZJ.js";import{getShellConfig}from"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-D3OXAPLU.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-H76KZMOI.js";import"./chunks/chunk-JXWJOIH4.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingToolDefinitions,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createMcpExtension,createReadOnlyToolDefinitions,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatReadLineRange,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-3NEJV7UG.js";import{AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingToolDefinitions,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createMcpExtension,createReadOnlyToolDefinitions,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-K47GPRYD.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatReadLineRange,formatSize,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-BRYV63PL.js";import{ArminComponent}from"./chunks/chunk-3EGEEHMN.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-H2UJDH5M.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-PG7P2LUM.js";import{readStoredCredential}from"./chunks/chunk-VYYRESZJ.js";import{getShellConfig}from"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-D3OXAPLU.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-H76KZMOI.js";import"./chunks/chunk-JXWJOIH4.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingToolDefinitions,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createMcpExtension,createReadOnlyToolDefinitions,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatReadLineRange,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-6C5IXBS7.js";import"./chunks/chunk-BRYV63PL.js";import"./chunks/chunk-3EGEEHMN.js";import"./chunks/chunk-H2UJDH5M.js";import"./chunks/chunk-PG7P2LUM.js";import"./chunks/chunk-VYYRESZJ.js";import"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-D3OXAPLU.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-H76KZMOI.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-K47GPRYD.js";import"./chunks/chunk-BRYV63PL.js";import"./chunks/chunk-3EGEEHMN.js";import"./chunks/chunk-H2UJDH5M.js";import"./chunks/chunk-PG7P2LUM.js";import"./chunks/chunk-VYYRESZJ.js";import"./chunks/chunk-H2AI7MFJ.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-3LTMO2WY.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-3V45WARH.js";import"./chunks/chunk-D3OXAPLU.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-H76KZMOI.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -40,7 +40,6 @@ export interface ObserverUpdate {
40
40
  sequence: number;
41
41
  cwd: string;
42
42
  title: string;
43
- lastActiveAt: number | null;
44
43
  replace?: ObserverMessage[];
45
44
  append?: ObserverMessage[];
46
45
  status: "running" | "idle";
@@ -77,13 +76,10 @@ export declare class PiServerObserver {
77
76
  private liveMessageId;
78
77
  private readonly tools;
79
78
  private disconnected;
80
- private activitySessionId?;
81
- private lastActiveAt;
79
+ private observedSessionId?;
82
80
  constructor(session: AgentSession);
83
81
  private handleEvent;
84
- private syncActivity;
85
- private recordEntryActivity;
86
- private recordActivity;
82
+ private syncSession;
87
83
  private schedule;
88
84
  private reportError;
89
85
  private stopDeletedSession;
@@ -1 +1 @@
1
- {"version":3,"file":"pi-server-observer.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-observer.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAA6B,eAAe,EAA6B,MAAM,uBAAuB,CAAC;AAEnH,OAAO,KAAK,EAAE,YAAY,EAAqB,MAAM,oBAAoB,CAAC;AAG1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAIzD,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhF;AAED,K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eAAe,CAAC,CAAgB;IACxC,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAClC,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,kBAAkB,CAAC,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAC,CAAgB;IACrC,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,YAAY,CAAQ;IAC5B,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,cAAc,CAAsB;IAC5C,OAAO,CAAC,cAAc,CAAM;IAC5B,OAAO,CAAC,WAAW,CAA6B;IAChD,OAAO,CAAC,aAAa,CAAM;IAC3B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAmC;IACzD,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,iBAAiB,CAAC,CAAS;IAEnC,YAAY,OAAO,EAAE,YAAY,EAYhC;IAED,OAAO,CAAC,WAAW;IAoFnB,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,QAAQ;IAkBhB,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,kBAAkB;IAe1B,OAAO,CAAC,OAAO;YAQD,OAAO;IAgFrB,OAAO,CAAC,KAAK;YAUC,UAAU;IA2ExB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAGrB;YAEa,aAAa;IA2B3B,OAAO,IAAI,IAAI,CAOd;CACD"}
@@ -105,11 +105,10 @@ export class PiServerObserver {
105
105
  liveMessageId = "";
106
106
  tools = new Map();
107
107
  disconnected = false;
108
- activitySessionId;
109
- lastActiveAt = null;
108
+ observedSessionId;
110
109
  constructor(session) {
111
110
  this.session = session;
112
- this.syncActivity();
111
+ this.syncSession();
113
112
  observers.set(session, this);
114
113
  this.unsubscribe = session.subscribe((event) => {
115
114
  try {
@@ -122,13 +121,12 @@ export class PiServerObserver {
122
121
  void this.connect();
123
122
  }
124
123
  handleEvent(event) {
125
- this.syncActivity();
124
+ this.syncSession();
126
125
  switch (event.type) {
127
126
  case "session_disposed":
128
127
  this.dispose();
129
128
  return;
130
129
  case "run_state_changed":
131
- this.recordActivity(Date.now());
132
130
  if (!event.running) {
133
131
  this.liveMessage = null;
134
132
  this.tools.clear();
@@ -137,7 +135,6 @@ export class PiServerObserver {
137
135
  case "message_start":
138
136
  if (event.message.role !== "assistant")
139
137
  return;
140
- this.recordActivity(Date.now());
141
138
  this.tools.clear();
142
139
  this.liveMessageId = randomUUID();
143
140
  this.liveMessage = event.message;
@@ -147,7 +144,6 @@ export class PiServerObserver {
147
144
  break;
148
145
  case "entry_appended":
149
146
  case "message_committed":
150
- this.recordEntryActivity(event.entry);
151
147
  if (this.connectionId && !this.historyDirty) {
152
148
  this.pendingEntries.push(event.entry);
153
149
  if (this.pendingEntries.length > 64) {
@@ -160,8 +156,6 @@ export class PiServerObserver {
160
156
  break;
161
157
  case "history_reconciled":
162
158
  case "session_tree_changed":
163
- for (const entry of this.session.sessionManager.getEntries())
164
- this.recordEntryActivity(entry);
165
159
  if (this.deletedSessionId && this.deletedSessionId !== this.session.sessionId) {
166
160
  this.deletedSessionId = undefined;
167
161
  void this.connect();
@@ -174,16 +168,13 @@ export class PiServerObserver {
174
168
  this.historyDirty = true;
175
169
  break;
176
170
  case "compaction_end":
177
- this.recordActivity(Date.now());
178
171
  this.historyDirty = true;
179
172
  break;
180
173
  case "compaction_start":
181
- this.recordActivity(Date.now());
182
174
  break;
183
175
  case "session_info_changed":
184
176
  break;
185
177
  case "tool_execution_start":
186
- this.recordActivity(Date.now());
187
178
  this.tools.set(event.toolCallId, {
188
179
  id: event.toolCallId,
189
180
  name: event.toolName,
@@ -198,7 +189,6 @@ export class PiServerObserver {
198
189
  break;
199
190
  }
200
191
  case "tool_execution_end": {
201
- this.recordActivity(Date.now());
202
192
  const tool = this.tools.get(event.toolCallId);
203
193
  if (tool) {
204
194
  tool.result = { content: projectContent(event.result.content), isError: event.isError };
@@ -214,30 +204,15 @@ export class PiServerObserver {
214
204
  ? 0
215
205
  : 80);
216
206
  }
217
- syncActivity() {
218
- if (this.activitySessionId === this.session.sessionId)
207
+ syncSession() {
208
+ if (this.observedSessionId === this.session.sessionId)
219
209
  return;
220
- this.activitySessionId = this.session.sessionId;
221
- this.lastActiveAt = null;
210
+ this.observedSessionId = this.session.sessionId;
222
211
  this.sentEntryId = undefined;
223
212
  this.pendingEntries = [];
224
213
  this.firstUserTitle = "";
225
214
  this.liveMessage = null;
226
215
  this.tools.clear();
227
- for (const entry of this.session.sessionManager.getEntries())
228
- this.recordEntryActivity(entry);
229
- }
230
- recordEntryActivity(entry) {
231
- if ((entry.type === "message" &&
232
- entry.message.role !== "system" &&
233
- (entry.message.role !== "custom" || entry.message.display)) ||
234
- (entry.type === "custom_message" && entry.display) ||
235
- entry.type === "compaction" ||
236
- entry.type === "branch_summary")
237
- this.recordActivity(Date.parse(entry.timestamp));
238
- }
239
- recordActivity(timestamp) {
240
- this.lastActiveAt = this.lastActiveAt === null ? timestamp : Math.max(this.lastActiveAt, timestamp);
241
216
  }
242
217
  schedule(delay) {
243
218
  if (this.disposed ||
@@ -284,7 +259,7 @@ export class PiServerObserver {
284
259
  async connect() {
285
260
  if (this.disposed || this.deletedSessionId === this.session.sessionId)
286
261
  return;
287
- this.syncActivity();
262
+ this.syncSession();
288
263
  const controller = new AbortController();
289
264
  this.controller = controller;
290
265
  const sessionId = this.session.sessionId;
@@ -414,7 +389,6 @@ export class PiServerObserver {
414
389
  sequence: ++this.sequence,
415
390
  cwd: this.session.sessionManager.getCwd(),
416
391
  title: this.session.sessionManager.getSessionName() ?? this.firstUserTitle,
417
- lastActiveAt: this.lastActiveAt,
418
392
  ...(replace ? { replace: messages } : messages.length ? { append: messages } : {}),
419
393
  status: this.session.isIdle ? "idle" : "running",
420
394
  live: {
@@ -1 +1 @@
1
- {"version":3,"file":"pi-server-observer.js","sourceRoot":"","sources":["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IAChC,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent, TextSignatureV1, ThinkingContent, ToolCall } from \"@earendil-works/pi-ai\";\nimport { raceWithAbortSignal } from \"../utils/abort.ts\";\nimport type { AgentSession, AgentSessionEvent } from \"./agent-session.ts\";\nimport { bashExecutionToText } from \"./messages.ts\";\nimport { ChunkRequest } from \"./pi-server-request.ts\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nconst observers = new WeakMap<AgentSession, PiServerObserver>();\n\nexport async function closePiServerObserver(session: AgentSession): Promise<void> {\n\tawait observers.get(session)?.close();\n}\n\ntype ViewerContent =\n\t| { type: \"text\"; text: string; phase?: TextSignatureV1[\"phase\"] }\n\t| { type: \"thinking\"; thinking: string }\n\t| { type: \"toolCall\"; id: string; name: string; arguments: unknown }\n\t| { type: \"attachment\"; label: string };\n\nexport interface ObserverMessage {\n\tid: string;\n\trole: string;\n\tcontent: string | ViewerContent[];\n\ttimestamp: number;\n\tstopReason?: string;\n\tphase?: string;\n\terrorMessage?: string;\n}\n\ninterface ObserverTool {\n\tid: string;\n\tname: string;\n\targuments: unknown;\n\tresult?: unknown;\n\tstatus: \"running\" | \"completed\" | \"error\";\n}\n\nexport interface ObserverUpdate {\n\tsessionId: string;\n\tconnectionId: string;\n\tsequence: number;\n\tcwd: string;\n\ttitle: string;\n\tlastActiveAt: number | null;\n\treplace?: ObserverMessage[];\n\tappend?: ObserverMessage[];\n\tstatus: \"running\" | \"idle\";\n\tlive: { message: ObserverMessage | null; tools: ObserverTool[] };\n}\n\nfunction textPhase(signature: string | undefined): TextSignatureV1[\"phase\"] {\n\tif (!signature?.startsWith(\"{\")) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\tif (\n\t\t\tparsed.v === 1 &&\n\t\t\ttypeof parsed.id === \"string\" &&\n\t\t\t(parsed.phase === \"commentary\" || parsed.phase === \"final_answer\")\n\t\t)\n\t\t\treturn parsed.phase;\n\t} catch {\n\t\t// Provider signatures outside TextSignatureV1 have no display phase.\n\t}\n\treturn undefined;\n}\n\nfunction projectContent(\n\tcontent: string | (TextContent | ThinkingContent | ImageContent | ToolCall)[],\n): ObserverMessage[\"content\"] {\n\tif (typeof content === \"string\") return content;\n\treturn content.map((part): ViewerContent => {\n\t\tif (part.type === \"text\") return { type: \"text\", text: part.text, phase: textPhase(part.textSignature) };\n\t\tif (part.type === \"thinking\") return { type: \"thinking\", thinking: part.thinking };\n\t\tif (part.type === \"toolCall\")\n\t\t\treturn { type: \"toolCall\", id: part.id, name: part.name, arguments: part.arguments };\n\t\treturn { type: \"attachment\", label: part.mimeType };\n\t});\n}\n\nfunction projectMessage(id: string, message: AgentMessage, timestamp = message.timestamp): ObserverMessage | undefined {\n\tif (message.role === \"system\" || (message.role === \"custom\" && !message.display)) return undefined;\n\tlet content: ObserverMessage[\"content\"];\n\tif (message.role === \"bashExecution\") content = bashExecutionToText(message);\n\telse if (message.role === \"compactionSummary\" || message.role === \"branchSummary\") content = message.summary;\n\telse content = projectContent(message.content);\n\tconst projected: ObserverMessage = { id, role: message.role, content, timestamp };\n\tif (message.role === \"assistant\") {\n\t\tprojected.stopReason = message.stopReason;\n\t\tprojected.errorMessage = message.errorMessage;\n\t\tfor (const part of message.content) {\n\t\t\tconst phase = part.type === \"text\" ? textPhase(part.textSignature) : undefined;\n\t\t\tif (phase) projected.phase = phase;\n\t\t}\n\t}\n\treturn projected;\n}\n\nexport function projectObserverEntries(entries: SessionEntry[]): ObserverMessage[] {\n\tconst messages: ObserverMessage[] = [];\n\tfor (const entry of entries) {\n\t\tlet message: ObserverMessage | undefined;\n\t\tif (entry.type === \"message\") message = projectMessage(entry.id, entry.message, Date.parse(entry.timestamp));\n\t\telse if (entry.type === \"custom_message\" && entry.display) {\n\t\t\tmessage = {\n\t\t\t\tid: entry.id,\n\t\t\t\trole: \"custom\",\n\t\t\t\tcontent: projectContent(entry.content),\n\t\t\t\ttimestamp: Date.parse(entry.timestamp),\n\t\t\t};\n\t\t} else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\tmessage = { id: entry.id, role: entry.type, content: entry.summary, timestamp: Date.parse(entry.timestamp) };\n\t\t}\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\n/** Publishes transcript updates independently of provider requests and durable server trees. */\nexport class PiServerObserver {\n\tprivate readonly session: AgentSession;\n\tprivate readonly unsubscribe: () => void;\n\tprivate controller?: AbortController;\n\tprivate timer?: ReturnType<typeof setTimeout>;\n\tprivate reconnectTimer?: ReturnType<typeof setTimeout>;\n\tprivate disposed = false;\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate connectionReady?: Promise<void>;\n\tprivate deletedSessionId?: string;\n\tprivate connectionId?: string;\n\tprivate connectedSessionId?: string;\n\tprivate sequence = 0;\n\tprivate sending = false;\n\tprivate flushPromise?: Promise<void>;\n\tprivate dirty = true;\n\tprivate historyDirty = true;\n\tprivate replace = true;\n\tprivate sentEntryId?: string;\n\tprivate pendingEntries: SessionEntry[] = [];\n\tprivate firstUserTitle = \"\";\n\tprivate liveMessage: AgentMessage | null = null;\n\tprivate liveMessageId = \"\";\n\tprivate readonly tools = new Map<string, ObserverTool>();\n\tprivate disconnected = false;\n\tprivate activitySessionId?: string;\n\tprivate lastActiveAt: number | null = null;\n\n\tconstructor(session: AgentSession) {\n\t\tthis.session = session;\n\t\tthis.syncActivity();\n\t\tobservers.set(session, this);\n\t\tthis.unsubscribe = session.subscribe((event) => {\n\t\t\ttry {\n\t\t\t\tthis.handleEvent(event);\n\t\t\t} catch (error) {\n\t\t\t\tthis.reportError(error);\n\t\t\t}\n\t\t});\n\t\tvoid this.connect();\n\t}\n\n\tprivate handleEvent(event: AgentSessionEvent): void {\n\t\tthis.syncActivity();\n\t\tswitch (event.type) {\n\t\t\tcase \"session_disposed\":\n\t\t\t\tthis.dispose();\n\t\t\t\treturn;\n\t\t\tcase \"run_state_changed\":\n\t\t\t\tthis.recordActivity(Date.now());\n\t\t\t\tif (!event.running) {\n\t\t\t\t\tthis.liveMessage = null;\n\t\t\t\t\tthis.tools.clear();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\t\tif (event.message.role !== \"assistant\") return;\n\t\t\t\tthis.recordActivity(Date.now());\n\t\t\t\tthis.tools.clear();\n\t\t\t\tthis.liveMessageId = randomUUID();\n\t\t\t\tthis.liveMessage = event.message;\n\t\t\t\tbreak;\n\t\t\tcase \"message_update\":\n\t\t\t\tthis.liveMessage = event.message;\n\t\t\t\tbreak;\n\t\t\tcase \"entry_appended\":\n\t\t\tcase \"message_committed\":\n\t\t\t\tthis.recordEntryActivity(event.entry);\n\t\t\t\tif (this.connectionId && !this.historyDirty) {\n\t\t\t\t\tthis.pendingEntries.push(event.entry);\n\t\t\t\t\tif (this.pendingEntries.length > 64) {\n\t\t\t\t\t\tthis.pendingEntries = [];\n\t\t\t\t\t\tthis.historyDirty = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (event.entry.type === \"message\" && event.entry.message.role === \"assistant\") this.liveMessage = null;\n\t\t\t\tbreak;\n\t\t\tcase \"history_reconciled\":\n\t\t\tcase \"session_tree_changed\":\n\t\t\t\tfor (const entry of this.session.sessionManager.getEntries()) this.recordEntryActivity(entry);\n\t\t\t\tif (this.deletedSessionId && this.deletedSessionId !== this.session.sessionId) {\n\t\t\t\t\tthis.deletedSessionId = undefined;\n\t\t\t\t\tvoid this.connect();\n\t\t\t\t}\n\t\t\t\tif (this.connectedSessionId && this.connectedSessionId !== this.session.sessionId) {\n\t\t\t\t\tthis.connectionId = undefined;\n\t\t\t\t\tthis.controller?.abort();\n\t\t\t\t}\n\t\t\t\tthis.replace = true;\n\t\t\t\tthis.historyDirty = true;\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_end\":\n\t\t\t\tthis.recordActivity(Date.now());\n\t\t\t\tthis.historyDirty = true;\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_start\":\n\t\t\t\tthis.recordActivity(Date.now());\n\t\t\t\tbreak;\n\t\t\tcase \"session_info_changed\":\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.recordActivity(Date.now());\n\t\t\t\tthis.tools.set(event.toolCallId, {\n\t\t\t\t\tid: event.toolCallId,\n\t\t\t\t\tname: event.toolName,\n\t\t\t\t\targuments: event.args,\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_update\": {\n\t\t\t\tconst tool = this.tools.get(event.toolCallId);\n\t\t\t\tif (tool) tool.result = { content: projectContent(event.partialResult.content) };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tthis.recordActivity(Date.now());\n\t\t\t\tconst tool = this.tools.get(event.toolCallId);\n\t\t\t\tif (tool) {\n\t\t\t\t\ttool.result = { content: projectContent(event.result.content), isError: event.isError };\n\t\t\t\t\ttool.status = event.isError ? \"error\" : \"completed\";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\t\tthis.dirty = true;\n\t\tthis.schedule(\n\t\t\tevent.type === \"run_state_changed\" || event.type === \"compaction_start\" || event.type === \"compaction_end\"\n\t\t\t\t? 0\n\t\t\t\t: 80,\n\t\t);\n\t}\n\n\tprivate syncActivity(): void {\n\t\tif (this.activitySessionId === this.session.sessionId) return;\n\t\tthis.activitySessionId = this.session.sessionId;\n\t\tthis.lastActiveAt = null;\n\t\tthis.sentEntryId = undefined;\n\t\tthis.pendingEntries = [];\n\t\tthis.firstUserTitle = \"\";\n\t\tthis.liveMessage = null;\n\t\tthis.tools.clear();\n\t\tfor (const entry of this.session.sessionManager.getEntries()) this.recordEntryActivity(entry);\n\t}\n\n\tprivate recordEntryActivity(entry: SessionEntry): void {\n\t\tif (\n\t\t\t(entry.type === \"message\" &&\n\t\t\t\tentry.message.role !== \"system\" &&\n\t\t\t\t(entry.message.role !== \"custom\" || entry.message.display)) ||\n\t\t\t(entry.type === \"custom_message\" && entry.display) ||\n\t\t\tentry.type === \"compaction\" ||\n\t\t\tentry.type === \"branch_summary\"\n\t\t)\n\t\t\tthis.recordActivity(Date.parse(entry.timestamp));\n\t}\n\n\tprivate recordActivity(timestamp: number): void {\n\t\tthis.lastActiveAt = this.lastActiveAt === null ? timestamp : Math.max(this.lastActiveAt, timestamp);\n\t}\n\n\tprivate schedule(delay: number): void {\n\t\tif (\n\t\t\tthis.disposed ||\n\t\t\tthis.closing ||\n\t\t\tthis.deletedSessionId === this.session.sessionId ||\n\t\t\t!this.dirty ||\n\t\t\t!this.connectionId ||\n\t\t\tthis.sending ||\n\t\t\tthis.timer\n\t\t)\n\t\t\treturn;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = undefined;\n\t\t\tvoid this.flush();\n\t\t}, delay);\n\t\tthis.timer.unref();\n\t}\n\n\tprivate reportError(error: unknown): void {\n\t\tif (this.disposed || this.disconnected) return;\n\t\tthis.disconnected = true;\n\t\tconsole.error(`pi-server observer disconnected: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\n\tprivate stopDeletedSession(sessionId: string, controller: AbortController): void {\n\t\tif (sessionId === this.session.sessionId) {\n\t\t\tthis.deletedSessionId = sessionId;\n\t\t\tthis.connectionId = undefined;\n\t\t\tthis.pendingEntries = [];\n\t\t\tthis.liveMessage = null;\n\t\t\tthis.tools.clear();\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = undefined;\n\t\t\tclearTimeout(this.reconnectTimer);\n\t\t\tthis.reconnectTimer = undefined;\n\t\t}\n\t\tcontroller.abort();\n\t}\n\n\tprivate request(signal: AbortSignal): ChunkRequest {\n\t\treturn new ChunkRequest({\n\t\t\tserverUrl: process.env.PI_SERVER_URL ?? \"http://127.0.0.1:4217\",\n\t\t\tauthToken: process.env.PI_SERVER_AUTH_TOKEN ?? \"\",\n\t\t\tsignal,\n\t\t});\n\t}\n\n\tprivate async connect(): Promise<void> {\n\t\tif (this.disposed || this.deletedSessionId === this.session.sessionId) return;\n\t\tthis.syncActivity();\n\t\tconst controller = new AbortController();\n\t\tthis.controller = controller;\n\t\tconst sessionId = this.session.sessionId;\n\t\tthis.connectedSessionId = sessionId;\n\t\tlet resolveConnection: (() => void) | undefined;\n\t\tthis.connectionReady = new Promise<void>((resolve) => {\n\t\t\tresolveConnection = resolve;\n\t\t});\n\t\tconst timeout = setTimeout(() => controller.abort(new Error(\"connection timed out\")), 10000);\n\t\ttimeout.unref();\n\t\ttry {\n\t\t\tconst response = await this.request(controller.signal).getJson(\n\t\t\t\t`/api/observer/connect?sessionId=${encodeURIComponent(sessionId)}`,\n\t\t\t);\n\t\t\tif (response.status === 410) {\n\t\t\t\tthis.stopDeletedSession(sessionId, controller);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok || !response.headers.get(\"content-type\")?.includes(\"text/event-stream\") || !response.body) {\n\t\t\t\tthrow new Error(`connection failed (HTTP ${response.status})`);\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\t\t\tlet event = \"\";\n\t\t\ttry {\n\t\t\t\twhile (!this.disposed) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) throw new Error(\"connection closed\");\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet newline = buffer.indexOf(\"\\n\");\n\t\t\t\t\twhile (newline !== -1) {\n\t\t\t\t\t\tconst line = buffer.slice(0, newline).replace(/\\r$/, \"\");\n\t\t\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\t\t\tif (line.startsWith(\"event:\")) event = line.slice(6).trim();\n\t\t\t\t\t\tif (event === \"deleted\" && line.startsWith(\"data:\")) {\n\t\t\t\t\t\t\tthis.stopDeletedSession(sessionId, controller);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event === \"connected\" && !this.connectionId && line.startsWith(\"data:\")) {\n\t\t\t\t\t\t\tconst connected = JSON.parse(line.slice(5)) as { connectionId: string };\n\t\t\t\t\t\t\tthis.connectionId = connected.connectionId;\n\t\t\t\t\t\t\tthis.sequence = 0;\n\t\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\t\tthis.replace = true;\n\t\t\t\t\t\t\tthis.historyDirty = true;\n\t\t\t\t\t\t\tthis.dirty = true;\n\t\t\t\t\t\t\tthis.schedule(0);\n\t\t\t\t\t\t\tresolveConnection?.();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewline = buffer.indexOf(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait reader.cancel();\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (sessionId === this.session.sessionId && this.deletedSessionId !== sessionId) this.reportError(error);\n\t\t} finally {\n\t\t\tresolveConnection?.();\n\t\t\tclearTimeout(timeout);\n\t\t\tcontroller.abort();\n\t\t\tif (this.controller === controller) this.connectionId = undefined;\n\t\t\tif (this.controller === controller && !this.disposed && !this.closing && this.deletedSessionId !== sessionId) {\n\t\t\t\tthis.reconnectTimer = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.reconnectTimer = undefined;\n\t\t\t\t\t\tvoid this.connect();\n\t\t\t\t\t},\n\t\t\t\t\tsessionId === this.session.sessionId ? 2000 : 0,\n\t\t\t\t);\n\t\t\t\tthis.reconnectTimer.unref();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate flush(): Promise<void> {\n\t\tif (this.flushPromise) return this.flushPromise;\n\t\tconst promise = this.sendUpdate();\n\t\tthis.flushPromise = promise;\n\t\tvoid promise.finally(() => {\n\t\t\tthis.flushPromise = undefined;\n\t\t});\n\t\treturn promise;\n\t}\n\n\tprivate async sendUpdate(): Promise<void> {\n\t\tconst connectionId = this.connectionId;\n\t\tconst sessionId = this.connectedSessionId;\n\t\tconst controller = this.controller;\n\t\tif (\n\t\t\t!connectionId ||\n\t\t\t!sessionId ||\n\t\t\tsessionId !== this.session.sessionId ||\n\t\t\t!controller ||\n\t\t\tthis.disposed ||\n\t\t\tthis.deletedSessionId === sessionId ||\n\t\t\tthis.sending ||\n\t\t\t!this.dirty\n\t\t)\n\t\t\treturn;\n\t\tthis.sending = true;\n\t\tthis.dirty = false;\n\t\ttry {\n\t\t\tconst branch = this.historyDirty ? this.session.sessionManager.getBranch() : undefined;\n\t\t\tconst sentIndex = branch && this.sentEntryId ? branch.findIndex((entry) => entry.id === this.sentEntryId) : -1;\n\t\t\tconst replace = this.replace || (branch !== undefined && this.sentEntryId !== undefined && sentIndex === -1);\n\t\t\tthis.historyDirty = false;\n\t\t\tthis.replace = false;\n\t\t\tconst entries = branch ? (replace ? branch : branch.slice(sentIndex + 1)) : this.pendingEntries;\n\t\t\tthis.pendingEntries = [];\n\t\t\tconst messages = projectObserverEntries(entries);\n\t\t\tif (replace) this.firstUserTitle = \"\";\n\t\t\tif (!this.firstUserTitle) {\n\t\t\t\tconst firstUserContent = messages.find((message) => message.role === \"user\")?.content;\n\t\t\t\tthis.firstUserTitle = (\n\t\t\t\t\ttypeof firstUserContent === \"string\"\n\t\t\t\t\t\t? firstUserContent\n\t\t\t\t\t\t: (firstUserContent\n\t\t\t\t\t\t\t\t?.filter((part) => part.type === \"text\")\n\t\t\t\t\t\t\t\t.map((part) => part.text)\n\t\t\t\t\t\t\t\t.join(\"\") ?? \"\")\n\t\t\t\t).slice(0, 120);\n\t\t\t}\n\t\t\tconst update: ObserverUpdate = {\n\t\t\t\tsessionId,\n\t\t\t\tconnectionId,\n\t\t\t\tsequence: ++this.sequence,\n\t\t\t\tcwd: this.session.sessionManager.getCwd(),\n\t\t\t\ttitle: this.session.sessionManager.getSessionName() ?? this.firstUserTitle,\n\t\t\t\tlastActiveAt: this.lastActiveAt,\n\t\t\t\t...(replace ? { replace: messages } : messages.length ? { append: messages } : {}),\n\t\t\t\tstatus: this.session.isIdle ? \"idle\" : \"running\",\n\t\t\t\tlive: {\n\t\t\t\t\tmessage: this.liveMessage ? (projectMessage(this.liveMessageId, this.liveMessage) ?? null) : null,\n\t\t\t\t\ttools: [...this.tools.values()],\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst response = await this.request(controller.signal).postJson(\"/api/observer\", update);\n\t\t\tif (response.status === 410) {\n\t\t\t\tthis.stopDeletedSession(sessionId, controller);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) throw new Error(`update failed (HTTP ${response.status})`);\n\t\t\tconst result = (await response.json()) as { accepted: boolean };\n\t\t\tif (!result.accepted) throw new Error(\"update was not accepted\");\n\t\t\tif (sessionId !== this.session.sessionId) return;\n\t\t\tif (entries.length > 0) this.sentEntryId = entries.at(-1)?.id;\n\t\t\telse if (replace) this.sentEntryId = undefined;\n\t\t\tif (this.disconnected) {\n\t\t\t\tthis.disconnected = false;\n\t\t\t\tconsole.error(\"pi-server observer connected\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (sessionId === this.session.sessionId && this.deletedSessionId !== sessionId) this.reportError(error);\n\t\t\tcontroller.abort();\n\t\t} finally {\n\t\t\tthis.sending = false;\n\t\t\tthis.schedule(80);\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tthis.closePromise ??= this.drainAndClose();\n\t\treturn this.closePromise;\n\t}\n\n\tprivate async drainAndClose(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tthis.closing = true;\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = undefined;\n\t\tclearTimeout(this.reconnectTimer);\n\t\ttry {\n\t\t\tawait raceWithAbortSignal(\n\t\t\t\t(async () => {\n\t\t\t\t\tif (this.deletedSessionId === this.session.sessionId) return;\n\t\t\t\t\tif (!this.connectionId && this.controller?.signal.aborted) void this.connect();\n\t\t\t\t\tawait this.connectionReady;\n\t\t\t\t\tawait this.flushPromise;\n\t\t\t\t\tif (!this.connectionId) throw new Error(\"final transcript was not delivered: observer is disconnected\");\n\t\t\t\t\twhile (this.dirty && this.connectionId && !this.disposed) await this.flush();\n\t\t\t\t\tif (this.controller?.signal.aborted && this.deletedSessionId !== this.session.sessionId)\n\t\t\t\t\t\tthrow new Error(\"final transcript was not delivered: observer update failed\");\n\t\t\t\t})(),\n\t\t\t\tAbortSignal.timeout(10000),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconsole.error(`pi-server observer shutdown failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t} finally {\n\t\t\tthis.dispose();\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.unsubscribe();\n\t\tclearTimeout(this.timer);\n\t\tclearTimeout(this.reconnectTimer);\n\t\tthis.controller?.abort();\n\t\tobservers.delete(this.session);\n\t}\n}\n"]}
1
+ {"version":3,"file":"pi-server-observer.js","sourceRoot":"","sources":["../../src/core/pi-server-observer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAGtD,MAAM,SAAS,GAAG,IAAI,OAAO,EAAkC,CAAC;AAEhE,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,OAAqB;IAChE,MAAM,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC;AACvC,CAAC;AAsCD,SAAS,SAAS,CAAC,SAA6B;IAC/C,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAClD,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,IA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,IAAI,CAAC,OAAO,EAAE,CAAC;QAChB,CAAC;IACF,CAAC;IAED,OAAO;QACN,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,WAAW,EAAE,CAAC;QACnB,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzB,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAClC,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC;QACzB,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent, TextSignatureV1, ThinkingContent, ToolCall } from \"@earendil-works/pi-ai\";\nimport { raceWithAbortSignal } from \"../utils/abort.ts\";\nimport type { AgentSession, AgentSessionEvent } from \"./agent-session.ts\";\nimport { bashExecutionToText } from \"./messages.ts\";\nimport { ChunkRequest } from \"./pi-server-request.ts\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nconst observers = new WeakMap<AgentSession, PiServerObserver>();\n\nexport async function closePiServerObserver(session: AgentSession): Promise<void> {\n\tawait observers.get(session)?.close();\n}\n\ntype ViewerContent =\n\t| { type: \"text\"; text: string; phase?: TextSignatureV1[\"phase\"] }\n\t| { type: \"thinking\"; thinking: string }\n\t| { type: \"toolCall\"; id: string; name: string; arguments: unknown }\n\t| { type: \"attachment\"; label: string };\n\nexport interface ObserverMessage {\n\tid: string;\n\trole: string;\n\tcontent: string | ViewerContent[];\n\ttimestamp: number;\n\tstopReason?: string;\n\tphase?: string;\n\terrorMessage?: string;\n}\n\ninterface ObserverTool {\n\tid: string;\n\tname: string;\n\targuments: unknown;\n\tresult?: unknown;\n\tstatus: \"running\" | \"completed\" | \"error\";\n}\n\nexport interface ObserverUpdate {\n\tsessionId: string;\n\tconnectionId: string;\n\tsequence: number;\n\tcwd: string;\n\ttitle: string;\n\treplace?: ObserverMessage[];\n\tappend?: ObserverMessage[];\n\tstatus: \"running\" | \"idle\";\n\tlive: { message: ObserverMessage | null; tools: ObserverTool[] };\n}\n\nfunction textPhase(signature: string | undefined): TextSignatureV1[\"phase\"] {\n\tif (!signature?.startsWith(\"{\")) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\tif (\n\t\t\tparsed.v === 1 &&\n\t\t\ttypeof parsed.id === \"string\" &&\n\t\t\t(parsed.phase === \"commentary\" || parsed.phase === \"final_answer\")\n\t\t)\n\t\t\treturn parsed.phase;\n\t} catch {\n\t\t// Provider signatures outside TextSignatureV1 have no display phase.\n\t}\n\treturn undefined;\n}\n\nfunction projectContent(\n\tcontent: string | (TextContent | ThinkingContent | ImageContent | ToolCall)[],\n): ObserverMessage[\"content\"] {\n\tif (typeof content === \"string\") return content;\n\treturn content.map((part): ViewerContent => {\n\t\tif (part.type === \"text\") return { type: \"text\", text: part.text, phase: textPhase(part.textSignature) };\n\t\tif (part.type === \"thinking\") return { type: \"thinking\", thinking: part.thinking };\n\t\tif (part.type === \"toolCall\")\n\t\t\treturn { type: \"toolCall\", id: part.id, name: part.name, arguments: part.arguments };\n\t\treturn { type: \"attachment\", label: part.mimeType };\n\t});\n}\n\nfunction projectMessage(id: string, message: AgentMessage, timestamp = message.timestamp): ObserverMessage | undefined {\n\tif (message.role === \"system\" || (message.role === \"custom\" && !message.display)) return undefined;\n\tlet content: ObserverMessage[\"content\"];\n\tif (message.role === \"bashExecution\") content = bashExecutionToText(message);\n\telse if (message.role === \"compactionSummary\" || message.role === \"branchSummary\") content = message.summary;\n\telse content = projectContent(message.content);\n\tconst projected: ObserverMessage = { id, role: message.role, content, timestamp };\n\tif (message.role === \"assistant\") {\n\t\tprojected.stopReason = message.stopReason;\n\t\tprojected.errorMessage = message.errorMessage;\n\t\tfor (const part of message.content) {\n\t\t\tconst phase = part.type === \"text\" ? textPhase(part.textSignature) : undefined;\n\t\t\tif (phase) projected.phase = phase;\n\t\t}\n\t}\n\treturn projected;\n}\n\nexport function projectObserverEntries(entries: SessionEntry[]): ObserverMessage[] {\n\tconst messages: ObserverMessage[] = [];\n\tfor (const entry of entries) {\n\t\tlet message: ObserverMessage | undefined;\n\t\tif (entry.type === \"message\") message = projectMessage(entry.id, entry.message, Date.parse(entry.timestamp));\n\t\telse if (entry.type === \"custom_message\" && entry.display) {\n\t\t\tmessage = {\n\t\t\t\tid: entry.id,\n\t\t\t\trole: \"custom\",\n\t\t\t\tcontent: projectContent(entry.content),\n\t\t\t\ttimestamp: Date.parse(entry.timestamp),\n\t\t\t};\n\t\t} else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\tmessage = { id: entry.id, role: entry.type, content: entry.summary, timestamp: Date.parse(entry.timestamp) };\n\t\t}\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\n/** Publishes transcript updates independently of provider requests and durable server trees. */\nexport class PiServerObserver {\n\tprivate readonly session: AgentSession;\n\tprivate readonly unsubscribe: () => void;\n\tprivate controller?: AbortController;\n\tprivate timer?: ReturnType<typeof setTimeout>;\n\tprivate reconnectTimer?: ReturnType<typeof setTimeout>;\n\tprivate disposed = false;\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate connectionReady?: Promise<void>;\n\tprivate deletedSessionId?: string;\n\tprivate connectionId?: string;\n\tprivate connectedSessionId?: string;\n\tprivate sequence = 0;\n\tprivate sending = false;\n\tprivate flushPromise?: Promise<void>;\n\tprivate dirty = true;\n\tprivate historyDirty = true;\n\tprivate replace = true;\n\tprivate sentEntryId?: string;\n\tprivate pendingEntries: SessionEntry[] = [];\n\tprivate firstUserTitle = \"\";\n\tprivate liveMessage: AgentMessage | null = null;\n\tprivate liveMessageId = \"\";\n\tprivate readonly tools = new Map<string, ObserverTool>();\n\tprivate disconnected = false;\n\tprivate observedSessionId?: string;\n\n\tconstructor(session: AgentSession) {\n\t\tthis.session = session;\n\t\tthis.syncSession();\n\t\tobservers.set(session, this);\n\t\tthis.unsubscribe = session.subscribe((event) => {\n\t\t\ttry {\n\t\t\t\tthis.handleEvent(event);\n\t\t\t} catch (error) {\n\t\t\t\tthis.reportError(error);\n\t\t\t}\n\t\t});\n\t\tvoid this.connect();\n\t}\n\n\tprivate handleEvent(event: AgentSessionEvent): void {\n\t\tthis.syncSession();\n\t\tswitch (event.type) {\n\t\t\tcase \"session_disposed\":\n\t\t\t\tthis.dispose();\n\t\t\t\treturn;\n\t\t\tcase \"run_state_changed\":\n\t\t\t\tif (!event.running) {\n\t\t\t\t\tthis.liveMessage = null;\n\t\t\t\t\tthis.tools.clear();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\t\tif (event.message.role !== \"assistant\") return;\n\t\t\t\tthis.tools.clear();\n\t\t\t\tthis.liveMessageId = randomUUID();\n\t\t\t\tthis.liveMessage = event.message;\n\t\t\t\tbreak;\n\t\t\tcase \"message_update\":\n\t\t\t\tthis.liveMessage = event.message;\n\t\t\t\tbreak;\n\t\t\tcase \"entry_appended\":\n\t\t\tcase \"message_committed\":\n\t\t\t\tif (this.connectionId && !this.historyDirty) {\n\t\t\t\t\tthis.pendingEntries.push(event.entry);\n\t\t\t\t\tif (this.pendingEntries.length > 64) {\n\t\t\t\t\t\tthis.pendingEntries = [];\n\t\t\t\t\t\tthis.historyDirty = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (event.entry.type === \"message\" && event.entry.message.role === \"assistant\") this.liveMessage = null;\n\t\t\t\tbreak;\n\t\t\tcase \"history_reconciled\":\n\t\t\tcase \"session_tree_changed\":\n\t\t\t\tif (this.deletedSessionId && this.deletedSessionId !== this.session.sessionId) {\n\t\t\t\t\tthis.deletedSessionId = undefined;\n\t\t\t\t\tvoid this.connect();\n\t\t\t\t}\n\t\t\t\tif (this.connectedSessionId && this.connectedSessionId !== this.session.sessionId) {\n\t\t\t\t\tthis.connectionId = undefined;\n\t\t\t\t\tthis.controller?.abort();\n\t\t\t\t}\n\t\t\t\tthis.replace = true;\n\t\t\t\tthis.historyDirty = true;\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_end\":\n\t\t\t\tthis.historyDirty = true;\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_start\":\n\t\t\t\tbreak;\n\t\t\tcase \"session_info_changed\":\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.tools.set(event.toolCallId, {\n\t\t\t\t\tid: event.toolCallId,\n\t\t\t\t\tname: event.toolName,\n\t\t\t\t\targuments: event.args,\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_update\": {\n\t\t\t\tconst tool = this.tools.get(event.toolCallId);\n\t\t\t\tif (tool) tool.result = { content: projectContent(event.partialResult.content) };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst tool = this.tools.get(event.toolCallId);\n\t\t\t\tif (tool) {\n\t\t\t\t\ttool.result = { content: projectContent(event.result.content), isError: event.isError };\n\t\t\t\t\ttool.status = event.isError ? \"error\" : \"completed\";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\t\tthis.dirty = true;\n\t\tthis.schedule(\n\t\t\tevent.type === \"run_state_changed\" || event.type === \"compaction_start\" || event.type === \"compaction_end\"\n\t\t\t\t? 0\n\t\t\t\t: 80,\n\t\t);\n\t}\n\n\tprivate syncSession(): void {\n\t\tif (this.observedSessionId === this.session.sessionId) return;\n\t\tthis.observedSessionId = this.session.sessionId;\n\t\tthis.sentEntryId = undefined;\n\t\tthis.pendingEntries = [];\n\t\tthis.firstUserTitle = \"\";\n\t\tthis.liveMessage = null;\n\t\tthis.tools.clear();\n\t}\n\n\tprivate schedule(delay: number): void {\n\t\tif (\n\t\t\tthis.disposed ||\n\t\t\tthis.closing ||\n\t\t\tthis.deletedSessionId === this.session.sessionId ||\n\t\t\t!this.dirty ||\n\t\t\t!this.connectionId ||\n\t\t\tthis.sending ||\n\t\t\tthis.timer\n\t\t)\n\t\t\treturn;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = undefined;\n\t\t\tvoid this.flush();\n\t\t}, delay);\n\t\tthis.timer.unref();\n\t}\n\n\tprivate reportError(error: unknown): void {\n\t\tif (this.disposed || this.disconnected) return;\n\t\tthis.disconnected = true;\n\t\tconsole.error(`pi-server observer disconnected: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\n\tprivate stopDeletedSession(sessionId: string, controller: AbortController): void {\n\t\tif (sessionId === this.session.sessionId) {\n\t\t\tthis.deletedSessionId = sessionId;\n\t\t\tthis.connectionId = undefined;\n\t\t\tthis.pendingEntries = [];\n\t\t\tthis.liveMessage = null;\n\t\t\tthis.tools.clear();\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = undefined;\n\t\t\tclearTimeout(this.reconnectTimer);\n\t\t\tthis.reconnectTimer = undefined;\n\t\t}\n\t\tcontroller.abort();\n\t}\n\n\tprivate request(signal: AbortSignal): ChunkRequest {\n\t\treturn new ChunkRequest({\n\t\t\tserverUrl: process.env.PI_SERVER_URL ?? \"http://127.0.0.1:4217\",\n\t\t\tauthToken: process.env.PI_SERVER_AUTH_TOKEN ?? \"\",\n\t\t\tsignal,\n\t\t});\n\t}\n\n\tprivate async connect(): Promise<void> {\n\t\tif (this.disposed || this.deletedSessionId === this.session.sessionId) return;\n\t\tthis.syncSession();\n\t\tconst controller = new AbortController();\n\t\tthis.controller = controller;\n\t\tconst sessionId = this.session.sessionId;\n\t\tthis.connectedSessionId = sessionId;\n\t\tlet resolveConnection: (() => void) | undefined;\n\t\tthis.connectionReady = new Promise<void>((resolve) => {\n\t\t\tresolveConnection = resolve;\n\t\t});\n\t\tconst timeout = setTimeout(() => controller.abort(new Error(\"connection timed out\")), 10000);\n\t\ttimeout.unref();\n\t\ttry {\n\t\t\tconst response = await this.request(controller.signal).getJson(\n\t\t\t\t`/api/observer/connect?sessionId=${encodeURIComponent(sessionId)}`,\n\t\t\t);\n\t\t\tif (response.status === 410) {\n\t\t\t\tthis.stopDeletedSession(sessionId, controller);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok || !response.headers.get(\"content-type\")?.includes(\"text/event-stream\") || !response.body) {\n\t\t\t\tthrow new Error(`connection failed (HTTP ${response.status})`);\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\t\t\tlet event = \"\";\n\t\t\ttry {\n\t\t\t\twhile (!this.disposed) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) throw new Error(\"connection closed\");\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet newline = buffer.indexOf(\"\\n\");\n\t\t\t\t\twhile (newline !== -1) {\n\t\t\t\t\t\tconst line = buffer.slice(0, newline).replace(/\\r$/, \"\");\n\t\t\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\t\t\tif (line.startsWith(\"event:\")) event = line.slice(6).trim();\n\t\t\t\t\t\tif (event === \"deleted\" && line.startsWith(\"data:\")) {\n\t\t\t\t\t\t\tthis.stopDeletedSession(sessionId, controller);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event === \"connected\" && !this.connectionId && line.startsWith(\"data:\")) {\n\t\t\t\t\t\t\tconst connected = JSON.parse(line.slice(5)) as { connectionId: string };\n\t\t\t\t\t\t\tthis.connectionId = connected.connectionId;\n\t\t\t\t\t\t\tthis.sequence = 0;\n\t\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\t\tthis.replace = true;\n\t\t\t\t\t\t\tthis.historyDirty = true;\n\t\t\t\t\t\t\tthis.dirty = true;\n\t\t\t\t\t\t\tthis.schedule(0);\n\t\t\t\t\t\t\tresolveConnection?.();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewline = buffer.indexOf(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait reader.cancel();\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (sessionId === this.session.sessionId && this.deletedSessionId !== sessionId) this.reportError(error);\n\t\t} finally {\n\t\t\tresolveConnection?.();\n\t\t\tclearTimeout(timeout);\n\t\t\tcontroller.abort();\n\t\t\tif (this.controller === controller) this.connectionId = undefined;\n\t\t\tif (this.controller === controller && !this.disposed && !this.closing && this.deletedSessionId !== sessionId) {\n\t\t\t\tthis.reconnectTimer = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.reconnectTimer = undefined;\n\t\t\t\t\t\tvoid this.connect();\n\t\t\t\t\t},\n\t\t\t\t\tsessionId === this.session.sessionId ? 2000 : 0,\n\t\t\t\t);\n\t\t\t\tthis.reconnectTimer.unref();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate flush(): Promise<void> {\n\t\tif (this.flushPromise) return this.flushPromise;\n\t\tconst promise = this.sendUpdate();\n\t\tthis.flushPromise = promise;\n\t\tvoid promise.finally(() => {\n\t\t\tthis.flushPromise = undefined;\n\t\t});\n\t\treturn promise;\n\t}\n\n\tprivate async sendUpdate(): Promise<void> {\n\t\tconst connectionId = this.connectionId;\n\t\tconst sessionId = this.connectedSessionId;\n\t\tconst controller = this.controller;\n\t\tif (\n\t\t\t!connectionId ||\n\t\t\t!sessionId ||\n\t\t\tsessionId !== this.session.sessionId ||\n\t\t\t!controller ||\n\t\t\tthis.disposed ||\n\t\t\tthis.deletedSessionId === sessionId ||\n\t\t\tthis.sending ||\n\t\t\t!this.dirty\n\t\t)\n\t\t\treturn;\n\t\tthis.sending = true;\n\t\tthis.dirty = false;\n\t\ttry {\n\t\t\tconst branch = this.historyDirty ? this.session.sessionManager.getBranch() : undefined;\n\t\t\tconst sentIndex = branch && this.sentEntryId ? branch.findIndex((entry) => entry.id === this.sentEntryId) : -1;\n\t\t\tconst replace = this.replace || (branch !== undefined && this.sentEntryId !== undefined && sentIndex === -1);\n\t\t\tthis.historyDirty = false;\n\t\t\tthis.replace = false;\n\t\t\tconst entries = branch ? (replace ? branch : branch.slice(sentIndex + 1)) : this.pendingEntries;\n\t\t\tthis.pendingEntries = [];\n\t\t\tconst messages = projectObserverEntries(entries);\n\t\t\tif (replace) this.firstUserTitle = \"\";\n\t\t\tif (!this.firstUserTitle) {\n\t\t\t\tconst firstUserContent = messages.find((message) => message.role === \"user\")?.content;\n\t\t\t\tthis.firstUserTitle = (\n\t\t\t\t\ttypeof firstUserContent === \"string\"\n\t\t\t\t\t\t? firstUserContent\n\t\t\t\t\t\t: (firstUserContent\n\t\t\t\t\t\t\t\t?.filter((part) => part.type === \"text\")\n\t\t\t\t\t\t\t\t.map((part) => part.text)\n\t\t\t\t\t\t\t\t.join(\"\") ?? \"\")\n\t\t\t\t).slice(0, 120);\n\t\t\t}\n\t\t\tconst update: ObserverUpdate = {\n\t\t\t\tsessionId,\n\t\t\t\tconnectionId,\n\t\t\t\tsequence: ++this.sequence,\n\t\t\t\tcwd: this.session.sessionManager.getCwd(),\n\t\t\t\ttitle: this.session.sessionManager.getSessionName() ?? this.firstUserTitle,\n\t\t\t\t...(replace ? { replace: messages } : messages.length ? { append: messages } : {}),\n\t\t\t\tstatus: this.session.isIdle ? \"idle\" : \"running\",\n\t\t\t\tlive: {\n\t\t\t\t\tmessage: this.liveMessage ? (projectMessage(this.liveMessageId, this.liveMessage) ?? null) : null,\n\t\t\t\t\ttools: [...this.tools.values()],\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst response = await this.request(controller.signal).postJson(\"/api/observer\", update);\n\t\t\tif (response.status === 410) {\n\t\t\t\tthis.stopDeletedSession(sessionId, controller);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) throw new Error(`update failed (HTTP ${response.status})`);\n\t\t\tconst result = (await response.json()) as { accepted: boolean };\n\t\t\tif (!result.accepted) throw new Error(\"update was not accepted\");\n\t\t\tif (sessionId !== this.session.sessionId) return;\n\t\t\tif (entries.length > 0) this.sentEntryId = entries.at(-1)?.id;\n\t\t\telse if (replace) this.sentEntryId = undefined;\n\t\t\tif (this.disconnected) {\n\t\t\t\tthis.disconnected = false;\n\t\t\t\tconsole.error(\"pi-server observer connected\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (sessionId === this.session.sessionId && this.deletedSessionId !== sessionId) this.reportError(error);\n\t\t\tcontroller.abort();\n\t\t} finally {\n\t\t\tthis.sending = false;\n\t\t\tthis.schedule(80);\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tthis.closePromise ??= this.drainAndClose();\n\t\treturn this.closePromise;\n\t}\n\n\tprivate async drainAndClose(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tthis.closing = true;\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = undefined;\n\t\tclearTimeout(this.reconnectTimer);\n\t\ttry {\n\t\t\tawait raceWithAbortSignal(\n\t\t\t\t(async () => {\n\t\t\t\t\tif (this.deletedSessionId === this.session.sessionId) return;\n\t\t\t\t\tif (!this.connectionId && this.controller?.signal.aborted) void this.connect();\n\t\t\t\t\tawait this.connectionReady;\n\t\t\t\t\tawait this.flushPromise;\n\t\t\t\t\tif (!this.connectionId) throw new Error(\"final transcript was not delivered: observer is disconnected\");\n\t\t\t\t\twhile (this.dirty && this.connectionId && !this.disposed) await this.flush();\n\t\t\t\t\tif (this.controller?.signal.aborted && this.deletedSessionId !== this.session.sessionId)\n\t\t\t\t\t\tthrow new Error(\"final transcript was not delivered: observer update failed\");\n\t\t\t\t})(),\n\t\t\t\tAbortSignal.timeout(10000),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconsole.error(`pi-server observer shutdown failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t} finally {\n\t\t\tthis.dispose();\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.unsubscribe();\n\t\tclearTimeout(this.timer);\n\t\tclearTimeout(this.reconnectTimer);\n\t\tthis.controller?.abort();\n\t\tobservers.delete(this.session);\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@averyyy/pi-coding-agent",
3
- "version": "1.4.0-piclient.7",
3
+ "version": "1.4.0-piclient.9",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {
@@ -48,11 +48,11 @@
48
48
  "prepublishOnly": "npm run clean && npm run build"
49
49
  },
50
50
  "dependencies": {
51
- "@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@1.4.0-piclient.7",
52
- "@earendil-works/pi-ai": "npm:@averyyy/pi-ai@1.4.0-piclient.7",
51
+ "@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@1.4.0-piclient.9",
52
+ "@earendil-works/pi-ai": "npm:@averyyy/pi-ai@1.4.0-piclient.9",
53
53
  "@earendil-works/pi-codemode": "1.4.0",
54
54
  "@earendil-works/pi-mcp": "1.4.0",
55
- "@earendil-works/pi-tui": "npm:@averyyy/pi-tui@1.4.0-piclient.7",
55
+ "@earendil-works/pi-tui": "npm:@averyyy/pi-tui@1.4.0-piclient.9",
56
56
  "@silvia-odwyer/photon-node": "0.3.4",
57
57
  "brace-expansion": "5.0.12",
58
58
  "chalk": "6.0.0",