@code-yeongyu/senpi 2026.10.16-3 → 2026.10.16-4

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 (99) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/bundle/chunks/{chunk-I5ZJEXTM.js → chunk-2NO5ZOYE.js} +6 -6
  3. package/dist/bundle/chunks/{chunk-4R4PRTF5.js → chunk-CJRE5LLR.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-X5VCHHXR.js → chunk-GY5O7NIQ.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-AVALXFDW.js → chunk-JD4CV3GH.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-SSEGIXRL.js → chunk-KUQ3K33L.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-FMYLLJBQ.js → chunk-KWC3MCLP.js} +1 -1
  8. package/dist/bundle/chunks/chunk-MLL7AGVM.js +3 -0
  9. package/dist/bundle/chunks/chunk-PAJKEG2L.js +8 -0
  10. package/dist/bundle/chunks/{chunk-DPRV3FR7.js → chunk-PWHAOWNH.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-HJPX7PBL.js → chunk-XCRGEMY2.js} +125 -118
  12. package/dist/bundle/chunks/{cli-main-JVPFJGP5.js → cli-main-I6JF2GPS.js} +1 -1
  13. package/dist/bundle/chunks/{help-fast-path-SVCMHCYG.js → help-fast-path-APSHUDY6.js} +1 -1
  14. package/dist/bundle/chunks/{host-session-command-46PTZGIB.js → host-session-command-BUJUJHDA.js} +1 -1
  15. package/dist/bundle/chunks/{interactive-mode-BROZRY34.js → interactive-mode-4Q3TIXOZ.js} +1 -1
  16. package/dist/bundle/chunks/{multi-session-host-SMQR5SCJ.js → multi-session-host-XEZB2XVR.js} +5 -4
  17. package/dist/bundle/chunks/{package-manager-cli-2QFJY2AS.js → package-manager-cli-YWZHOZOY.js} +1 -1
  18. package/dist/bundle/chunks/{rotation-stream-QX7YSKDU.js → rotation-stream-HY3JPQCX.js} +1 -1
  19. package/dist/bundle/chunks/{rpc-mode-Z45T3NZO.js → rpc-mode-SLWXVXXE.js} +1 -1
  20. package/dist/bundle/chunks/{schedule-command-2RHSWBQO.js → schedule-command-JRWZGEDU.js} +1 -1
  21. package/dist/bundle/chunks/{session-control-endpoint-H7FFWF2A.js → session-control-endpoint-E2ZSEWXW.js} +1 -1
  22. package/dist/bundle/chunks/session-picker-5IZY7E3G.js +2 -0
  23. package/dist/bundle/chunks/session-worker.js +243 -235
  24. package/dist/bundle/cli.js +2 -2
  25. package/dist/bundle/index.js +1 -1
  26. package/dist/bundle/rpc-entry.js +1 -1
  27. package/dist/bundle/runtime-manifest.json +1 -1
  28. package/dist/core/agent-session-runtime.d.ts +15 -0
  29. package/dist/core/agent-session-runtime.js +53 -2
  30. package/dist/core/agent-session.d.ts +12 -0
  31. package/dist/core/agent-session.js +42 -1
  32. package/dist/core/context-files.d.ts +21 -0
  33. package/dist/core/context-files.js +175 -0
  34. package/dist/core/diagnostics.d.ts +1 -0
  35. package/dist/core/extensions/builtin/anthropic-subscription/account-command.js +26 -3
  36. package/dist/core/extensions/builtin/anthropic-subscription/account-management.d.ts +5 -0
  37. package/dist/core/extensions/builtin/anthropic-subscription/account-management.js +40 -0
  38. package/dist/core/extensions/builtin/anthropic-subscription/accounts.d.ts +3 -0
  39. package/dist/core/extensions/builtin/anthropic-subscription/accounts.js +1 -1
  40. package/dist/core/extensions/builtin/anthropic-subscription/affinity.js +1 -1
  41. package/dist/core/extensions/builtin/anthropic-subscription/auth-lane.js +1 -0
  42. package/dist/core/extensions/builtin/anthropic-subscription/failover.d.ts +10 -5
  43. package/dist/core/extensions/builtin/anthropic-subscription/failover.js +158 -17
  44. package/dist/core/extensions/builtin/anthropic-subscription/usage-limit-block.d.ts +13 -0
  45. package/dist/core/extensions/builtin/anthropic-subscription/usage-limit-block.js +89 -0
  46. package/dist/core/extensions/builtin/permission-system/always-scope.d.ts +34 -0
  47. package/dist/core/extensions/builtin/permission-system/always-scope.js +77 -0
  48. package/dist/core/extensions/builtin/permission-system/index.js +3 -1
  49. package/dist/core/extensions/builtin/permission-system/parsers.d.ts +1 -1
  50. package/dist/core/extensions/builtin/permission-system/parsers.js +24 -3
  51. package/dist/core/extensions/builtin/permission-system/prompt.js +5 -1
  52. package/dist/core/extensions/builtin/permission-system/service.js +1 -1
  53. package/dist/core/extensions/builtin/permission-system/types.d.ts +7 -0
  54. package/dist/core/package-manager.js +4 -32
  55. package/dist/core/project-trust.d.ts +8 -0
  56. package/dist/core/project-trust.js +12 -0
  57. package/dist/core/resource-loader.d.ts +5 -7
  58. package/dist/core/resource-loader.js +11 -84
  59. package/dist/core/retry-fallback/circuit-probes.d.ts +1 -0
  60. package/dist/core/retry-fallback/circuit-probes.js +3 -0
  61. package/dist/core/retry-fallback/circuit.d.ts +5 -0
  62. package/dist/core/retry-fallback/circuit.js +27 -4
  63. package/dist/core/retry-fallback/controller.d.ts +9 -4
  64. package/dist/core/retry-fallback/controller.js +21 -4
  65. package/dist/core/settings-manager.d.ts +15 -0
  66. package/dist/core/settings-manager.js +21 -1
  67. package/dist/core/skills-prompt.d.ts +18 -0
  68. package/dist/core/skills-prompt.js +131 -0
  69. package/dist/core/skills.d.ts +1 -9
  70. package/dist/core/skills.js +1 -59
  71. package/dist/core/trust-manager.d.ts +13 -4
  72. package/dist/core/trust-manager.js +52 -21
  73. package/dist/main.js +23 -4
  74. package/dist/modes/interactive/interactive-mode.js +10 -3
  75. package/dist/modes/rpc/abort-grace.d.ts +9 -0
  76. package/dist/modes/rpc/abort-grace.js +11 -0
  77. package/dist/modes/rpc/effect-commands.d.ts +0 -2
  78. package/dist/modes/rpc/effect-commands.js +2 -3
  79. package/dist/modes/rpc/host-handover-parked.d.ts +6 -0
  80. package/dist/modes/rpc/host-handover-parked.js +1 -0
  81. package/dist/modes/rpc/host-handover-reopen.js +11 -2
  82. package/dist/modes/rpc/rpc-client.d.ts +28 -2
  83. package/dist/modes/rpc/rpc-client.js +24 -11
  84. package/dist/modes/rpc/rpc-request-deadline.d.ts +12 -0
  85. package/dist/modes/rpc/rpc-request-deadline.js +15 -0
  86. package/dist/modes/rpc/session-command-router.js +7 -4
  87. package/dist/modes/rpc/session-registry-attach.js +6 -1
  88. package/dist/modes/rpc/session-registry-claims.d.ts +22 -2
  89. package/dist/modes/rpc/session-registry-claims.js +68 -0
  90. package/dist/modes/rpc/session-registry-opening.d.ts +23 -0
  91. package/dist/modes/rpc/session-registry-opening.js +57 -0
  92. package/dist/modes/rpc/session-registry.d.ts +1 -0
  93. package/dist/modes/rpc/session-registry.js +48 -60
  94. package/docs/rpc.md +6 -2
  95. package/docs/settings.md +13 -0
  96. package/package.json +6 -6
  97. package/dist/bundle/chunks/chunk-6MEETY7N.js +0 -8
  98. package/dist/bundle/chunks/chunk-TEGEPQIA.js +0 -3
  99. package/dist/bundle/chunks/session-picker-2O2BNBVE.js +0 -2
@@ -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
- import{enableStartupCompileCache}from"./chunks/chunk-FMYLLJBQ.js";import{captureStdout,exitAfterOutput,getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,printThenExit,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-X5VCHHXR.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-NP42HAJO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync3,realpathSync as realpathSync5}from"node:fs";import{dirname as dirname4,join as join8}from"node:path";import{fileURLToPath}from"node:url";import{createHash}from"node:crypto";import{readFileSync as readFileSync5,realpathSync as realpathSync4}from"node:fs";import{basename as basename2,dirname as dirname3,join as join6,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync as existsSync2,readFileSync as readFileSync3,realpathSync as realpathSync3,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname as dirname2,join as join4}from"node:path";import{existsSync,readFileSync}from"node:fs";import{join}from"node:path";var INERT_TREE=/^(?:tests?|__tests__|__fixtures__|fixtures|docs?|examples?|bench(?:marks?)?)$/,ROOT_NOTES=/^(?:readme|changelog|history)(?:\.[^/]*)?$/i,ROOT_MARKDOWN=/^[^/]+\.md$/i,LICENSE=/^licen[cs]e(?:\.[^/]*)?$/i;function dependencyFileExclusions(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return()=>!1;let entryRoots=new Set,built=!1,visit=value=>{if(typeof value=="string"){let entry=value.replace(/^\.\//,"");entryRoots.add(entry.split("/")[0]??""),/\.[cm]?js$/.test(entry)&&existsSync(join(packageDir,entry))&&(built=!0)}else if(Array.isArray(value))for(let child of value)visit(child);else if(typeof value=="object"&&value!==null)for(let[condition,child]of Object.entries(value))condition!=="types"&&visit(child)};for(let[key,value]of Object.entries(manifest))["main","module","exports","bin","pi"].includes(key)&&visit(value);return path=>{let root=path.split("/")[0]??"";return entryRoots.has(root)||entryRoots.has("*")||entryRoots.has("**")?!1:INERT_TREE.test(root)||ROOT_NOTES.test(path)||ROOT_MARKDOWN.test(path)&&!LICENSE.test(path)?!0:built&&root==="src"&&/\.[cm]?tsx?$/.test(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))}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{dirname,join as join3}from"node:path";import{mkdirSync,readdirSync,realpathSync,statSync}from"node:fs";import{join as join2}from"node:path";var 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,excluded=()=>!1,relativeDir=""){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 relativePath=relativeDir===""?entry.name:`${relativeDir}/${entry.name}`;if(excluded(relativePath))continue;let from=join2(real,entry.name),to=join2(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen,excluded,relativePath);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,excluded,relativePath):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}var ALWAYS_SHIPPED=/^(?:package\.json|readme(?:\..*)?|licen[cs]e(?:\..*)?)$/i;function globToRegExp(glob){let source="";for(let index=0;index<glob.length;index++){let char=glob[index];glob.startsWith("**/",index)?(source+="(?:.*/)?",index+=2):glob.startsWith("**",index)?(source+=".*",index+=1):char==="*"?source+="[^/]*":char==="?"?source+="[^/]":source+=char.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${source}(?:/.*)?$`)}function shippedEntries(packageDir){let manifest=JSON.parse(readFileSync2(join3(packageDir,"package.json"),"utf8")),listed=typeof manifest=="object"&&manifest!==null?manifest.files:void 0;if(!Array.isArray(listed)||!listed.every(entry=>typeof entry=="string"))return;let normalize=entry=>entry.replace(/^\.\//,"").replace(/\/+$/,"");return{include:listed.filter(entry=>!entry.startsWith("!")).map(normalize),exclude:listed.filter(entry=>entry.startsWith("!")).map(entry=>globToRegExp(normalize(entry.slice(1))))}}function planPackageRoot(packageDir,target,files){let shipped=shippedEntries(packageDir);if(shipped===void 0){planTree(packageDir,target,files,!0);return}let root=realpathSync2(packageDir),excluded=relativePath=>shipped.exclude.some(pattern=>pattern.test(relativePath)),planned=new Set,plan=relativePath=>{if(planned.has(relativePath)||excluded(relativePath))return;let from=join3(root,relativePath),isDirectory;try{isDirectory=statSync2(from).isDirectory()}catch(error){if(isMissing(error))return;throw error}planned.add(relativePath);let to=join3(target,relativePath);isDirectory?planTree(from,to,files,!0,new Set([root]),excluded,relativePath):UNLOADED_FILE.test(relativePath)||(mkdirSync2(dirname(to),{recursive:!0}),files.push([realpathSync2(from),to]))};mkdirSync2(target,{recursive:!0});let topLevel=readdirSync2(root).filter(name=>name!=="node_modules");for(let name of topLevel)ALWAYS_SHIPPED.test(name)&&plan(name);for(let entry of shipped.include){let segments=entry.split("/"),wildcard=segments.findIndex(segment=>/[*?]/.test(segment));if(wildcard===-1)plan(entry);else if(wildcard>0)plan(segments.slice(0,wildcard).join("/"));else{let pattern=globToRegExp(segments[0]??"");for(let name of topLevel)pattern.test(name)&&plan(name)}}}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-";function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname2(current)){if(basename(current)!=="node_modules"){let candidate=join4(current,"node_modules");existsSync2(candidate)&&directories.push(candidate)}if(dirname2(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join4(modules,packageName);if(existsSync2(join4(root,"package.json")))return realpathSync3(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync3(join4(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=[realpathSync3(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=realpathSync3(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0,new Set,dependencyFileExclusions(installDir)),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname2(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join4(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname2(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join4(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,join4(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=>join4(modules,name)).find(root=>existsSync2(join4(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=join4(dirname2(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planPackageRoot(packageDir,staging,files);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join4(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync3(packageDir)};writeFileSync(join4(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 mkdirSync3,readdirSync as readdirSync3,readFileSync as readFileSync4,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync3,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join5}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-statSync3(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){mkdirSync3(root,{recursive:!0});let lock=join5(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync3(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(readFileSync4(join5(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){mkdirSync3(root,{recursive:!0});let lock=join5(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync3(lock),writeFileSync2(join5(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 readdirSync3(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join5(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){mkdirSync3(join5(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join5(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join5(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync3(join5(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(join5(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join5(root,keep),isAlive);for(let name of readdirSync3(root)){if(name===LOCK_NAME||name===keep)continue;let path=join5(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join5(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join5(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(readFileSync5(join6(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=dirname3(entryPath),runtimeRoot=join6(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)!==join6("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync4(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join6(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(join6(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync6}from"node:fs";import{join as join7}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(readFileSync6(join7(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(existsSync3,realpathSync5),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync5(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();await 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=>!existsSync3(join8(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"))&&await printThenExit(()=>console.log(DISPLAY_VERSION));if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-SVCMHCYG.js"),help=await captureStdout(()=>tryPrintHelpWithoutEngine(args));help.result&&await exitAfterOutput(help.output),process.stdout.write(help.output)}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(dirname4(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-JVPFJGP5.js")}
3
+ import{enableStartupCompileCache}from"./chunks/chunk-KWC3MCLP.js";import{captureStdout,exitAfterOutput,getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,printThenExit,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-GY5O7NIQ.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-NP42HAJO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync3,realpathSync as realpathSync5}from"node:fs";import{dirname as dirname4,join as join8}from"node:path";import{fileURLToPath}from"node:url";import{createHash}from"node:crypto";import{readFileSync as readFileSync5,realpathSync as realpathSync4}from"node:fs";import{basename as basename2,dirname as dirname3,join as join6,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync as existsSync2,readFileSync as readFileSync3,realpathSync as realpathSync3,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname as dirname2,join as join4}from"node:path";import{existsSync,readFileSync}from"node:fs";import{join}from"node:path";var INERT_TREE=/^(?:tests?|__tests__|__fixtures__|fixtures|docs?|examples?|bench(?:marks?)?)$/,ROOT_NOTES=/^(?:readme|changelog|history)(?:\.[^/]*)?$/i,ROOT_MARKDOWN=/^[^/]+\.md$/i,LICENSE=/^licen[cs]e(?:\.[^/]*)?$/i;function dependencyFileExclusions(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return()=>!1;let entryRoots=new Set,built=!1,visit=value=>{if(typeof value=="string"){let entry=value.replace(/^\.\//,"");entryRoots.add(entry.split("/")[0]??""),/\.[cm]?js$/.test(entry)&&existsSync(join(packageDir,entry))&&(built=!0)}else if(Array.isArray(value))for(let child of value)visit(child);else if(typeof value=="object"&&value!==null)for(let[condition,child]of Object.entries(value))condition!=="types"&&visit(child)};for(let[key,value]of Object.entries(manifest))["main","module","exports","bin","pi"].includes(key)&&visit(value);return path=>{let root=path.split("/")[0]??"";return entryRoots.has(root)||entryRoots.has("*")||entryRoots.has("**")?!1:INERT_TREE.test(root)||ROOT_NOTES.test(path)||ROOT_MARKDOWN.test(path)&&!LICENSE.test(path)?!0:built&&root==="src"&&/\.[cm]?tsx?$/.test(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))}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{dirname,join as join3}from"node:path";import{mkdirSync,readdirSync,realpathSync,statSync}from"node:fs";import{join as join2}from"node:path";var 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,excluded=()=>!1,relativeDir=""){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 relativePath=relativeDir===""?entry.name:`${relativeDir}/${entry.name}`;if(excluded(relativePath))continue;let from=join2(real,entry.name),to=join2(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen,excluded,relativePath);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,excluded,relativePath):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}var ALWAYS_SHIPPED=/^(?:package\.json|readme(?:\..*)?|licen[cs]e(?:\..*)?)$/i;function globToRegExp(glob){let source="";for(let index=0;index<glob.length;index++){let char=glob[index];glob.startsWith("**/",index)?(source+="(?:.*/)?",index+=2):glob.startsWith("**",index)?(source+=".*",index+=1):char==="*"?source+="[^/]*":char==="?"?source+="[^/]":source+=char.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${source}(?:/.*)?$`)}function shippedEntries(packageDir){let manifest=JSON.parse(readFileSync2(join3(packageDir,"package.json"),"utf8")),listed=typeof manifest=="object"&&manifest!==null?manifest.files:void 0;if(!Array.isArray(listed)||!listed.every(entry=>typeof entry=="string"))return;let normalize=entry=>entry.replace(/^\.\//,"").replace(/\/+$/,"");return{include:listed.filter(entry=>!entry.startsWith("!")).map(normalize),exclude:listed.filter(entry=>entry.startsWith("!")).map(entry=>globToRegExp(normalize(entry.slice(1))))}}function planPackageRoot(packageDir,target,files){let shipped=shippedEntries(packageDir);if(shipped===void 0){planTree(packageDir,target,files,!0);return}let root=realpathSync2(packageDir),excluded=relativePath=>shipped.exclude.some(pattern=>pattern.test(relativePath)),planned=new Set,plan=relativePath=>{if(planned.has(relativePath)||excluded(relativePath))return;let from=join3(root,relativePath),isDirectory;try{isDirectory=statSync2(from).isDirectory()}catch(error){if(isMissing(error))return;throw error}planned.add(relativePath);let to=join3(target,relativePath);isDirectory?planTree(from,to,files,!0,new Set([root]),excluded,relativePath):UNLOADED_FILE.test(relativePath)||(mkdirSync2(dirname(to),{recursive:!0}),files.push([realpathSync2(from),to]))};mkdirSync2(target,{recursive:!0});let topLevel=readdirSync2(root).filter(name=>name!=="node_modules");for(let name of topLevel)ALWAYS_SHIPPED.test(name)&&plan(name);for(let entry of shipped.include){let segments=entry.split("/"),wildcard=segments.findIndex(segment=>/[*?]/.test(segment));if(wildcard===-1)plan(entry);else if(wildcard>0)plan(segments.slice(0,wildcard).join("/"));else{let pattern=globToRegExp(segments[0]??"");for(let name of topLevel)pattern.test(name)&&plan(name)}}}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-";function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname2(current)){if(basename(current)!=="node_modules"){let candidate=join4(current,"node_modules");existsSync2(candidate)&&directories.push(candidate)}if(dirname2(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join4(modules,packageName);if(existsSync2(join4(root,"package.json")))return realpathSync3(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync3(join4(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=[realpathSync3(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=realpathSync3(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0,new Set,dependencyFileExclusions(installDir)),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname2(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join4(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname2(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join4(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,join4(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=>join4(modules,name)).find(root=>existsSync2(join4(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=join4(dirname2(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planPackageRoot(packageDir,staging,files);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join4(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync3(packageDir)};writeFileSync(join4(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 mkdirSync3,readdirSync as readdirSync3,readFileSync as readFileSync4,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync3,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join5}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-statSync3(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){mkdirSync3(root,{recursive:!0});let lock=join5(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync3(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(readFileSync4(join5(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){mkdirSync3(root,{recursive:!0});let lock=join5(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync3(lock),writeFileSync2(join5(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 readdirSync3(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join5(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){mkdirSync3(join5(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join5(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join5(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync3(join5(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(join5(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join5(root,keep),isAlive);for(let name of readdirSync3(root)){if(name===LOCK_NAME||name===keep)continue;let path=join5(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join5(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join5(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(readFileSync5(join6(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=dirname3(entryPath),runtimeRoot=join6(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)!==join6("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync4(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join6(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(join6(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync6}from"node:fs";import{join as join7}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(readFileSync6(join7(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(existsSync3,realpathSync5),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync5(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();await 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=>!existsSync3(join8(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"))&&await printThenExit(()=>console.log(DISPLAY_VERSION));if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-APSHUDY6.js"),help=await captureStdout(()=>tryPrintHelpWithoutEngine(args));help.result&&await exitAfterOutput(help.output),process.stdout.write(help.output)}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(dirname4(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-I6JF2GPS.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,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,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,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-HJPX7PBL.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-6MEETY7N.js";import"./chunks/chunk-43WLJPEG.js";import"./chunks/chunk-4R4PRTF5.js";import{DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,SettingsManager,Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,parseSkillBlock,rawKeyHint}from"./chunks/chunk-I5ZJEXTM.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-P37AEPIE.js";import"./chunks/chunk-DCQCK6CK.js";import"./chunks/chunk-M2NJDRVW.js";import"./chunks/chunk-77PE5H2A.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-UUMKAA7S.js";import"./chunks/chunk-AVALXFDW.js";import"./chunks/chunk-IRKWZZKD.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-TEGEPQIA.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-D6XX3VBK.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-QN2BHP3M.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest}from"./chunks/chunk-MBT6FT2E.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,listHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-EL4NYWZT.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-ZMUAAPGV.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-DPRV3FR7.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-SSEGIXRL.js";import"./chunks/chunk-QC4KECXI.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-VNVSXIJO.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import{parseArgs}from"./chunks/chunk-BJ7LHDCD.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ZDTNH3XU.js";import"./chunks/chunk-5HYU3KLH.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-BPOEQRHX.js";import"./chunks/chunk-7ASLQ243.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-G3OOGWMC.js";import"./chunks/chunk-X5VCHHXR.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-NP42HAJO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-QXREUA5F.js";import"./chunks/chunk-WASCMT6Y.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-RUGYFYH7.js";import"./chunks/chunk-PFNBY43W.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-UAQW2T7G.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-4D2PPFKR.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-2ON6BFHO.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,findReservedKeywordRuns,findReservedKeywordSpans,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,sessionControlSenderOf,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,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,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,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-XCRGEMY2.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-PAJKEG2L.js";import"./chunks/chunk-43WLJPEG.js";import"./chunks/chunk-CJRE5LLR.js";import{DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,SettingsManager,Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,parseSkillBlock,rawKeyHint}from"./chunks/chunk-2NO5ZOYE.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-P37AEPIE.js";import"./chunks/chunk-DCQCK6CK.js";import"./chunks/chunk-M2NJDRVW.js";import"./chunks/chunk-77PE5H2A.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-UUMKAA7S.js";import"./chunks/chunk-JD4CV3GH.js";import"./chunks/chunk-IRKWZZKD.js";import"./chunks/chunk-JABBHOD5.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-MLL7AGVM.js";import"./chunks/chunk-D6XX3VBK.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-QN2BHP3M.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest}from"./chunks/chunk-MBT6FT2E.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,listHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-EL4NYWZT.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-ZMUAAPGV.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-PWHAOWNH.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-KUQ3K33L.js";import"./chunks/chunk-QC4KECXI.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-VNVSXIJO.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import{parseArgs}from"./chunks/chunk-BJ7LHDCD.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ZDTNH3XU.js";import"./chunks/chunk-5HYU3KLH.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-BPOEQRHX.js";import"./chunks/chunk-7ASLQ243.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-G3OOGWMC.js";import"./chunks/chunk-GY5O7NIQ.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-NP42HAJO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-QXREUA5F.js";import"./chunks/chunk-WASCMT6Y.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-RUGYFYH7.js";import"./chunks/chunk-PFNBY43W.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-UAQW2T7G.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-4D2PPFKR.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-2ON6BFHO.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,findReservedKeywordRuns,findReservedKeywordSpans,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,sessionControlSenderOf,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,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-HJPX7PBL.js";import"./chunks/chunk-6MEETY7N.js";import"./chunks/chunk-43WLJPEG.js";import"./chunks/chunk-4R4PRTF5.js";import{configureHttpDispatcher}from"./chunks/chunk-I5ZJEXTM.js";import"./chunks/chunk-P37AEPIE.js";import"./chunks/chunk-DCQCK6CK.js";import"./chunks/chunk-M2NJDRVW.js";import"./chunks/chunk-77PE5H2A.js";import"./chunks/chunk-UUMKAA7S.js";import"./chunks/chunk-AVALXFDW.js";import"./chunks/chunk-IRKWZZKD.js";import"./chunks/chunk-TEGEPQIA.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-D6XX3VBK.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-QN2BHP3M.js";import"./chunks/chunk-MBT6FT2E.js";import"./chunks/chunk-EL4NYWZT.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-ZMUAAPGV.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-DPRV3FR7.js";import"./chunks/chunk-SSEGIXRL.js";import"./chunks/chunk-QC4KECXI.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-VNVSXIJO.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-BJ7LHDCD.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ZDTNH3XU.js";import"./chunks/chunk-5HYU3KLH.js";import"./chunks/chunk-BPOEQRHX.js";import"./chunks/chunk-7ASLQ243.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-G3OOGWMC.js";import"./chunks/chunk-X5VCHHXR.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-NP42HAJO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-QXREUA5F.js";import"./chunks/chunk-WASCMT6Y.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-RUGYFYH7.js";import"./chunks/chunk-PFNBY43W.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-UAQW2T7G.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-4D2PPFKR.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-2ON6BFHO.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-XCRGEMY2.js";import"./chunks/chunk-PAJKEG2L.js";import"./chunks/chunk-43WLJPEG.js";import"./chunks/chunk-CJRE5LLR.js";import{configureHttpDispatcher}from"./chunks/chunk-2NO5ZOYE.js";import"./chunks/chunk-P37AEPIE.js";import"./chunks/chunk-DCQCK6CK.js";import"./chunks/chunk-M2NJDRVW.js";import"./chunks/chunk-77PE5H2A.js";import"./chunks/chunk-UUMKAA7S.js";import"./chunks/chunk-JD4CV3GH.js";import"./chunks/chunk-IRKWZZKD.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-MLL7AGVM.js";import"./chunks/chunk-D6XX3VBK.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-QN2BHP3M.js";import"./chunks/chunk-MBT6FT2E.js";import"./chunks/chunk-EL4NYWZT.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-ZMUAAPGV.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-PWHAOWNH.js";import"./chunks/chunk-KUQ3K33L.js";import"./chunks/chunk-QC4KECXI.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-VNVSXIJO.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-BJ7LHDCD.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ZDTNH3XU.js";import"./chunks/chunk-5HYU3KLH.js";import"./chunks/chunk-BPOEQRHX.js";import"./chunks/chunk-7ASLQ243.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-G3OOGWMC.js";import"./chunks/chunk-GY5O7NIQ.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-NP42HAJO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-QXREUA5F.js";import"./chunks/chunk-WASCMT6Y.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-RUGYFYH7.js";import"./chunks/chunk-PFNBY43W.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-UAQW2T7G.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-4D2PPFKR.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-2ON6BFHO.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":"74e2d0c17bb63efc","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"af5b0670fb147d75","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
@@ -122,6 +122,21 @@ export declare class AgentSessionRuntime {
122
122
  * fork) keep it.
123
123
  */
124
124
  setPermissionPreset(preset: string): void;
125
+ /** The session teardownCurrent disposed; it stays the live session only until apply() installs a replacement. */
126
+ private _disposedSession;
127
+ /**
128
+ * Keeps a Full-access-only project trust in step with the preset (senpi#3414, #3420). Leaving Full
129
+ * access withdraws it, unless the user has since saved "trust"; going back restores it, unless the
130
+ * user saved "do not trust". Either way the session's runtime is rebuilt so project extensions,
131
+ * skills, hooks and MCP servers load or unload, and nothing can cancel that rebuild. The trust is
132
+ * never saved. Returns the rebuild, or undefined when the trust did not change.
133
+ */
134
+ private syncFullAccessTrust;
135
+ /** Settles when the rebuild that followed a Full-access trust change has finished. */
136
+ get projectTrustChange(): Promise<void>;
137
+ private _projectTrustChange;
138
+ /** Failed trust rebuilds; kept across session replacement so the error stays visible. */
139
+ private _trustChangeDiagnostics;
125
140
  /**
126
141
  * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements
127
142
  * (switch, new, fork) keep it. Callers set it before the first turn: a chain never changes under a
@@ -7,6 +7,7 @@ import { holdSessionFile } from "./session-holders.js";
7
7
  import { SessionManager } from "./session-manager.js";
8
8
  import { reserveSessionWrite, unregisterSessionWriter } from "./session-write-reservation.js";
9
9
  import { resetTimings, time } from "./timings.js";
10
+ import { ProjectTrustStore } from "./trust-manager.js";
10
11
  /** Overlays a session's fallback policy on its settings in memory: never saved, never shared. */
11
12
  export function applyRetryFallbackProfile(settingsManager, profile) {
12
13
  settingsManager.applyOverrides({
@@ -45,6 +46,9 @@ function extractUserMessageText(content) {
45
46
  export class AgentSessionRuntime {
46
47
  constructor(_session, _services, createRuntime, _diagnostics = [], _modelFallbackMessage, launchProfile) {
47
48
  this.sessionReplaceListeners = new Set();
49
+ this._projectTrustChange = Promise.resolve();
50
+ /** Failed trust rebuilds; kept across session replacement so the error stays visible. */
51
+ this._trustChangeDiagnostics = [];
48
52
  this._session = _session;
49
53
  this._services = _services;
50
54
  this.createRuntime = createRuntime;
@@ -68,7 +72,9 @@ export class AgentSessionRuntime {
68
72
  return this._services.cwd;
69
73
  }
70
74
  get diagnostics() {
71
- return this._diagnostics;
75
+ return this._trustChangeDiagnostics.length === 0
76
+ ? this._diagnostics
77
+ : [...this._diagnostics, ...this._trustChangeDiagnostics];
72
78
  }
73
79
  get modelFallbackMessage() {
74
80
  return this._modelFallbackMessage;
@@ -94,6 +100,40 @@ export class AgentSessionRuntime {
94
100
  setPermissionPreset(preset) {
95
101
  this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), permissionPreset: preset });
96
102
  this._session.extensionRunner.setFlagValue("permission-preset", preset);
103
+ // While a replacement is in flight (or after one failed) the live session is the disposed one:
104
+ // nothing may rebuild it. The preset is recorded above, and apply() syncs the next replacement to
105
+ // it before that one goes live. There is no flag to clear: the check is the session itself.
106
+ if (this._session !== this._disposedSession)
107
+ this.syncFullAccessTrust(this._session, preset);
108
+ }
109
+ /**
110
+ * Keeps a Full-access-only project trust in step with the preset (senpi#3414, #3420). Leaving Full
111
+ * access withdraws it, unless the user has since saved "trust"; going back restores it, unless the
112
+ * user saved "do not trust". Either way the session's runtime is rebuilt so project extensions,
113
+ * skills, hooks and MCP servers load or unload, and nothing can cancel that rebuild. The trust is
114
+ * never saved. Returns the rebuild, or undefined when the trust did not change.
115
+ */
116
+ syncFullAccessTrust(session, preset) {
117
+ const settings = session.settingsManager;
118
+ // The session's own project: a replacement can belong to another project than the retired one (#3420 review).
119
+ const saved = new ProjectTrustStore(this.services.agentDir).get(session.sessionManager.getCwd());
120
+ if (preset !== "full-access" && settings.isTrustFromFullAccess() && saved !== true)
121
+ settings.setProjectTrusted(false);
122
+ else if (preset === "full-access" && settings.canRestoreFullAccessTrust() && saved !== false)
123
+ settings.setProjectTrusted(true);
124
+ else
125
+ return undefined;
126
+ this._projectTrustChange = session.applyProjectTrustChange().catch((error) => {
127
+ this._trustChangeDiagnostics = [
128
+ ...this._trustChangeDiagnostics,
129
+ { type: "error", message: `Updating project code after a Full access change failed: ${String(error)}` },
130
+ ];
131
+ });
132
+ return this._projectTrustChange;
133
+ }
134
+ /** Settles when the rebuild that followed a Full-access trust change has finished. */
135
+ get projectTrustChange() {
136
+ return this._projectTrustChange;
97
137
  }
98
138
  /**
99
139
  * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements
@@ -204,6 +244,7 @@ export class AgentSessionRuntime {
204
244
  this.beforeSessionInvalidate?.();
205
245
  const replaced = this.session.sessionManager;
206
246
  this.session.dispose();
247
+ this._disposedSession = this.session;
207
248
  // Nothing writes to the replaced manager once its session is disposed, so the
208
249
  // shared host may hand its session file to another worker.
209
250
  unregisterSessionWriter(replaced);
@@ -227,10 +268,20 @@ export class AgentSessionRuntime {
227
268
  async apply(result, hold) {
228
269
  this._sessionHold =
229
270
  hold ?? holdActiveSession(result.session.sessionManager, false, this._launchProfile?.holderEndpoint);
230
- this._session = result.session;
231
271
  // The replacement was built from the profile read before its runtime was created; an attach
232
272
  // that moved a setting while it was being built reached only the retired session (senpi#2842).
273
+ // Its project trust follows the CURRENT preset before it goes live: a replacement built while the
274
+ // session was still Full access must not be reachable with that trust's project code (#3420). A
275
+ // preset change that lands while that rebuild runs reaches only the retired session, so sync
276
+ // again until the preset stops moving, then install the profile read last.
277
+ let syncedPreset;
278
+ while (this._launchProfile?.permissionPreset !== undefined &&
279
+ this._launchProfile.permissionPreset !== syncedPreset) {
280
+ syncedPreset = this._launchProfile.permissionPreset;
281
+ await this.syncFullAccessTrust(result.session, syncedPreset);
282
+ }
233
283
  const profile = this._launchProfile;
284
+ this._session = result.session;
234
285
  if (profile?.permissionPreset !== undefined)
235
286
  this._session.extensionRunner.setFlagValue("permission-preset", profile.permissionPreset);
236
287
  if (profile?.promptSurface !== undefined)
@@ -561,6 +561,8 @@ export declare class AgentSession {
561
561
  private _continueWithQueuedInput;
562
562
  /** True while a reload's `session_start` handlers run; a nested reload would retire the runner they run on. */
563
563
  private _sessionStartDispatching;
564
+ /** Waiters for the moment no prompt start is pending and no session start is dispatching (applyProjectTrustChange). */
565
+ private _admissionIdleWaiters;
564
566
  /** User-abort generation at the start of an idle trigger turn's awaited admission hooks. */
565
567
  private _triggerTurnAdmissionAbortGeneration;
566
568
  private _engineTurnStarts;
@@ -1731,6 +1733,16 @@ export declare class AgentSession {
1731
1733
  cancelled: boolean;
1732
1734
  reason?: string;
1733
1735
  }>;
1736
+ /**
1737
+ * Loads or unloads the project's code after the session's project trust changed (Full access left or
1738
+ * re-entered, senpi#3420): rebuilds the runtime exactly like reload(), but nothing can cancel it. No
1739
+ * `session_before_reload` handler runs (a project extension must not keep itself loaded); a prompt
1740
+ * that is being admitted, or a session start in dispatch, is waited out instead of cancelling, and
1741
+ * prompts admitted after that wait for the rebuilt runtime. A reload already in flight sees the trust
1742
+ * epoch move and loads again before it installs anything.
1743
+ */
1744
+ applyProjectTrustChange(): Promise<void>;
1745
+ private _notifyAdmissionIdle;
1734
1746
  private _rebuildRuntimeForReload;
1735
1747
  /**
1736
1748
  * Ask extensions whether a full session reload may proceed by emitting the
@@ -325,6 +325,8 @@ export class AgentSession {
325
325
  this._continueWithQueuedInput = false;
326
326
  /** True while a reload's `session_start` handlers run; a nested reload would retire the runner they run on. */
327
327
  this._sessionStartDispatching = false;
328
+ /** Waiters for the moment no prompt start is pending and no session start is dispatching (applyProjectTrustChange). */
329
+ this._admissionIdleWaiters = [];
328
330
  this._engineTurnStarts = [];
329
331
  this._engineTurnPauseRecorded = false;
330
332
  this._nextInputId = 0;
@@ -2256,7 +2258,7 @@ export class AgentSession {
2256
2258
  assistantMsg.stopReason !== "aborted" &&
2257
2259
  !isClassifierRefusal(assistantMsg);
2258
2260
  if (succeeded)
2259
- this._retryFallback.probes.accept(`${assistantMsg.provider}/${assistantMsg.model}`);
2261
+ this._retryFallback.noteServed(`${assistantMsg.provider}/${assistantMsg.model}`);
2260
2262
  if (succeeded && assistantMsg.stopReason !== "length") {
2261
2263
  this._overflowRecoveryRungs = 0;
2262
2264
  }
@@ -3685,6 +3687,7 @@ export class AgentSession {
3685
3687
  return;
3686
3688
  claim.started = started;
3687
3689
  this._promptStartPending = false;
3690
+ this._notifyAdmissionIdle();
3688
3691
  if (!started && claim.joined === true && !this.isStreaming)
3689
3692
  this._drainJoinedInput();
3690
3693
  };
@@ -8102,6 +8105,34 @@ export class AgentSession {
8102
8105
  finishReloadWork();
8103
8106
  }
8104
8107
  }
8108
+ /**
8109
+ * Loads or unloads the project's code after the session's project trust changed (Full access left or
8110
+ * re-entered, senpi#3420): rebuilds the runtime exactly like reload(), but nothing can cancel it. No
8111
+ * `session_before_reload` handler runs (a project extension must not keep itself loaded); a prompt
8112
+ * that is being admitted, or a session start in dispatch, is waited out instead of cancelling, and
8113
+ * prompts admitted after that wait for the rebuilt runtime. A reload already in flight sees the trust
8114
+ * epoch move and loads again before it installs anything.
8115
+ */
8116
+ async applyProjectTrustChange() {
8117
+ while (this._promptStartPending || this._sessionStartDispatching) {
8118
+ await new Promise((resolve) => this._admissionIdleWaiters.push(resolve));
8119
+ }
8120
+ const finishReloadWork = this._sessionWorkBarrier.begin();
8121
+ try {
8122
+ await this._rebuildRuntimeForReload();
8123
+ }
8124
+ finally {
8125
+ finishReloadWork();
8126
+ }
8127
+ }
8128
+ _notifyAdmissionIdle() {
8129
+ if (this._promptStartPending || this._sessionStartDispatching)
8130
+ return;
8131
+ const waiters = this._admissionIdleWaiters;
8132
+ this._admissionIdleWaiters = [];
8133
+ for (const resolve of waiters)
8134
+ resolve();
8135
+ }
8105
8136
  async _rebuildRuntimeForReload(options) {
8106
8137
  resetTimings("reload");
8107
8138
  const oldExtensionRunner = this._extensionRunner;
@@ -8120,6 +8151,7 @@ export class AgentSession {
8120
8151
  });
8121
8152
  time("shutdown", "reload");
8122
8153
  const previousDefaultTools = new Set(this._usesDefaultTools ? (this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES) : []);
8154
+ let trustEpoch = this.settingsManager.getTrustEpoch();
8123
8155
  await this.settingsManager.reload();
8124
8156
  this._delegatedCompactionKey = undefined;
8125
8157
  // Activate tools newly added to defaultTools. Removed ones stay active, and tools disabled
@@ -8158,6 +8190,14 @@ export class AgentSession {
8158
8190
  await this._resourceLoader.reload({
8159
8191
  settingsAlreadyReloadedFor: this.settingsManager,
8160
8192
  });
8193
+ // The project trust changed while this rebuild ran (senpi#3420): what it loaded matches the old
8194
+ // trust, so it loads again under the current one. Nothing is installed until a load matches the
8195
+ // trust at install time; the check and the install below run in one synchronous step.
8196
+ while (this.settingsManager.getTrustEpoch() !== trustEpoch) {
8197
+ trustEpoch = this.settingsManager.getTrustEpoch();
8198
+ await this.settingsManager.reload();
8199
+ await this._resourceLoader.reload({ settingsAlreadyReloadedFor: this.settingsManager });
8200
+ }
8161
8201
  time("resources", "reload");
8162
8202
  try {
8163
8203
  this._buildRuntime({
@@ -8211,6 +8251,7 @@ export class AgentSession {
8211
8251
  finally {
8212
8252
  this._sessionStartDispatching = false;
8213
8253
  settleSessionStart();
8254
+ this._notifyAdmissionIdle();
8214
8255
  }
8215
8256
  }
8216
8257
  time("lifecycle", "reload");
@@ -0,0 +1,21 @@
1
+ import type { ResourceDiagnostic } from "./diagnostics.ts";
2
+ export interface ContextFile {
3
+ path: string;
4
+ content: string;
5
+ }
6
+ /** Preserve the public array API while returning diagnostics to the owning mode. */
7
+ export type ContextFiles = ContextFile[] & {
8
+ readonly diagnostics: ResourceDiagnostic[];
9
+ };
10
+ /** Size limits for AGENTS.md / CLAUDE.md context files, which ride along on every model request. */
11
+ export interface ContextFileLimits {
12
+ maxBytesPerFile?: number;
13
+ maxTotalBytes?: number;
14
+ }
15
+ export declare const DEFAULT_CONTEXT_FILE_MAX_BYTES: number;
16
+ export declare const DEFAULT_CONTEXT_FILES_MAX_TOTAL_BYTES: number;
17
+ export declare function loadProjectContextFiles(options: {
18
+ cwd: string;
19
+ agentDir: string;
20
+ } & ContextFileLimits): ContextFiles;
21
+ //# sourceMappingURL=context-files.d.ts.map