@code-yeongyu/senpi 2026.10.6 → 2026.10.7

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/bundle/chunks/{app-server-command-GNTX4MZT.js → app-server-command-SO5RJ2N7.js} +1 -1
  3. package/dist/bundle/chunks/chunk-7SMFF2QJ.js +14 -0
  4. package/dist/bundle/chunks/{chunk-6JXPZACL.js → chunk-CM5QTRC2.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-3EE6G4G7.js → chunk-EUU6W5B3.js} +10 -10
  6. package/dist/bundle/chunks/{chunk-HKG7XL4H.js → chunk-HY4AOLON.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-4MJKBXI3.js → chunk-JJNIU2A2.js} +8 -4
  8. package/dist/bundle/chunks/{chunk-22DAHAHO.js → chunk-LUWWM7GA.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-6KQGOVQG.js → chunk-VJJ53ORU.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-XYDZ3LIE.js → chunk-YI7SPFDN.js} +2 -2
  11. package/dist/bundle/chunks/chunk-ZJHRDQCH.js +2 -0
  12. package/dist/bundle/chunks/cli-main-XBQN73O2.js +3 -0
  13. package/dist/bundle/chunks/host-command-YXQAXNKK.js +2 -0
  14. package/dist/bundle/chunks/{host-lifecycle-7OVWGVIZ.js → host-lifecycle-L4XQIATP.js} +1 -1
  15. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  16. package/dist/bundle/chunks/interactive-mode-ROO5W56P.js +2 -0
  17. package/dist/bundle/chunks/{multi-session-host-QLLTPWIM.js → multi-session-host-5WTKAQJM.js} +1 -1
  18. package/dist/bundle/chunks/{package-manager-cli-VRCAO7RV.js → package-manager-cli-NCD5FQGV.js} +1 -1
  19. package/dist/bundle/chunks/rpc-mode-MWURKCP2.js +2 -0
  20. package/dist/bundle/chunks/{schedule-command-QTYSUYO2.js → schedule-command-UTXB465F.js} +1 -1
  21. package/dist/bundle/chunks/session-control-endpoint-J6RHZXWB.js +3 -0
  22. package/dist/bundle/chunks/session-worker.js +16 -12
  23. package/dist/bundle/cli.js +1 -1
  24. package/dist/bundle/index.js +1 -1
  25. package/dist/bundle/rpc-entry.js +1 -1
  26. package/dist/bundle/runtime-manifest.json +1 -1
  27. package/dist/core/extensions/eval-handle-host.d.ts +82 -0
  28. package/dist/core/extensions/eval-handle-host.js +28 -0
  29. package/dist/core/extensions/loader.js +5 -0
  30. package/dist/core/extensions/runner.js +4 -0
  31. package/dist/core/extensions/types.d.ts +15 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.js +1 -0
  34. package/dist/modes/interactive/session-control-registry.js +2 -0
  35. package/dist/modes/rpc/host-daemon-registration.d.ts +9 -0
  36. package/dist/modes/rpc/host-daemon-registration.js +2 -4
  37. package/dist/modes/rpc/host-ensure-start.js +2 -0
  38. package/dist/modes/rpc/host-handoff-unregistered.d.ts +24 -0
  39. package/dist/modes/rpc/host-handoff-unregistered.js +50 -0
  40. package/dist/modes/rpc/host-handoff.d.ts +7 -2
  41. package/dist/modes/rpc/host-handoff.js +7 -3
  42. package/dist/modes/rpc/host-legacy.d.ts +3 -0
  43. package/dist/modes/rpc/host-legacy.js +10 -5
  44. package/dist/modes/rpc/host-probe.d.ts +12 -0
  45. package/dist/modes/rpc/host-probe.js +53 -5
  46. package/dist/modes/rpc/host-runner.js +1 -1
  47. package/dist/modes/rpc/host-successor.d.ts +5 -4
  48. package/dist/modes/rpc/host-successor.js +11 -4
  49. package/docs/rpc.md +10 -2
  50. package/package.json +6 -6
  51. package/dist/bundle/chunks/chunk-QLIW3YMI.js +0 -14
  52. package/dist/bundle/chunks/cli-main-2C3YPHRE.js +0 -3
  53. package/dist/bundle/chunks/host-command-N6XS5O67.js +0 -2
  54. package/dist/bundle/chunks/interactive-mode-CM4C4ZFY.js +0 -2
  55. package/dist/bundle/chunks/rpc-mode-2OPE6J7P.js +0 -2
  56. package/dist/bundle/chunks/session-control-endpoint-SOG4XFF7.js +0 -3
@@ -1,4 +1,4 @@
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
3
  import{enableStartupCompileCache}from"./chunks/chunk-F73COJ7R.js";import{getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync2,realpathSync as realpathSync3}from"node:fs";import{dirname as dirname3,join as join5}from"node:path";import{fileURLToPath}from"node:url";import{createHash}from"node:crypto";import{readFileSync as readFileSync3,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname2,join as join3,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync,mkdirSync,readdirSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";import{constants}from"node:fs";import{copyFile,link}from"node:fs/promises";function errorCode(error){return error instanceof Error&&"code"in error?error.code:void 0}var FILE_OPERATIONS={copyFile,link},COPY_CONCURRENCY=8;function nextCopyMode(mode,error,platform){let code=errorCode(error);if(!(code==="ENOENT"||code==="ENOTDIR"||code==="EEXIST"))switch(mode){case"clone":return platform==="darwin"&&code==="ENOSYS"?"clone-or-copy":"link";case"link":return"copy";case"clone-or-copy":case"copy":return}}function createSnapshotFileCopier(platform=process.platform,operations=FILE_OPERATIONS){let mode="clone",attempt=(current,source,target)=>{switch(current){case"clone":return operations.copyFile(source,target,constants.COPYFILE_FICLONE_FORCE);case"clone-or-copy":return operations.copyFile(source,target,constants.COPYFILE_FICLONE);case"link":return operations.link(source,target);case"copy":return operations.copyFile(source,target,0)}};return{get mode(){return mode},async copy(source,target){for(let current=mode;;)try{await attempt(current,source,target);return}catch(error){let next=nextCopyMode(current,error,platform);if(next===void 0)throw error;current=next,mode=next}}}}async function copyFiles(pairs,copier){let next=0,worker=async()=>{for(let index=next++;index<pairs.length;index=next++){let[source,target]=pairs[index]??[];source!==void 0&&target!==void 0&&await copier.copy(source,target)}};await Promise.all(Array.from({length:Math.min(COPY_CONCURRENCY,pairs.length)},worker))}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-",UNLOADED_FILE=/\.(?:d\.[cm]?ts|map)$/;function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function planTree(source,target,files,skipModules,seen=new Set){let real=realpathSync(source);if(!seen.has(real)){seen.add(real),mkdirSync(target,{recursive:!0});for(let entry of readdirSync(real,{withFileTypes:!0})){if(skipModules&&entry.name==="node_modules")continue;let from=join(real,entry.name),to=join(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen);else if(entry.isFile())UNLOADED_FILE.test(entry.name)||files.push([from,to]);else if(entry.isSymbolicLink()){let isDirectory;try{isDirectory=statSync(from).isDirectory()}catch(error){if(isMissing(error))continue;throw error}isDirectory?planTree(from,to,files,skipModules,seen):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname(current)){if(basename(current)!=="node_modules"){let candidate=join(current,"node_modules");existsSync(candidate)&&directories.push(candidate)}if(dirname(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join(modules,packageName);if(existsSync(join(root,"package.json")))return realpathSync(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return[];let names=new Set;for(let field of["dependencies","optionalDependencies","peerDependencies"]){let block=manifest[field];if(typeof block=="object"&&block!==null)for(let name of Object.keys(block))names.add(name)}return[...names]}function closureNames(packageDir,extra){let names=new Set(extra),visited=new Set,pending=[realpathSync(packageDir)];for(let dir=pending.pop();dir!==void 0;dir=pending.pop())if(!visited.has(dir)){visited.add(dir);for(let name of dependencyNames(dir)){names.add(name);let root=packageRootFrom(dir,name);root!==void 0&&!visited.has(root)&&pending.push(root)}}return names}function planModules(packageDir,snapshotRoot,externals,files){let self=realpathSync(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join(snapshotRoot,"node_modules",name))}for(let next=pending.shift();next!==void 0;next=pending.shift())for(let name of dependencyNames(next.installDir)){let expected=packageRootFrom(next.installDir,name);expected===void 0||expected===self||resolvePlaced(next.snapshotDir,name)!==expected&&place(expected,join(next.snapshotDir,"node_modules",name))}return placed}function verifyExternals(packageDir,snapshotBundleDir,externals,placed){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected===void 0)continue;let found=moduleDirectoriesFrom(snapshotBundleDir).map(modules=>join(modules,name)).find(root=>existsSync(join(root,"package.json")));if(found===void 0||placed.get(found)!==expected)throw new RuntimeSnapshotLayoutError(name)}}async function materializeRuntimeSnapshot(packageDir,target,manifest,copier=createSnapshotFileCopier()){let staging=join(dirname(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planTree(packageDir,staging,files,!0);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync(packageDir)};writeFileSync(join(staging,RUNTIME_SNAPSHOT_MARKER),`${JSON.stringify(marker)}
4
- `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-FUMH5NSA.js");tryPrintHelpWithoutEngine(args)&&process.exit()}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-2C3YPHRE.js")}
4
+ `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-FUMH5NSA.js");tryPrintHelpWithoutEngine(args)&&process.exit()}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-XBQN73O2.js")}
@@ -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{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-3EE6G4G7.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-QLIW3YMI.js";import"./chunks/chunk-QNAG7FYM.js";import{CURRENT_SESSION_VERSION,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionManager,SessionSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,keyHint,keyText,migrateSessionEntries,parseSessionEntries,rawKeyHint,sessionEntryToContextMessages}from"./chunks/chunk-BE66QJ3Z.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-ESSQUSRC.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import{sanitizeTerminalLabel}from"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-6EH7QXOG.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-4MJKBXI3.js";import"./chunks/chunk-6KQGOVQG.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-6JXPZACL.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-7A3WRAKP.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HKG7XL4H.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-22DAHAHO.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-XYDZ3LIE.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-6SMU7ANE.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-D2W3MXRF.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-YSPHACIN.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-EUU6W5B3.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-7SMFF2QJ.js";import"./chunks/chunk-QNAG7FYM.js";import{CURRENT_SESSION_VERSION,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionManager,SessionSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,keyHint,keyText,migrateSessionEntries,parseSessionEntries,rawKeyHint,sessionEntryToContextMessages}from"./chunks/chunk-BE66QJ3Z.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-ESSQUSRC.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import{sanitizeTerminalLabel}from"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-6EH7QXOG.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-JJNIU2A2.js";import"./chunks/chunk-VJJ53ORU.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-CM5QTRC2.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-7A3WRAKP.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HY4AOLON.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-LUWWM7GA.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-6SMU7ANE.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-D2W3MXRF.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-YSPHACIN.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{main}from"./chunks/chunk-3EE6G4G7.js";import"./chunks/chunk-QLIW3YMI.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-BE66QJ3Z.js";import{configureHttpDispatcher}from"./chunks/chunk-ESSQUSRC.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-6EH7QXOG.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-4MJKBXI3.js";import"./chunks/chunk-6KQGOVQG.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-6JXPZACL.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-7A3WRAKP.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HKG7XL4H.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-22DAHAHO.js";import"./chunks/chunk-XYDZ3LIE.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import"./chunks/chunk-6SMU7ANE.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-D2W3MXRF.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-YSPHACIN.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{main}from"./chunks/chunk-EUU6W5B3.js";import"./chunks/chunk-7SMFF2QJ.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-BE66QJ3Z.js";import{configureHttpDispatcher}from"./chunks/chunk-ESSQUSRC.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-6EH7QXOG.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-JJNIU2A2.js";import"./chunks/chunk-VJJ53ORU.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-CM5QTRC2.js";import"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-7A3WRAKP.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HY4AOLON.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-LUWWM7GA.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import"./chunks/chunk-6SMU7ANE.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-D2W3MXRF.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-YSPHACIN.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -1 +1 @@
1
- {"buildId":"66277a5723ae8d19","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"58dfb08430dcf39a","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Host capability that lets an eval cell wait on, inspect and control work the host owns (agent runs,
3
+ * workpools). The task owner implements it and registers it; codemode only consumes it. Every operation is
4
+ * fenced by the owning session, the handle id and its run epoch: a ref whose epoch is no longer live is
5
+ * refused with `eval_handle_stale`, never silently redirected to a successor run.
6
+ */
7
+ export type HandleKind = "agent" | "completion" | "workpool";
8
+ export interface HandleRef {
9
+ readonly kind: HandleKind;
10
+ readonly id: string;
11
+ readonly run_epoch: number;
12
+ }
13
+ export type HandlePhase = "pending" | "succeeded" | "failed" | "cancelled" | "lost";
14
+ export interface HandleSnapshot {
15
+ readonly ref: HandleRef;
16
+ readonly phase: HandlePhase;
17
+ readonly host_status: string;
18
+ /** Strictly increases with every change of this ref; a consumer drops an update whose revision is not newer. */
19
+ readonly revision: number;
20
+ }
21
+ export interface HandleError {
22
+ readonly code: string;
23
+ readonly message: string;
24
+ readonly details?: unknown;
25
+ }
26
+ export type HandleOutcome = {
27
+ readonly status: "fulfilled";
28
+ readonly ref: HandleRef;
29
+ readonly value: unknown;
30
+ } | {
31
+ readonly status: "rejected";
32
+ readonly ref: HandleRef;
33
+ readonly error: HandleError;
34
+ };
35
+ export interface HandleCallContext {
36
+ readonly ownerSessionId: string;
37
+ readonly signal?: AbortSignal;
38
+ }
39
+ export interface HandleWatch {
40
+ /** One snapshot per watched ref, taken atomically with the subscription. */
41
+ readonly initial: readonly HandleSnapshot[];
42
+ /** Every change after `initial`, in order; a change during `watch()` setup arrives here exactly once. */
43
+ readonly updates: AsyncIterable<HandleSnapshot>;
44
+ close(): void;
45
+ }
46
+ export interface CancelReceipt {
47
+ readonly ref: HandleRef;
48
+ /** False when the run had already ended; cancelling twice is not an error. */
49
+ readonly cancelled: boolean;
50
+ readonly phase: HandlePhase;
51
+ }
52
+ export interface OutputRequest {
53
+ readonly format?: "raw" | "tail";
54
+ readonly offset?: number;
55
+ readonly limit?: number;
56
+ }
57
+ export interface OutputSnapshot {
58
+ readonly ref: HandleRef;
59
+ readonly text: string;
60
+ readonly offset: number;
61
+ readonly total: number;
62
+ readonly truncated: boolean;
63
+ }
64
+ export interface EvalHandleHost {
65
+ readonly version: 1;
66
+ watch(refs: readonly HandleRef[], ctx: HandleCallContext): Promise<HandleWatch>;
67
+ /** The terminal outcome; rejects with `eval_handle_pending` while the run is still pending. */
68
+ result(ref: HandleRef, ctx: HandleCallContext): Promise<HandleOutcome>;
69
+ /** Agent refs only; others refuse with `eval_handle_operation_unsupported`. */
70
+ send(ref: HandleRef, message: string, ctx: HandleCallContext): Promise<HandleSnapshot>;
71
+ cancel(ref: HandleRef, ctx: HandleCallContext): Promise<CancelReceipt>;
72
+ output(ref: HandleRef, request: OutputRequest, ctx: HandleCallContext): Promise<OutputSnapshot>;
73
+ }
74
+ export declare const EVAL_HANDLE_ERROR_CODES: readonly ["eval_handle_stale", "eval_handle_forbidden", "eval_handle_not_found", "eval_handle_pending", "eval_handle_operation_unsupported", "eval_wait_unavailable", "eval_wait_timeout", "eval_wait_empty", "eval_pool_open", "eval_workpool_failed"];
75
+ export type EvalHandleErrorCode = (typeof EVAL_HANDLE_ERROR_CODES)[number];
76
+ export declare class EvalHandleError extends Error {
77
+ readonly name = "EvalHandleError";
78
+ readonly code: EvalHandleErrorCode;
79
+ readonly details?: unknown;
80
+ constructor(code: EvalHandleErrorCode, message: string, details?: unknown);
81
+ }
82
+ //# sourceMappingURL=eval-handle-host.d.ts.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Host capability that lets an eval cell wait on, inspect and control work the host owns (agent runs,
3
+ * workpools). The task owner implements it and registers it; codemode only consumes it. Every operation is
4
+ * fenced by the owning session, the handle id and its run epoch: a ref whose epoch is no longer live is
5
+ * refused with `eval_handle_stale`, never silently redirected to a successor run.
6
+ */
7
+ export const EVAL_HANDLE_ERROR_CODES = [
8
+ "eval_handle_stale",
9
+ "eval_handle_forbidden",
10
+ "eval_handle_not_found",
11
+ "eval_handle_pending",
12
+ "eval_handle_operation_unsupported",
13
+ "eval_wait_unavailable",
14
+ "eval_wait_timeout",
15
+ "eval_wait_empty",
16
+ "eval_pool_open",
17
+ "eval_workpool_failed",
18
+ ];
19
+ export class EvalHandleError extends Error {
20
+ constructor(code, message, details) {
21
+ super(`${code}: ${message}`);
22
+ this.name = "EvalHandleError";
23
+ this.code = code;
24
+ if (details !== undefined)
25
+ this.details = details;
26
+ }
27
+ }
28
+ //# sourceMappingURL=eval-handle-host.js.map
@@ -209,6 +209,7 @@ export function createExtensionRuntime() {
209
209
  for (const unsubscribe of eventBusUnsubscribers)
210
210
  unsubscribe();
211
211
  eventBusUnsubscribers.clear();
212
+ runtime.evalHandleHost = undefined;
212
213
  runtimeFactories.delete(runtime);
213
214
  },
214
215
  trackEventBusSubscription: (unsubscribe) => {
@@ -350,6 +351,10 @@ function createExtensionAPI(extension, runtime, cwd, eventBus, session) {
350
351
  extension.lazyToolActivators = activators;
351
352
  runtime.registerLazyToolActivator(activator);
352
353
  },
354
+ provideEvalHandleHost(host) {
355
+ runtime.assertActive();
356
+ runtime.evalHandleHost = host;
357
+ },
353
358
  registerRemovedToolHint(name, hint) {
354
359
  runtime.assertActive();
355
360
  let hints = extension.removedToolHints;
@@ -955,6 +955,10 @@ export class ExtensionRunner {
955
955
  runner.assertActive();
956
956
  return kernelToolsStorage.getStore();
957
957
  },
958
+ get evalHandleHost() {
959
+ runner.assertActive();
960
+ return runner.runtime.evalHandleHost;
961
+ },
958
962
  abort: (source) => {
959
963
  runner.assertActive();
960
964
  runner.abortFn(source);
@@ -34,6 +34,7 @@ import type { BashToolDetails, BashToolInput, EditToolInput, FindToolDetails, Fi
34
34
  import type { ReadClassifier } from "../tools/read-classifiers.ts";
35
35
  import type { ModelRoute, ModelRouteRequest, VirtualModelDefinition } from "../virtual-models.ts";
36
36
  import type { McpServerDeclaration } from "./builtin/mcp/config-schema.ts";
37
+ import type { EvalHandleHost } from "./eval-handle-host.ts";
37
38
  import type { ExtensionKernelTools } from "./kernel-tools-context.ts";
38
39
  import type { SessionControlActions, SessionControlWakeEvent } from "./session-control-types.ts";
39
40
  export type { ExecOptions, ExecResult } from "../exec.ts";
@@ -391,6 +392,12 @@ export interface ExtensionContext {
391
392
  * JavaScript eval owns the host-tool context; absent on older runtimes.
392
393
  */
393
394
  readonly kernelTools?: ExtensionKernelTools;
395
+ /**
396
+ * Session-scoped host capability behind the in-cell `wait()` / `handle()` helpers: watch, send to,
397
+ * cancel and read host-owned work (agent runs, workpools) fenced by owner, id and run epoch.
398
+ * Provided by the task owner through `pi.provideEvalHandleHost`; absent on runtimes without a provider.
399
+ */
400
+ readonly evalHandleHost?: EvalHandleHost;
394
401
  /** Abort the current agent operation */
395
402
  abort(source?: "user" | "system"): void;
396
403
  /** Whether there are queued messages waiting */
@@ -1797,6 +1804,12 @@ export interface ExtensionAPI {
1797
1804
  registerTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(tool: ToolDefinition<TParams, TDetails, TState>): void;
1798
1805
  /** Register migration guidance returned when an intentionally removed tool is called. */
1799
1806
  registerRemovedToolHint(name: string, hint: string): void;
1807
+ /**
1808
+ * Provide this session's `EvalHandleHost` (the task/workpool owner implements it). Session-scoped:
1809
+ * every extension loaded in the same session reads it back as `ctx.evalHandleHost`; the last
1810
+ * provider wins, and a replaced or reloaded session starts without one.
1811
+ */
1812
+ provideEvalHandleHost(host: EvalHandleHost): void;
1800
1813
  /**
1801
1814
  * Register a callback that may activate a registered-but-inactive tool on demand.
1802
1815
  * Called only when executeTool would otherwise fail with `inactive_tool`. Return
@@ -2302,6 +2315,8 @@ export interface ExtensionRuntimeState {
2302
2315
  registerRemovedToolHint: RegisterRemovedToolHintHandler;
2303
2316
  registerVirtualModel: (definition: VirtualModelDefinition, extensionPath?: string) => void;
2304
2317
  unregisterVirtualModel: (provider: string, id: string) => void;
2318
+ /** The session's eval handle host, set by `pi.provideEvalHandleHost`; cleared when the runtime is invalidated. */
2319
+ evalHandleHost?: EvalHandleHost;
2305
2320
  }
2306
2321
  /**
2307
2322
  * Action implementations for pi.* API methods.
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export { type OAuthCredential, readStoredCredential } from "./core/auth-storage.
7
7
  export { type BranchPreparation, type BranchSummaryResult, type CacheFriendlySummaryOptions, type CollectEntriesResult, type CompactionResult, type CutPointResult, calculateContextTokens, collectEntriesForBranchSummary, compact, DEFAULT_COMPACTION_SETTINGS, estimateTokens, type FileOperations, findCutPoint, findTurnStartIndex, type GenerateBranchSummaryOptions, generateBranchSummary, generateSummary, generateSummaryWithUsage, getLastAssistantUsage, prepareBranchEntries, serializeConversation, shouldCompact, } from "./core/compaction/index.ts";
8
8
  export { compareEngineOrdinal, type EngineBuildIdentity, type EngineBuildInput, type EngineOrdinal, type EngineOrdinalScheme, engineBuildIdentity, engineBuildIdentityFrom, } from "./core/engine-build-identity.ts";
9
9
  export { createEventBus, type EventBus, type EventBusController } from "./core/event-bus.ts";
10
+ export { type CancelReceipt, EVAL_HANDLE_ERROR_CODES, EvalHandleError, type EvalHandleErrorCode, type EvalHandleHost, type HandleCallContext, type HandleError, type HandleKind, type HandleOutcome, type HandlePhase, type HandleRef, type HandleSnapshot, type HandleWatch, type OutputRequest, type OutputSnapshot, } from "./core/extensions/eval-handle-host.ts";
10
11
  export type { AfterProviderResponseEvent, AgentActivityOutcome, AgentBeforeSettleEvent, AgentBeforeSettleEventResult, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BoundaryContextPreview, BoundaryResult, BoundaryState, BuildSystemPromptOptions, CompactionEntryDraft, CompactOptions, ContextEditEntryDraft, ContextEvent, ContextEventResult, ContextUsage, ContextWithSystemEvent, CustomEntryDraft, CustomMessageEntryDraft, CustomToolCallEvent, EditToolCallEvent, EntryRenderer, EntryRendererOptions, EntryRenderOptions, ExecOptions, ExecResult, ExecuteToolOptions, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionRpcRequestHandler, ExtensionRuntime, ExtensionShortcut, ExtensionToolContext, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionVirtualModel, ExtensionWidgetOptions, FilesystemOperation, FilesystemPolicy, FilesystemPolicyChecker, FilesystemPolicyDecision, FilesystemPolicyRequest, FindToolCallEvent, GrepToolCallEvent, InlineExtension, InputDispositionEvent, InputEvent, InputEventResult, InputSource, KernelPreludeContribution, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, MarkdownTransformContext, MarkdownTransformer, McpServerDeclaration, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelSelectEvent, ModelSelectSource, NormalizedBuildSystemPromptOptions, PowerShellToolCallEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ProviderStreamEvent, ReadToolCallEvent, RegisteredCommand, RegisteredTool, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionBoundaryDraft, SessionCompactEvent, SessionCompactFailedEvent, SessionInfoChangedEvent, SessionParkedEvent, SessionResumedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SlashCommandInfo, SlashCommandSource, SourceInfo, TerminalInputHandler, ThinkingLevelSelectEvent, ToolAnnotations, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolExposure, ToolInfo, ToolLoadout, ToolLoadoutChanges, ToolNamespace, ToolPermissionRequest, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TurnEndEvent, TurnEndEventResult, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, } from "./core/extensions/index.ts";
11
12
  export { createExtensionRuntime, defineTool, discoverAndLoadExtensions, ExtensionRunner, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, wrapRegisteredTool, wrapRegisteredTools, } from "./core/extensions/index.ts";
12
13
  export { type ExtensionKernelTools, type KernelToolInvokeOptions, type KernelToolInvokeScope, kernelToolsStorage, } from "./core/extensions/kernel-tools-context.ts";
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ export { calculateContextTokens, collectEntriesForBranchSummary, compact, DEFAUL
12
12
  // Engine build identity: the ordinal clients compare instead of version strings
13
13
  export { compareEngineOrdinal, engineBuildIdentity, engineBuildIdentityFrom, } from "./core/engine-build-identity.js";
14
14
  export { createEventBus } from "./core/event-bus.js";
15
+ export { EVAL_HANDLE_ERROR_CODES, EvalHandleError, } from "./core/extensions/eval-handle-host.js";
15
16
  export { createExtensionRuntime, defineTool, discoverAndLoadExtensions, ExtensionRunner, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, wrapRegisteredTool, wrapRegisteredTools, } from "./core/extensions/index.js";
16
17
  export { kernelToolsStorage, } from "./core/extensions/kernel-tools-context.js";
17
18
  // Notice primitives
@@ -11,6 +11,7 @@ import { createHash } from "node:crypto";
11
11
  import { rmSync } from "node:fs";
12
12
  import { chmod, lstat, mkdir, realpath, rm } from "node:fs/promises";
13
13
  import { dirname, join } from "node:path";
14
+ import { engineBuildIdentity } from "../../core/engine-build-identity.js";
14
15
  import { createDaemonDirectories, createHostDaemonPaths } from "../rpc/host-daemon-paths.js";
15
16
  import { thisProcessStartTime, writeHostRegistration } from "../rpc/host-daemon-registration.js";
16
17
  import { acquireHostEnsureLock } from "../rpc/host-ensure-lock.js";
@@ -64,6 +65,7 @@ export async function registerTuiEndpoint(options) {
64
65
  instanceId: options.instanceId,
65
66
  generation: 0,
66
67
  launchProfileId: "tui",
68
+ build: engineBuildIdentity(),
67
69
  });
68
70
  await createDaemonDirectories(paths, { kind: "tui" });
69
71
  }
@@ -1,3 +1,4 @@
1
+ import type { EngineOrdinal } from "../../core/engine-build-identity.ts";
1
2
  import { type DaemonPidFile } from "../app-server/daemon/process.ts";
2
3
  import { type HostDaemonPaths, type HostGenerationPaths } from "./host-daemon-paths.ts";
3
4
  /** Who wrote a registration: the process identity a later stop must match to be allowed. */
@@ -13,6 +14,14 @@ export interface HostRegistration {
13
14
  readonly generation: number;
14
15
  /** The profile the spawned host was launched with, for a client comparing two generations. */
15
16
  readonly launchProfileId: string;
17
+ /**
18
+ * The build of the process this record names. Absent while it is not known yet (a handoff's
19
+ * successor before it answers): the record then claims no engine version rather than the writer's.
20
+ */
21
+ readonly build?: {
22
+ readonly text: string;
23
+ readonly ordinal: EngineOrdinal;
24
+ };
16
25
  }
17
26
  export interface RegisteredHost {
18
27
  readonly record: DaemonPidFile;
@@ -23,7 +23,6 @@
23
23
  * this module reads and writes through its primitives and never builds a path of its own.
24
24
  */
25
25
  import { rename, rm } from "node:fs/promises";
26
- import { engineBuildIdentity } from "../../core/engine-build-identity.js";
27
26
  import { parseDaemonPidFile, processMatchesPidFile, readProcessStartTime, } from "../app-server/daemon/process.js";
28
27
  import { createGenerationDirectory, generationPaths, HOST_DAEMON_LAYOUT, sameEndpoint, } from "./host-daemon-paths.js";
29
28
  import { isRecord, parseJson, readFileOrUndefined, writeStateFile } from "./host-daemon-state.js";
@@ -80,14 +79,13 @@ export async function writeHostRegistration(paths, registration) {
80
79
  export async function writeGenerationRecord(paths, registration) {
81
80
  const generation = generationPaths(paths, registration.instanceId);
82
81
  const writer = { pid: process.pid, startTime: await thisProcessStartTime() };
83
- const build = engineBuildIdentity();
82
+ const { build } = registration;
84
83
  await createGenerationDirectory(generation);
85
84
  await writeStateFile(generation.pidFile, {
86
85
  ...registration.record,
87
86
  instance_id: registration.instanceId,
88
87
  generation: registration.generation,
89
- engineVersion: build.text,
90
- engineOrdinal: build.ordinal,
88
+ ...(build && { engineVersion: build.text, engineOrdinal: build.ordinal }),
91
89
  launchProfileId: registration.launchProfileId,
92
90
  socket: registration.socket,
93
91
  writer,
@@ -2,6 +2,7 @@
2
2
  import { spawn } from "node:child_process";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { open, readFile } from "node:fs/promises";
5
+ import { engineBuildIdentity } from "../../core/engine-build-identity.js";
5
6
  import { readProcessStartTime, waitForStartTime } from "../app-server/daemon/process.js";
6
7
  import { clearHostRegistration, writeHostRegistration } from "./host-daemon-registration.js";
7
8
  import { writeHostSettings } from "./host-daemon-state.js";
@@ -92,6 +93,7 @@ export async function startHost(paths, socket, options, generation = 0) {
92
93
  instanceId,
93
94
  generation,
94
95
  launchProfileId: hostLaunchProfile(hostChildArgv(options.hostArgs ?? []), process.cwd()).profile_id,
96
+ build: engineBuildIdentity(),
95
97
  });
96
98
  child.unref();
97
99
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A handoff away from a host that no layout-2 registration proves (#2701).
3
+ *
4
+ * After an upgrade the old host is often still serving the very socket the updated client uses, and the
5
+ * only evidence of who it is may be a flat pre-layout-2 record - or nothing provable at all. Refusing
6
+ * such a host with `unknown_owner` left the client unable to replace it until somebody drained it by
7
+ * hand. An IDLE one is replaced instead; one that holds work never is.
8
+ *
9
+ * - The sessions are counted over a connection that stays open, and counted again over that same
10
+ * connection once the successor owns the socket: the recount reaches the old process, and a session
11
+ * it accepted in between is seen there.
12
+ * - A flat record that proves the process is the only licence to signal it, and the signal is a DRAIN
13
+ * (SIGUSR1), sent only when the recount still finds no session. A drain ends no work either way.
14
+ * - Without a provable owner nothing is signalled: the old host notices that it lost the public entry
15
+ * and drains itself (`host-supersession.ts`). That predecessor is named in one warning line, so an
16
+ * old host that outlives the handoff can still be identified.
17
+ */
18
+ import type { HostDaemonPaths } from "./host-daemon-paths.ts";
19
+ import type { HostProtocolInfo } from "./host-decision.ts";
20
+ import type { HandoffHostOptions, HandoffResult } from "./host-handoff.ts";
21
+ /** One session count; an unregistered host is counted twice (before the swap and over the held connection after). */
22
+ export declare const SESSION_COUNT_TIMEOUT_MS = 10000;
23
+ export declare function handoffUnregisteredHost(options: HandoffHostOptions, paths: HostDaemonPaths, host: HostProtocolInfo): Promise<HandoffResult>;
24
+ //# sourceMappingURL=host-handoff-unregistered.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { busyLegacyHostDetail, describeSessions, provenLegacyOwner } from "./host-legacy.js";
2
+ import { holdSessionCount } from "./host-probe.js";
3
+ import { startSuccessor } from "./host-successor.js";
4
+ /** One session count; an unregistered host is counted twice (before the swap and over the held connection after). */
5
+ export const SESSION_COUNT_TIMEOUT_MS = 10_000;
6
+ export async function handoffUnregisteredHost(options, paths, host) {
7
+ const counted = await holdSessionCount(options.socket, SESSION_COUNT_TIMEOUT_MS);
8
+ try {
9
+ const legacy = await provenLegacyOwner(paths, options.socket);
10
+ const sessions = counted?.sessions;
11
+ if (sessions !== 0) {
12
+ if (legacy !== undefined) {
13
+ return {
14
+ action: "refuse",
15
+ reason: "legacy_host",
16
+ upgradeable: true,
17
+ detail: busyLegacyHostDetail(legacy.pid, options.socket, sessions),
18
+ };
19
+ }
20
+ return {
21
+ action: "refuse",
22
+ reason: "unknown_owner",
23
+ upgradeable: true,
24
+ detail: `${options.socket} has no provable owner and holds ${describeSessions(sessions)}; it is never signalled - let that work finish, then retry`,
25
+ };
26
+ }
27
+ const result = await startSuccessor({
28
+ options,
29
+ paths,
30
+ host,
31
+ owner: legacy,
32
+ drainGate: async () => (await counted?.recount(SESSION_COUNT_TIMEOUT_MS)) === 0,
33
+ });
34
+ if (result.action === "handoff" && legacy === undefined)
35
+ warnUnsignalledPredecessor(options.socket, host);
36
+ return result;
37
+ }
38
+ finally {
39
+ counted?.close();
40
+ }
41
+ }
42
+ /**
43
+ * The one record of a predecessor nobody could prove, on the caller's stderr: the endpoint's log belongs
44
+ * to the generations writing it. Its pid is not known: no record proves it, and a Unix socket's peer
45
+ * credentials are not readable from this runtime.
46
+ */
47
+ function warnUnsignalledPredecessor(socket, host) {
48
+ process.stderr.write(`generation handoff: no provable owner for ${socket}; the host it replaced (instance ${host.instanceId ?? "unknown"}, engine ${host.engineVersion ?? "unknown"}) listed 0 sessions and was not signalled; it drains itself on losing the public socket\n`);
49
+ }
50
+ //# sourceMappingURL=host-handoff-unregistered.js.map
@@ -1,5 +1,8 @@
1
1
  import type { HostLifecyclePolicyInput } from "./host-lifecycle.ts";
2
- /** The longest a handoff holds the ensure lock: its probe of the running host, then the successor's start. */
2
+ /**
3
+ * The longest a handoff holds the ensure lock: its probe of the running host, the two session counts
4
+ * an unregistered host gets (before the swap and the recount after it), then the successor's start.
5
+ */
3
6
  export declare const HANDOFF_LOCK_HOLD_MS: number;
4
7
  export interface HandoffHostOptions {
5
8
  readonly socket: string;
@@ -43,8 +46,10 @@ export type HandoffRefusal =
43
46
  | "handoff_unsupported"
44
47
  /** win32: a named pipe can be neither renamed nor drained. */
45
48
  | "upgrade_unsupported"
46
- /** The pidfile cannot prove which process serves this socket, so it may not be signalled. */
49
+ /** No record proves which process serves this socket, and that host holds sessions (or will not say). */
47
50
  | "unknown_owner"
51
+ /** A host from before layout 2, proven by its flat record, holds sessions; `detail` says how to retire it. */
52
+ | "legacy_host"
48
53
  /** The public socket stopped being the one this handoff was decided against. */
49
54
  | "socket_replaced"
50
55
  /** `<public>.next-<gen>` would exceed the platform's socket path limit. */
@@ -31,11 +31,15 @@ import { createDaemonDirectories, createHostDaemonPaths } from "./host-daemon-pa
31
31
  import { provenOwner, readHostRegistration } from "./host-daemon-registration.js";
32
32
  import { GENERATION_HANDOFF_CAPABILITY } from "./host-decision.js";
33
33
  import { acquireHostEnsureLock } from "./host-ensure-lock.js";
34
+ import { handoffUnregisteredHost, SESSION_COUNT_TIMEOUT_MS } from "./host-handoff-unregistered.js";
34
35
  import { probeProtocolInfo } from "./host-probe.js";
35
36
  import { SUCCESSOR_START_BUDGET_MS, startSuccessor } from "./host-successor.js";
36
37
  const HANDOFF_PROBE_TIMEOUT_MS = 10_000;
37
- /** The longest a handoff holds the ensure lock: its probe of the running host, then the successor's start. */
38
- export const HANDOFF_LOCK_HOLD_MS = HANDOFF_PROBE_TIMEOUT_MS + SUCCESSOR_START_BUDGET_MS;
38
+ /**
39
+ * The longest a handoff holds the ensure lock: its probe of the running host, the two session counts
40
+ * an unregistered host gets (before the swap and the recount after it), then the successor's start.
41
+ */
42
+ export const HANDOFF_LOCK_HOLD_MS = HANDOFF_PROBE_TIMEOUT_MS + 2 * SESSION_COUNT_TIMEOUT_MS + SUCCESSOR_START_BUDGET_MS;
39
43
  /**
40
44
  * How long a handoff waits for the lock. The longest holder is an ensure that probes the running host
41
45
  * and then hands it off itself (its upgrade path); 10 s of headroom for a slow runner.
@@ -74,7 +78,7 @@ export async function handoffHostLocked(options) {
74
78
  const registered = await readHostRegistration(paths);
75
79
  const owner = await provenOwner(registered, options.socket);
76
80
  if (!owner)
77
- return { action: "refuse", reason: "unknown_owner", upgradeable: true };
81
+ return handoffUnregisteredHost(options, paths, host);
78
82
  return startSuccessor({ options, paths, host, owner });
79
83
  }
80
84
  function handoffUnsupported(options) {
@@ -15,4 +15,7 @@ export declare function provenLegacyOwner(paths: HostDaemonPaths, socket: string
15
15
  pid: number;
16
16
  processStartTime: string;
17
17
  } | undefined>;
18
+ /** Why a proven legacy host that holds work is left alone, and the command that retires it. */
19
+ export declare function busyLegacyHostDetail(pid: number, socket: string, sessions: number | undefined): string;
20
+ export declare function describeSessions(sessions: number | undefined): string;
18
21
  //# sourceMappingURL=host-legacy.d.ts.map