@code-yeongyu/senpi 2026.9.26 → 2026.9.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/dist/bun-runtime.d.ts +18 -2
- package/dist/bun-runtime.d.ts.map +1 -1
- package/dist/bun-runtime.js +60 -8
- package/dist/bun-runtime.js.map +1 -1
- package/dist/bundle/chunks/{app-server-command-ZRCKWY2X.js → app-server-command-7WEJGW7D.js} +1 -1
- package/dist/bundle/chunks/bun-extension-importer-R4HXF3GD.js +14 -0
- package/dist/bundle/chunks/{chunk-QGC46CGK.js → chunk-3QCAGZFO.js} +17 -16
- package/dist/bundle/chunks/chunk-HCXLCGMF.js +8 -0
- package/dist/bundle/chunks/{chunk-OZCB6BP3.js → chunk-HH3D5ZYA.js} +3 -3
- package/dist/bundle/chunks/chunk-W3D3ZYDS.js +2 -0
- package/dist/bundle/chunks/{cli-main-H6JAXAXV.js → cli-main-YLZ4MMLV.js} +1 -1
- package/dist/bundle/chunks/{interactive-host-runtime-YI75GFD5.js → interactive-host-runtime-6WY6424X.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-HM7UQYRC.js → interactive-mode-6AHR5TEM.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-7YX2I7UK.js → multi-session-host-5IWJEFDF.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-3ISYTEL2.js → package-manager-cli-FZKBCLWV.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-6PY4TN5F.js → rpc-mode-JSCHAE6O.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +117 -116
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +10 -5
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/bun-extension-importer.d.ts.map +1 -1
- package/dist/core/extensions/bun-extension-importer.js +10 -4
- package/dist/core/extensions/bun-extension-importer.js.map +1 -1
- package/dist/core/extensions/bun-extension-registry.js +6 -5
- package/dist/core/extensions/bun-extension-registry.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +4 -2
- package/dist/core/messages.js.map +1 -1
- package/dist/core/provider-rejected-images.d.ts +18 -0
- package/dist/core/provider-rejected-images.d.ts.map +1 -0
- package/dist/core/provider-rejected-images.js +107 -0
- package/dist/core/provider-rejected-images.js.map +1 -0
- package/dist/core/session-title-generator.d.ts.map +1 -1
- package/dist/core/session-title-generator.js +21 -3
- package/dist/core/session-title-generator.js.map +1 -1
- package/dist/core/session-title-reasoning.d.ts +14 -0
- package/dist/core/session-title-reasoning.d.ts.map +1 -0
- package/dist/core/session-title-reasoning.js +31 -0
- package/dist/core/session-title-reasoning.js.map +1 -0
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js +13 -0
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +2 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/runtime-notice-presenter.d.ts +8 -0
- package/dist/modes/interactive/runtime-notice-presenter.d.ts.map +1 -0
- package/dist/modes/interactive/runtime-notice-presenter.js +69 -0
- package/dist/modes/interactive/runtime-notice-presenter.js.map +1 -0
- package/dist/modes/interactive/runtime-notice.d.ts +50 -0
- package/dist/modes/interactive/runtime-notice.d.ts.map +1 -0
- package/dist/modes/interactive/runtime-notice.js +104 -0
- package/dist/modes/interactive/runtime-notice.js.map +1 -0
- package/docs/environment-variables.md +2 -0
- package/docs/quickstart.md +7 -1
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/native/prebuilds/darwin-arm64/senpi_pty.darwin-arm64.node +0 -0
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
- package/dist/bundle/chunks/bun-extension-importer-H4IJCWWQ.js +0 -14
- package/dist/bundle/chunks/chunk-34HMVB33.js +0 -2
- package/dist/bundle/chunks/chunk-T3JBT2IK.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
2
|
import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-3WBSBDBX.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-UBPMXBOJ.js";import{sanitizeBinaryOutput}from"./chunk-FHXKBENX.js";import{dropFailedAssistantTurns}from"./chunk-KMJXSXRX.js";import{copyContextProvenance}from"./chunk-ELFCNCBY.js";import{APP_NAME,getAgentDir,getSessionsDir,normalizePath,resolvePath}from"./chunk-Y65WFI5H.js";import{normalizeProviderId}from"./chunk-WL5EQYNL.js";var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context";function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
3
|
-
`)}function isEnvironmentContext(value){if(typeof value!="object"||value===null)return!1;let candidate=value;return typeof candidate.cwd=="string"&&typeof candidate.currentDate=="string"}function latestEnvironmentContext(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="custom"&&message.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&isEnvironmentContext(message.details))return message.details}}function createEnvironmentContextMessage(context,timestamp=Date.now()){return{role:"custom",customType:ENVIRONMENT_CONTEXT_MESSAGE_TYPE,content:formatEnvironmentContext(context),display:!1,details:{cwd:context.cwd,currentDate:context.currentDate},timestamp}}function environmentContextMessageIfChanged(messages,current){let latest=latestEnvironmentContext(messages);if(!(latest?.cwd===current.cwd&&latest.currentDate===current.currentDate))return createEnvironmentContextMessage(current)}function contentBlocks(content){return typeof content=="string"?[{type:"text",text:content}]:content}function foldEnvironmentContextIntoNextUserMessage(messages,environmentMessages){let folded=[];for(let index=0;index<messages.length;index++){let message=messages[index],next=messages[index+1];if(environmentMessages.has(message)&&message.role==="user"&&next?.role==="user"&&!environmentMessages.has(next)){folded.push({...next,content:[...contentBlocks(message.content),...contentBlocks(next.content)]}),index++;continue}folded.push(message)}return folded}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
3
|
+
`)}function isEnvironmentContext(value){if(typeof value!="object"||value===null)return!1;let candidate=value;return typeof candidate.cwd=="string"&&typeof candidate.currentDate=="string"}function latestEnvironmentContext(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="custom"&&message.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&isEnvironmentContext(message.details))return message.details}}function createEnvironmentContextMessage(context,timestamp=Date.now()){return{role:"custom",customType:ENVIRONMENT_CONTEXT_MESSAGE_TYPE,content:formatEnvironmentContext(context),display:!1,details:{cwd:context.cwd,currentDate:context.currentDate},timestamp}}function environmentContextMessageIfChanged(messages,current){let latest=latestEnvironmentContext(messages);if(!(latest?.cwd===current.cwd&&latest.currentDate===current.currentDate))return createEnvironmentContextMessage(current)}function contentBlocks(content){return typeof content=="string"?[{type:"text",text:content}]:content}function foldEnvironmentContextIntoNextUserMessage(messages,environmentMessages){let folded=[];for(let index=0;index<messages.length;index++){let message=messages[index],next=messages[index+1];if(environmentMessages.has(message)&&message.role==="user"&&next?.role==="user"&&!environmentMessages.has(next)){folded.push({...next,content:[...contentBlocks(message.content),...contentBlocks(next.content)]}),index++;continue}folded.push(message)}return folded}var PROVIDER_IMAGE_REJECTION_PATTERN=/does not represent a valid image|image_parse_error|invalid_image|unsupported image|could not process image|unable to process input image|image_url'?\.?[^\n]*invalid base64|expected a base64-encoded data url|image was specified using the image\/[a-z]+ media type|unsupported media type for base64 image|invalid data url for image/i;function isProviderImageRejection(errorMessage){return errorMessage!==void 0&&PROVIDER_IMAGE_REJECTION_PATTERN.test(errorMessage)}function rejectedImagePlaceholder(source){return`[Image omitted: the provider rejected this image (${source}) as invalid, so it is no longer sent with the conversation.]`}function field(message,key){return key in message?message[key]:void 0}function contentBlocks2(message){let content=field(message,"content");return Array.isArray(content)?content:[]}function toolCallSource(block){let args=block.arguments;if(typeof args!="object"||args===null)return;let record=args;for(let key of["path","file_path","filePath"]){let value=record[key];if(typeof value=="string"&&value.trim().length>0)return value}}function imageSource(message,toolCallSources){if(message.role!=="toolResult")return"an attached image";let toolCallId=field(message,"toolCallId"),known=typeof toolCallId=="string"?toolCallSources.get(toolCallId):void 0;if(known)return known;let toolName=field(message,"toolName");return typeof toolName=="string"?`${toolName} tool result`:"a tool result"}function scanRejectedImages(messages){let toolCallSources=new Map,rejections=new Map,unconfirmed=[];return messages.forEach((message,messageIndex)=>{if(message.role==="assistant"){for(let block of contentBlocks2(message)){let source=block.type==="toolCall"?toolCallSource(block):void 0;source&&typeof block.id=="string"&&toolCallSources.set(block.id,source)}let stopReason=field(message,"stopReason"),errorMessage=field(message,"errorMessage");stopReason==="error"&&isProviderImageRejection(typeof errorMessage=="string"?errorMessage:void 0)?(unconfirmed.length>0&&rejections.set(messageIndex,unconfirmed),unconfirmed=[]):stopReason!=="error"&&stopReason!=="aborted"&&(unconfirmed=[]);return}message.role!=="user"&&message.role!=="toolResult"||contentBlocks2(message).forEach((block,blockIndex)=>{block.type==="image"&&unconfirmed.push({messageIndex,blockIndex,source:imageSource(message,toolCallSources)})})}),rejections}function rejectedImageSources(messages,failedTurn){let failedIndex=messages.lastIndexOf(failedTurn);return(scanRejectedImages(messages).get(failedIndex)??[]).map(image=>image.source)}function omitProviderRejectedImages(messages){let rejected=new Map;for(let images of scanRejectedImages(messages).values())for(let image of images){let blocks=rejected.get(image.messageIndex)??new Map;blocks.set(image.blockIndex,image.source),rejected.set(image.messageIndex,blocks)}return rejected.size===0?messages:messages.map((message,messageIndex)=>{let blocks=rejected.get(messageIndex);if(!blocks)return message;let content=contentBlocks2(message).map((block,blockIndex)=>{let source=blocks.get(blockIndex);return source===void 0?block:{type:"text",text:rejectedImagePlaceholder(source)}});return{...message,content}})}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
4
4
|
|
|
5
5
|
<summary>
|
|
6
6
|
`,COMPACTION_SUMMARY_SUFFIX=`
|
|
@@ -16,7 +16,7 @@ ${msg.output}
|
|
|
16
16
|
|
|
17
17
|
Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
|
|
18
18
|
|
|
19
|
-
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(dropFailedAssistantTurns(converted),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,limitHistory=maxHistoricalImages!==void 0,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),imagesToElide=new Set,keptImages=0,keptHistoricalImages=0,imageBytes=0,cutoffReached=!1;for(let messageIndex=messages.length-1;messageIndex>=0;messageIndex--){let message=messages[messageIndex];if(!(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)))for(let blockIndex=message.content.length-1;blockIndex>=0;blockIndex--){let block=message.content[blockIndex];if(block.type!=="image")continue;let isCurrentTurn=limitHistory&&messageIndex>lastAssistantIndex,isProtectedHistory=limitHistory&&!isCurrentTurn&&keptHistoricalImages<maxHistoricalImages;if(limitHistory&&!isCurrentTurn&&!isProtectedHistory||cutoffReached&&!isCurrentTurn&&!isProtectedHistory){imagesToElide.add(`${messageIndex}:${blockIndex}`);continue}if(isCurrentTurn||isProtectedHistory||keptImages<alwaysKeepNewest||imageBytes+block.data.length<=budgetBytes){keptImages++,isCurrentTurn||keptHistoricalImages++,imageBytes+=block.data.length;continue}cutoffReached=!0,imagesToElide.add(`${messageIndex}:${blockIndex}`)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)))return message;let replaced=message.content.map((block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)?{type:"text",text:IMAGE_ELISION_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,IMAGE_ELISION_PLACEHOLDER)}})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync,readdirSync,readFileSync as readFileSync2,readSync,rmSync as rmSync2,statSync,writeFileSync as writeFileSync2}from"fs";import{readdir as readdir2}from"fs/promises";import{join as join4,resolve as resolve2}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";function parseEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isMessageWithContent(message){return typeof message=="object"&&message!==null&&typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function visibleMessage(entry){if(entry.type!=="message")return null;let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return null;let messageTime=message.timestamp,entryTime=Date.parse(entry.timestamp),time=typeof messageTime=="number"?messageTime:Number.isNaN(entryTime)?void 0:entryTime;return{text:extractTextContent(message),role:message.role,time}}function sessionInfoName(entry){return entry.type!=="session_info"?null:entry.name?.trim()||void 0}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
19
|
+
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(dropFailedAssistantTurns(omitProviderRejectedImages(converted)),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,limitHistory=maxHistoricalImages!==void 0,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),imagesToElide=new Set,keptImages=0,keptHistoricalImages=0,imageBytes=0,cutoffReached=!1;for(let messageIndex=messages.length-1;messageIndex>=0;messageIndex--){let message=messages[messageIndex];if(!(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)))for(let blockIndex=message.content.length-1;blockIndex>=0;blockIndex--){let block=message.content[blockIndex];if(block.type!=="image")continue;let isCurrentTurn=limitHistory&&messageIndex>lastAssistantIndex,isProtectedHistory=limitHistory&&!isCurrentTurn&&keptHistoricalImages<maxHistoricalImages;if(limitHistory&&!isCurrentTurn&&!isProtectedHistory||cutoffReached&&!isCurrentTurn&&!isProtectedHistory){imagesToElide.add(`${messageIndex}:${blockIndex}`);continue}if(isCurrentTurn||isProtectedHistory||keptImages<alwaysKeepNewest||imageBytes+block.data.length<=budgetBytes){keptImages++,isCurrentTurn||keptHistoricalImages++,imageBytes+=block.data.length;continue}cutoffReached=!0,imagesToElide.add(`${messageIndex}:${blockIndex}`)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)))return message;let replaced=message.content.map((block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)?{type:"text",text:IMAGE_ELISION_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,IMAGE_ELISION_PLACEHOLDER)}})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync,readdirSync,readFileSync as readFileSync2,readSync,rmSync as rmSync2,statSync,writeFileSync as writeFileSync2}from"fs";import{readdir as readdir2}from"fs/promises";import{join as join4,resolve as resolve2}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";function parseEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isMessageWithContent(message){return typeof message=="object"&&message!==null&&typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function visibleMessage(entry){if(entry.type!=="message")return null;let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return null;let messageTime=message.timestamp,entryTime=Date.parse(entry.timestamp),time=typeof messageTime=="number"?messageTime:Number.isNaN(entryTime)?void 0:entryTime;return{text:extractTextContent(message),role:message.role,time}}function sessionInfoName(entry){return entry.type!=="session_info"?null:entry.name?.trim()||void 0}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
20
20
|
`,searchFrom);for(;newlineIndex!==-1;){if(!emit(pending.slice(lineStart,newlineIndex)))return{completed:!1,bytes,endsWithNewline:!1};lineStart=newlineIndex+1,newlineIndex=pending.indexOf(`
|
|
21
21
|
`,lineStart)}pending=pending.slice(lineStart)}return pending+=decoder.end(),pending&&!emit(pending)?{completed:!1,bytes,endsWithNewline:!1}:{completed:!0,bytes,endsWithNewline:lastByte===10}}finally{await handle.close()}}async function readSessionSummary(filePath){let accumulator=newAccumulator();try{if(!(await readFileLines(filePath,line=>accumulateLine(accumulator,line))).completed)return null}catch(error){if(error instanceof Error)return null;throw error}let header=accumulator.header;return header?{header,name:accumulator.name,firstUserMessage:accumulator.firstUserMessage,messageCount:accumulator.messageCount,lastActivityTime:accumulator.lastActivityTime,allMessagesText:accumulator.texts.join(" ")}:null}import{stat}from"fs/promises";import{basename,join}from"path";import{appendFile,rename,rm,writeFile}from"fs/promises";var SESSION_SUMMARY_INDEX_FILE=".session-summaries.index",INDEX_VERSION=1,HEADER_LINE=`${JSON.stringify({version:INDEX_VERSION})}
|
|
22
22
|
`,UNUSABLE={usable:!1,entries:new Map,entryBytes:0,endsWithNewline:!0};function isObject(value){return typeof value=="object"&&value!==null}function isOptional(value,type){return value===void 0||typeof value===type}function isSessionSummary(value){return!isObject(value)||!isObject(value.header)?!1:value.header.type==="session"&&typeof value.header.id=="string"&&typeof value.firstUserMessage=="string"&&typeof value.messageCount=="number"&&typeof value.allMessagesText=="string"&&isOptional(value.name,"string")&&isOptional(value.lastActivityTime,"number")}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function toIndexEntry(file,stamp,summary){if(!(summary.lastActivityTime!==void 0&&!Number.isFinite(summary.lastActivityTime)))return withLine(file,stamp,summary,`${JSON.stringify({file,size:stamp.size,mtimeMs:stamp.mtimeMs,summary})}
|
|
@@ -44,4 +44,4 @@ Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCw
|
|
|
44
44
|
${issue.sessionCwd}
|
|
45
45
|
|
|
46
46
|
continue in current cwd
|
|
47
|
-
${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{spawn}from"node:child_process";import{createConnection}from"node:net";var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.options=options}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve3=>setTimeout(resolve3,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}async stop(){if(this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.process.kill("SIGTERM"),await new Promise(resolve3=>{let timeout=setTimeout(()=>{this.process?.kill("SIGKILL"),resolve3()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve3()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=process.platform==="win32"?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve3,reject)=>{let onConnect=()=>{cleanup(),resolve3()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async closeSession(sessionId=this.sessionId){if(sessionId){try{await this.send({type:"close_session",sessionId},!1)}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0)}}async listSessions(){let response=await this.send({type:"list_sessions"},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success)throw new Error(response.error)}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async steer(message,images,recovery){await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder})}async followUp(message,images,recovery){await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder})}async abort(){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since){let response=await this.send({type:"get_entries",since});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async editUserMessage(entryId,text,options={}){let response=await this.send({type:"edit_user_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve3,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3())})})}collectEvents(timeout=6e4){return new Promise((resolve3,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of this.eventListeners)listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of this.eventListeners)listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{}};return expectResponse?new Promise((resolve3,reject)=>{let timeout=setTimeout(()=>{let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id);let timeoutError=new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`);pending?.onReject?.(timeoutError),reject(timeoutError)},3e4);this.pendingRequests.set(id,{resolve:response=>{clearTimeout(timeout),resolve3(response)},reject:error=>{clearTimeout(timeout),reject(error)},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}}):(stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0}))}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{stripAnsi,reserveSessionWrite,unregisterSessionWriter,resolveEnvironmentContext,environmentContextMessageIfChanged,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,executeBashWithOperations,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcCommandError,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
|
|
47
|
+
${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{spawn}from"node:child_process";import{createConnection}from"node:net";var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.options=options}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve3=>setTimeout(resolve3,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}async stop(){if(this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.process.kill("SIGTERM"),await new Promise(resolve3=>{let timeout=setTimeout(()=>{this.process?.kill("SIGKILL"),resolve3()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve3()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=process.platform==="win32"?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve3,reject)=>{let onConnect=()=>{cleanup(),resolve3()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async closeSession(sessionId=this.sessionId){if(sessionId){try{await this.send({type:"close_session",sessionId},!1)}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0)}}async listSessions(){let response=await this.send({type:"list_sessions"},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success)throw new Error(response.error)}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async steer(message,images,recovery){await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder})}async followUp(message,images,recovery){await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder})}async abort(){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since){let response=await this.send({type:"get_entries",since});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async editUserMessage(entryId,text,options={}){let response=await this.send({type:"edit_user_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve3,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3())})})}collectEvents(timeout=6e4){return new Promise((resolve3,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of this.eventListeners)listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of this.eventListeners)listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{}};return expectResponse?new Promise((resolve3,reject)=>{let timeout=setTimeout(()=>{let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id);let timeoutError=new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`);pending?.onReject?.(timeoutError),reject(timeoutError)},3e4);this.pendingRequests.set(id,{resolve:response=>{clearTimeout(timeout),resolve3(response)},reject:error=>{clearTimeout(timeout),reject(error)},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}}):(stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0}))}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{stripAnsi,reserveSessionWrite,unregisterSessionWriter,resolveEnvironmentContext,environmentContextMessageIfChanged,rejectedImageSources,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,executeBashWithOperations,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcCommandError,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{require_semver}from"./chunk-ZOFZRJSL.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{APP_NAME,BRAND,DISPLAY_VERSION,PACKAGE_NAME,brandProfile,envValue}from"./chunk-Y65WFI5H.js";import{__toESM}from"./chunk-IKOFCODM.js";import{spawnSync}from"node:child_process";import{homedir as osHomedir}from"node:os";import{posix,win32}from"node:path";var RUNTIME_ENV_VAR="SENPI_RUNTIME",MIN_BUN_VERSION="1.4.0";function normalize(path){return path.replaceAll("\\","/")}function paths(options){return options.platform==="win32"?win32:posix}function bunRoot(options){let configured=options.env.BUN_INSTALL;return configured!==void 0&&configured.trim()!==""?configured:paths(options).join(options.homedir,".bun")}function resolveOrSelf(path,options){try{return options.realpath(path)}catch{return path}}function isUnderBunGlobalTree(scriptRealPath,options){let globalRoot=paths(options).join(bunRoot(options),"install","global"),script=normalize(scriptRealPath);for(let candidate of new Set([globalRoot,resolveOrSelf(globalRoot,options)]))if(script.startsWith(`${normalize(candidate)}/`))return!0;return!1}function isInstalledPackageScript(scriptRealPath){return normalize(scriptRealPath).includes("/node_modules/")}function bunVersionSatisfies(version){let actual=/^v?(\d+)\.(\d+)\.(\d+)/.exec(version?.trim()??""),minimum=/^(\d+)\.(\d+)\.(\d+)/.exec(MIN_BUN_VERSION);if(!actual||!minimum)return!1;for(let index=1;index<=3;index++){let difference=Number(actual[index])-Number(minimum[index]);if(difference!==0)return difference>0}return!0}function bunExecutableName(options){return options.platform==="win32"?"bun.exe":"bun"}function pathCandidateNames(options){if(options.platform!=="win32")return["bun"];let extensions=(options.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(extension=>extension.trim()).filter(extension=>extension.length>0);return extensions.length>0?extensions.map(extension=>`bun${extension}`):["bun.exe"]}function findBunBinary(options){let path=paths(options),executable=bunExecutableName(options),rootCandidates=[path.join(bunRoot(options),"bin",executable),path.join(options.homedir,".bun","bin",executable)];for(let candidate of rootCandidates)if(options.exists(candidate))return candidate;let pathValue=options.env.PATH??options.env.Path;if(pathValue===void 0||pathValue==="")return;let names=pathCandidateNames(options);for(let directory of pathValue.split(path.delimiter))if(directory!=="")for(let name of names){let candidate=path.join(directory,name);if(options.exists(candidate))return candidate}}function readRuntimePin(options){let value=options.env[RUNTIME_ENV_VAR];if(value==="node"||value==="bun")return value}function resolveBunReexec(input){if(input.versions.bun!==void 0)return{action:"stay",reason:"already-bun"};let pinned=readRuntimePin(input.options);if(pinned==="node")return{action:"stay",reason:"runtime-pinned-node"};if(input.hasInheritedInspectorOption)return{action:"stay",reason:"inspector"};let trustsInstalledBun=pinned==="bun"||isUnderBunGlobalTree(input.scriptRealPath,input.options);if(!trustsInstalledBun&&!isInstalledPackageScript(input.scriptRealPath))return{action:"stay",reason:"not-bun-install"};let bunPath=findBunBinary(input.options);return bunPath===void 0?{action:"stay",reason:"bun-not-found"}:!trustsInstalledBun&&!bunVersionSatisfies(input.options.bunVersion(bunPath))?{action:"stay",reason:"bun-too-old"}:{action:"reexec",bunPath}}function readBunVersion(bunPath){try{let result=spawnSync(bunPath,["--version"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(result.status!==0)return;let version=result.stdout.trim();return version===""?void 0:version}catch{return}}function processBunRuntimeOptions(exists,realpath){return{env:process.env,homedir:osHomedir(),platform:process.platform,exists,realpath,bunVersion:readBunVersion}}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled||(earlyRecoveryInstalled=!0,process.on("uncaughtException",(error,origin)=>{let otherHandlerActive=process.listenerCount("uncaughtException")>1;if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||(console.error(error),process.exit(1))}))}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}function getPiUserAgent(version=DISPLAY_VERSION){let runtime=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`${BRAND?.userAgent??APP_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`}var import_semver=__toESM(require_semver(),1);var REGISTRY_BASE_URL="https://registry.npmjs.org",LATEST_VERSION_URL=`${REGISTRY_BASE_URL}/${encodeURIComponent(PACKAGE_NAME)}/latest`;function latestVersionUrl(channel){return channel?`${REGISTRY_BASE_URL}/-/package/${encodeURIComponent(channel.packageName)}/dist-tags`:LATEST_VERSION_URL}function readAvailableVersion(payload,channel){if(typeof payload!="object"||payload===null)return;let source=payload,raw=channel?source[channel.distTag]:source.version;return typeof raw=="string"&&raw.trim()?raw.trim():void 0}var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4,RELEASE_CHANGELOG_BASE_URL="https://github.com/code-yeongyu/senpi/blob",RELEASE_CHANGELOG_PATH="packages/coding-agent/CHANGELOG.md",SENPI_CALVER_PATTERN=/^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-([2-9]\d*))?$/;function parseSenpiCalVer(version){let match=SENPI_CALVER_PATTERN.exec(version);if(match)return[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??1)]}function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let leftTrimmed=leftVersion.trim(),rightTrimmed=rightVersion.trim(),leftCalVer=parseSenpiCalVer(leftTrimmed),rightCalVer=parseSenpiCalVer(rightTrimmed);if(leftCalVer&&rightCalVer){for(let index=0;index<leftCalVer.length;index++)if(leftCalVer[index]!==rightCalVer[index])return leftCalVer[index]<rightCalVer[index]?-1:1;return 0}let left=(0,import_semver.valid)(leftTrimmed),right=(0,import_semver.valid)(rightTrimmed);if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0&&comparison>0}function getReleaseChangelogUrl(version){let trimmedVersion=version.trim(),channel=brandProfile()?.update;if(channel?.changelogUrl)return channel.changelogUrl.replace("{version}",trimmedVersion);let tag=trimmedVersion.startsWith("v")?trimmedVersion:`v${trimmedVersion}`;return`${RELEASE_CHANGELOG_BASE_URL}/${tag}/${RELEASE_CHANGELOG_PATH}`}async function getLatestPiRelease(currentVersion,options={}){if(envValue("OFFLINE"))return;let brand=brandProfile(),channel=brand?.update;if(brand&&!channel)return;let response=await fetchWithRetry(latestVersionUrl(channel),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json(),availableVersion=readAvailableVersion(data,channel);if(!availableVersion)return;if(channel)return{version:availableVersion,packageName:channel.packageName};let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:availableVersion,packageName,note}}async function checkForNewPiVersion(currentVersion){if(!envValue("SKIP_VERSION_CHECK"))try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}export{RUNTIME_ENV_VAR,MIN_BUN_VERSION,bunVersionSatisfies,findBunBinary,resolveBunReexec,processBunRuntimeOptions,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,getPiUserAgent,formatVersionCheckError,isNewerPackageVersion,getReleaseChangelogUrl,getLatestPiRelease,checkForNewPiVersion};
|
|
@@ -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); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
3
|
-
import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-
|
|
3
|
+
import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-3QCAGZFO.js";import"./chunk-ZKZAATFM.js";import"./chunk-UYCGOK6M.js";import"./chunk-6WBYI25N.js";import"./chunk-HH3D5ZYA.js";import"./chunk-YS5YEX4S.js";import"./chunk-HCXLCGMF.js";import"./chunk-77ACEMYL.js";import"./chunk-EJKCBRYK.js";import"./chunk-6Q6DGME2.js";import{configureHttpDispatcher}from"./chunk-WM5FVFAP.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MKAM7IRH.js";import"./chunk-CLZVNQW3.js";import"./chunk-HH3KJDWA.js";import"./chunk-3WBSBDBX.js";import"./chunk-UBPMXBOJ.js";import"./chunk-FIJJKSPL.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-HZAKOVHN.js";import"./chunk-TTY5BHCG.js";import"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y54V65MS.js";import"./chunk-SUQDU5KM.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PRC5XIIH.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-W3D3ZYDS.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{RpcClient,RpcCommandError,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-OZCB6BP3.js";import{SessionStreamingError,UserEditError}from"./chunk-6Q6DGME2.js";import{SettingsManager}from"./chunk-WM5FVFAP.js";import{ensureHost}from"./chunk-CLZVNQW3.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-HH3KJDWA.js";import"./chunk-3WBSBDBX.js";import"./chunk-UBPMXBOJ.js";import"./chunk-FHXKBENX.js";import"./chunk-7X72IACK.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await startHost({socket:options.socket,agentDir:options.agentDir}),disposed||(await client.start(),disposed)||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await startHost({socket:options.socket,agentDir:options.agentDir}),await client.start(),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...options?.images?{images:options.images}:{},...options?.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options?.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options?.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options?.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
|
|
2
|
+
import{RpcClient,RpcCommandError,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-HH3D5ZYA.js";import{SessionStreamingError,UserEditError}from"./chunk-6Q6DGME2.js";import{SettingsManager}from"./chunk-WM5FVFAP.js";import{ensureHost}from"./chunk-CLZVNQW3.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-HH3KJDWA.js";import"./chunk-3WBSBDBX.js";import"./chunk-UBPMXBOJ.js";import"./chunk-FHXKBENX.js";import"./chunk-7X72IACK.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await startHost({socket:options.socket,agentDir:options.agentDir}),disposed||(await client.start(),disposed)||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await startHost({socket:options.socket,agentDir:options.agentDir}),await client.start(),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...options?.images?{images:options.images}:{},...options?.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options?.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options?.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options?.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
|
|
3
3
|
${command}`:command;try{let result=await executeBashWithOperations(resolvedCommand,state.cwd,options.operations,{onChunk,signal:abortController.signal});return state.sessionId===sessionAtStart&&await transportCall("recordBashResult",()=>client.recordBashResult(command,result,options.excludeFromContext)),result}finally{localBashAbortController=void 0,localBashRunning=!1,updateBashState()}}let executionId=`bash-${executionNamespace}-${++nextBashExecutionId}`,execution={chunk:onChunk,promises:new Set,error:void 0,hasError:!1};bashExecutions.set(executionId,execution);try{let result=await transportCall("bash",()=>client.bash(command,{excludeFromContext:options?.excludeFromContext,executionId,operations:options?.operations}),{output:"",exitCode:void 0,cancelled:!0,truncated:!1});if(!await waitForBashCallbacks(execution.promises,!1))throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),new Error("Bash output callback did not settle within 5000ms");if(execution.hasError)throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),execution.error;return result}finally{bashExecutions.delete(executionId)}};if(property==="abortBash")return()=>{localBashAbortController?localBashAbortController.abort():client.abortBash().catch(reportActionFailure("abortBash"))};if(property==="getContextUsage")return()=>state.contextUsage;if(property==="getSessionStats")return()=>transportCall("getSessionStats",()=>client.getSessionStats(),local.getSessionStats());if(property==="exportToHtml")return(outputPath,options)=>transportCall("exportToHtml",()=>client.exportHtml(outputPath,options?.themeName)).then(result=>result?.path);if(property==="setSessionName")return name=>client.setSessionName(name).catch(reportActionFailure("setSessionName"));if(property==="navigateTree")return async(targetId,options)=>{let result=await transportCall("navigateTree",()=>client.navigateTree(targetId,options),{cancelled:!0});return result.cancelled||await refresh(),result};if(property==="editAssistantMessage")return async(entryId,text,options)=>{let result=await client.editAssistantMessage(entryId,text,{expectedLeafId:options?.expectedLeafId,summarize:options?.summarize,customInstructions:options?.customInstructions});return result.outcome==="unchanged"?{cancelled:!1,unchanged:!0}:result.outcome==="cancelled"?{cancelled:!0,aborted:result.aborted}:(await refresh(),{cancelled:!1,entryId:result.entry.id})};if(property==="editUserMessage")return async(entryId,text,options)=>{let result;try{result=await client.editUserMessage(entryId,text,{expectedLeafId:options?.expectedLeafId,summarize:options?.summarize,customInstructions:options?.customInstructions})}catch(error){if(error instanceof RpcCommandError)switch(error.errorCode){case"streaming":throw new SessionStreamingError;case"not_found":throw new UserEditError("not-found",error.message);case"not_user":throw new UserEditError("not-user",error.message);case"empty":throw new UserEditError("empty",error.message);case"stale_leaf":throw new UserEditError("stale-leaf",error.message)}throw error}return result.outcome==="unchanged"?{cancelled:!1,unchanged:!0}:result.outcome==="cancelled"?{cancelled:!0,aborted:result.aborted}:(await refresh(),{cancelled:!1,entryId:result.entry.id})};if(property==="getUserMessagesForForking")return()=>transportCall("getUserMessagesForForking",()=>client.getForkMessages(),[]);if(property==="subscribe")return listener=>{listeners.add(listener);let localUnsubscribe=target.subscribe(listener);return()=>{listeners.delete(listener),localUnsubscribe()}};if(property==="isStreaming")return state.isStreaming;if(property==="isIdle")return!state.isStreaming;if(property==="isCompacting")return state.isCompacting;if(property==="pendingMessageCount")return state.pendingMessageCount;if(property==="getSteeringMessages")return()=>state.steering;if(property==="getFollowUpMessages")return()=>state.followUp;if(property==="clearQueue")return options=>{let result={steering:[...state.steering],followUp:[...state.followUp],ordered:[...state.ordered]};return Object.defineProperty(result,"ordered",{value:result.ordered,enumerable:!1}),client.clearQueue(options).catch(reportActionFailure("clearQueue")),result};if(property==="abortBranchSummary")return()=>{client.abortBranchSummary().catch(reportActionFailure("abortBranchSummary"))};if(property==="recordBashResult")return(command,result,options)=>{client.recordBashResult(command,result,options?.excludeFromContext).catch(reportActionFailure("recordBashResult"))};if(property!=="set_label"){if(property==="retryAttempt")return state.retryAttempt;if(property==="isBashRunning")return state.isBashRunning;if(property==="reload")return _options=>transportCall("reload",()=>client.reload(),{cancelled:!0});if(property==="checkReloadVeto")return()=>transportCall("checkReloadVeto",()=>client.checkReloadVeto(),{cancelled:!0});if(property==="exportToJsonl")return outputPath=>transportCall("exportToJsonl",()=>client.exportJsonl(outputPath)).then(result=>result?.path);if(property==="state"){let localState=target.state;return{...localState,model:state.model??localState.model,thinkingLevel:state.thinkingLevel,isStreaming:state.isStreaming,isCompacting:state.isCompacting}}return property==="sessionFile"?state.sessionFile:property==="sessionId"?state.sessionId:property==="sessionName"?state.sessionName:property==="serviceTier"?state.serviceTier:property==="steeringMode"?state.steeringMode:property==="followUpMode"?state.followUpMode:property==="autoCompactionEnabled"?state.autoCompactionEnabled:property==="isFastModeActive"?()=>state.fastMode:property==="sessionManager"?remoteSessionManager:property==="settingsManager"?settingsManager:property==="messages"?target.messages:property==="favoriteModels"?state.favoriteModels:property==="scopedModels"?state.scopedModels:property==="model"?state.model??target.model:property==="thinkingLevel"?state.thinkingLevel:Reflect.get(target,property,receiver)}}}),setHostUiHandler:callback=>{if(hostUiHandler=callback,callback)for(let request of pendingUiRequests.splice(0))Promise.resolve(callback(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response"))},refresh,aroundLocalReplacement:async body=>{localReplacementDepth++;try{return await body()}finally{localReplacementDepth--}},abortLocalBash:()=>localBashAbortController?.abort(),createReplacedSessionContext:()=>{let context=local.createReplacedSessionContext();return Object.defineProperty(context,"cwd",{value:state.cwd}),Object.defineProperty(context,"sessionManager",{value:remoteSessionManager}),context.sendMessage=(message,options)=>transportCall("sendMessage",()=>client.sendCustomMessage(message,{triggerTurn:options?.triggerTurn,deliverAs:options?.deliverAs})),context.sendUserMessage=(content,options)=>{if(typeof content=="string")return transportCall("sendUserMessage",()=>client.prompt(content,{streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}));let text=content.filter(part=>part.type==="text").map(part=>part.text).join(`
|
|
4
4
|
`),images=content.filter(part=>part.type==="image");return transportCall("sendUserMessage",()=>client.prompt(text,{images,streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}))},context}}}function hydrateMessageUpdate(event,streamingAssistant){if(event.type!=="message_update"||!streamingAssistant)return event;let update=event.assistantMessageEvent;if(update.type!=="text_delta"&&update.type!=="thinking_delta"&&update.type!=="toolcall_delta")return event;let content=streamingAssistant.content[update.contentIndex];if(update.type==="text_delta"&&content?.type==="text"&&(content.text+=update.delta),update.type==="thinking_delta"&&content?.type==="thinking"&&(content.thinking+=update.delta),update.type==="toolcall_delta"&&content?.type==="toolCall"){let raw=JSON.stringify(content.arguments)+update.delta;try{let parsed=JSON.parse(raw);typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)&&(content.arguments=parsed)}catch{}}return streamingAssistant.usage=event.usage,{type:"message_update",message:structuredClone(streamingAssistant),assistantMessageEvent:{...update,partial:structuredClone(streamingAssistant)}}}function isInteractiveHostEvent(event){return typeof event=="object"&&event!==null&&"type"in event}export{INTERACTIVE_HOST_FALLBACK_WARNING,INTERACTIVE_HOST_RECONNECTING_WARNING,RemoteInteractiveRuntime,createInteractiveHostRuntime,createRemoteSessionProxy,isInteractiveHostEvent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-3QCAGZFO.js";import"./chunk-ZKZAATFM.js";import"./chunk-UYCGOK6M.js";import"./chunk-6WBYI25N.js";import"./chunk-HH3D5ZYA.js";import"./chunk-YS5YEX4S.js";import{isApiKeyLoginProvider}from"./chunk-HCXLCGMF.js";import"./chunk-77ACEMYL.js";import"./chunk-EJKCBRYK.js";import"./chunk-6Q6DGME2.js";import"./chunk-WM5FVFAP.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MKAM7IRH.js";import"./chunk-CLZVNQW3.js";import"./chunk-HH3KJDWA.js";import"./chunk-3WBSBDBX.js";import"./chunk-UBPMXBOJ.js";import"./chunk-FIJJKSPL.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-HZAKOVHN.js";import"./chunk-TTY5BHCG.js";import"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y54V65MS.js";import"./chunk-SUQDU5KM.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PRC5XIIH.js";import"./chunk-W3D3ZYDS.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
|
package/dist/bundle/chunks/{multi-session-host-7YX2I7UK.js → multi-session-host-5IWJEFDF.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,isSessionBusySnapshot,runWithProviderScope}from"./chunk-QGC46CGK.js";import"./chunk-ZKZAATFM.js";import"./chunk-UYCGOK6M.js";import"./chunk-6WBYI25N.js";import{SessionManager,assertValidSessionId}from"./chunk-OZCB6BP3.js";import"./chunk-YS5YEX4S.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,recordLoopBlockedMs,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-T3JBT2IK.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-77ACEMYL.js";import"./chunk-EJKCBRYK.js";import"./chunk-6Q6DGME2.js";import"./chunk-WM5FVFAP.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MKAM7IRH.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-CLZVNQW3.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-HH3KJDWA.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createEndpointReservations,ensureSocketSecret,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-3WBSBDBX.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostGeneration,hostInstanceId,protocolIdentity}from"./chunk-UBPMXBOJ.js";import"./chunk-FIJJKSPL.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-HZAKOVHN.js";import"./chunk-TTY5BHCG.js";import{killTrackedDetachedChildren}from"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y54V65MS.js";import"./chunk-SUQDU5KM.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PRC5XIIH.js";import"./chunk-34HMVB33.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{access,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";var HOST_RSS_REFUSE_MB_ENV="SENPI_RPC_HOST_RSS_REFUSE_MB";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.critical=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),options.onCritical&&(this.onCritical=options.onCritical),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096,this.refuseMb=parsePositiveInteger(env[HOST_RSS_REFUSE_MB_ENV])??this.warnMb*2}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576),critical=rssMb>this.refuseMb;if(critical!==this.critical&&(this.critical=critical,this.onCritical?.(critical,rssMb)),rssMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(rssMb)),this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();if(this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5)return;this.lastLoggedAt=now;let policy=critical?"idle parking halved, new worker sessions refused":"idle parking halved";this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (${policy})
|
|
2
|
+
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,isSessionBusySnapshot,runWithProviderScope}from"./chunk-3QCAGZFO.js";import"./chunk-ZKZAATFM.js";import"./chunk-UYCGOK6M.js";import"./chunk-6WBYI25N.js";import{SessionManager,assertValidSessionId}from"./chunk-HH3D5ZYA.js";import"./chunk-YS5YEX4S.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,recordLoopBlockedMs,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-HCXLCGMF.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-77ACEMYL.js";import"./chunk-EJKCBRYK.js";import"./chunk-6Q6DGME2.js";import"./chunk-WM5FVFAP.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MKAM7IRH.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-CLZVNQW3.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-HH3KJDWA.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createEndpointReservations,ensureSocketSecret,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-3WBSBDBX.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostGeneration,hostInstanceId,protocolIdentity}from"./chunk-UBPMXBOJ.js";import"./chunk-FIJJKSPL.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-HZAKOVHN.js";import"./chunk-TTY5BHCG.js";import{killTrackedDetachedChildren}from"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y54V65MS.js";import"./chunk-SUQDU5KM.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PRC5XIIH.js";import"./chunk-W3D3ZYDS.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{access,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";var HOST_RSS_REFUSE_MB_ENV="SENPI_RPC_HOST_RSS_REFUSE_MB";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.critical=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),options.onCritical&&(this.onCritical=options.onCritical),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096,this.refuseMb=parsePositiveInteger(env[HOST_RSS_REFUSE_MB_ENV])??this.warnMb*2}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576),critical=rssMb>this.refuseMb;if(critical!==this.critical&&(this.critical=critical,this.onCritical?.(critical,rssMb)),rssMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(rssMb)),this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();if(this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5)return;this.lastLoggedAt=now;let policy=critical?"idle parking halved, new worker sessions refused":"idle parking halved";this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (${policy})
|
|
3
3
|
`)}};import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4;function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){this.timer===void 0&&(this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)})
|
|
4
4
|
`))}};function isHandoffBusy(snapshot){return isSessionBusySnapshot({...snapshot,hasActiveWakeSource:!1})}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
|
|
5
5
|
`)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),rerenderComponents:()=>runWithProviderScope(entry.scope,()=>handler.rerenderComponents()),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}import{existsSync,realpathSync}from"node:fs";import{basename,dirname,isAbsolute,resolve}from"node:path";function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
|
package/dist/bundle/chunks/{package-manager-cli-3ISYTEL2.js → package-manager-cli-FZKBCLWV.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-
|
|
2
|
+
import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-3QCAGZFO.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-ZKZAATFM.js";import"./chunk-UYCGOK6M.js";import"./chunk-6WBYI25N.js";import"./chunk-HH3D5ZYA.js";import"./chunk-YS5YEX4S.js";import"./chunk-HCXLCGMF.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-77ACEMYL.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-EJKCBRYK.js";import"./chunk-6Q6DGME2.js";import{SettingsManager}from"./chunk-WM5FVFAP.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MKAM7IRH.js";import"./chunk-CLZVNQW3.js";import"./chunk-HH3KJDWA.js";import"./chunk-3WBSBDBX.js";import"./chunk-UBPMXBOJ.js";import"./chunk-FIJJKSPL.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-HZAKOVHN.js";import"./chunk-TTY5BHCG.js";import{killProcessTree}from"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y54V65MS.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-SUQDU5KM.js";import"./chunk-BSOJHK4W.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import{require_proper_lockfile}from"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PRC5XIIH.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-W3D3ZYDS.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
|
|
3
3
|
`)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
|
|
4
4
|
`,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
|
|
5
5
|
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{runRpcMode}from"./chunk-
|
|
2
|
+
import{runRpcMode}from"./chunk-HCXLCGMF.js";import"./chunk-77ACEMYL.js";import"./chunk-EJKCBRYK.js";import"./chunk-6Q6DGME2.js";import"./chunk-WM5FVFAP.js";import"./chunk-YU2P3CAR.js";import"./chunk-HH3KJDWA.js";import"./chunk-UBPMXBOJ.js";import"./chunk-HB35RBP4.js";import"./chunk-TTY5BHCG.js";import"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-SUQDU5KM.js";import"./chunk-BSOJHK4W.js";import"./chunk-26UBFF6N.js";import"./chunk-KMJXSXRX.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-TTHMOL5G.js";import"./chunk-WVGCQOLJ.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
|