@code-yeongyu/senpi 2026.10.10-4 → 2026.10.10-6

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 (130) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/bundle/chunks/{anthropic-messages-OE3QBX4P.js → anthropic-messages-DUULMQBF.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-N3L2LNP7.js → app-server-command-GJ5NXQSY.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-3A3C5VVO.js → chunk-3OGEJMZ7.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-J5MUMVWB.js → chunk-64ZVBCTL.js} +8 -7
  6. package/dist/bundle/chunks/{chunk-MP2DMTI7.js → chunk-C7LEZMWS.js} +124 -124
  7. package/dist/bundle/chunks/{chunk-ZSYRWQWG.js → chunk-JMI5OCIJ.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-ODYQK5XJ.js → chunk-TALS4X7S.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-7GVD54RM.js → chunk-U3IL5N76.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-H67EVDWG.js → chunk-URQSNRHZ.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-H4UIUFU5.js → chunk-VGYIPYOK.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-M2IHGL3M.js → chunk-VW74BGIC.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-4TK7VCZZ.js → chunk-WKMUAG23.js} +1 -1
  14. package/dist/bundle/chunks/chunk-YG5UO3E4.js +7 -0
  15. package/dist/bundle/chunks/chunk-YV2XQFXG.js +14 -0
  16. package/dist/bundle/chunks/{chunk-Z7MMKKIY.js → chunk-ZYHIRFGT.js} +1 -1
  17. package/dist/bundle/chunks/{cli-main-CHDR33FZ.js → cli-main-SZ54SQLA.js} +1 -1
  18. package/dist/bundle/chunks/{help-fast-path-EHRZEBRO.js → help-fast-path-W5W3FYYM.js} +1 -1
  19. package/dist/bundle/chunks/{host-command-VATE7HRG.js → host-command-YG2FIDPN.js} +1 -1
  20. package/dist/bundle/chunks/{host-lifecycle-GC3GIR2N.js → host-lifecycle-5AV4JXDQ.js} +1 -1
  21. package/dist/bundle/chunks/{interactive-mode-RVEM62WX.js → interactive-mode-SCNDQ4R6.js} +1 -1
  22. package/dist/bundle/chunks/{list-tips-IIRFXBTO.js → list-tips-BXAA4FG5.js} +1 -1
  23. package/dist/bundle/chunks/{multi-session-host-CFND7CXH.js → multi-session-host-ZDZMPNP5.js} +7 -6
  24. package/dist/bundle/chunks/{package-manager-cli-NWNECBF7.js → package-manager-cli-4LMYHHKH.js} +1 -1
  25. package/dist/bundle/chunks/{rotation-stream-C5BM7TMM.js → rotation-stream-E3XKSST7.js} +1 -1
  26. package/dist/bundle/chunks/{rpc-mode-JQFUDLNB.js → rpc-mode-ZFNFREN5.js} +1 -1
  27. package/dist/bundle/chunks/{schedule-command-EQ4PQCRP.js → schedule-command-K6CTAB4T.js} +1 -1
  28. package/dist/bundle/chunks/{session-control-endpoint-HMB5T5VD.js → session-control-endpoint-MVSYBGM3.js} +1 -1
  29. package/dist/bundle/chunks/{session-picker-O7OESJWU.js → session-picker-TNXWY5QY.js} +1 -1
  30. package/dist/bundle/chunks/session-worker.js +224 -222
  31. package/dist/bundle/cli.js +1 -1
  32. package/dist/bundle/index.js +1 -1
  33. package/dist/bundle/rpc-entry.js +1 -1
  34. package/dist/bundle/runtime-manifest.json +1 -1
  35. package/dist/core/agent-session-runtime.d.ts +6 -0
  36. package/dist/core/agent-session-runtime.js +18 -0
  37. package/dist/core/agent-session.js +5 -2
  38. package/dist/core/extensions/builtin/anthropic-subscription/auth-lane.js +3 -2
  39. package/dist/core/extensions/builtin/anthropic-subscription/options.js +11 -2
  40. package/dist/core/extensions/builtin/anthropic-subscription/session-reattach.js +4 -1
  41. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +3 -0
  42. package/dist/core/extensions/builtin/anthropic-subscription/settings.d.ts +5 -0
  43. package/dist/core/extensions/builtin/anthropic-subscription/settings.js +11 -0
  44. package/dist/core/extensions/builtin/anthropic-subscription/stream.d.ts +1 -0
  45. package/dist/core/extensions/builtin/anthropic-subscription/stream.js +17 -1
  46. package/dist/core/extensions/builtin/compaction/lane-policy.d.ts +20 -12
  47. package/dist/core/extensions/builtin/compaction/lane-policy.js +39 -34
  48. package/dist/core/extensions/builtin/html-render/bootstrap.d.ts +15 -0
  49. package/dist/core/extensions/builtin/html-render/bootstrap.js +123 -0
  50. package/dist/core/extensions/builtin/html-render/images.d.ts +16 -0
  51. package/dist/core/extensions/builtin/html-render/images.js +155 -0
  52. package/dist/core/extensions/builtin/html-render/index.d.ts +3 -0
  53. package/dist/core/extensions/builtin/html-render/index.js +5 -0
  54. package/dist/core/extensions/builtin/html-render/tool.d.ts +19 -0
  55. package/dist/core/extensions/builtin/html-render/tool.js +74 -0
  56. package/dist/core/extensions/builtin/index.js +4 -0
  57. package/dist/core/extensions/builtin/mcp/auth/catalog-identity.d.ts +4 -0
  58. package/dist/core/extensions/builtin/mcp/auth/catalog-identity.js +41 -0
  59. package/dist/core/extensions/builtin/mcp/auth/legacy-lock.d.ts +3 -0
  60. package/dist/core/extensions/builtin/mcp/auth/legacy-lock.js +39 -0
  61. package/dist/core/extensions/builtin/mcp/auth/legacy-migration.d.ts +14 -0
  62. package/dist/core/extensions/builtin/mcp/auth/legacy-migration.js +91 -0
  63. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +1 -1
  64. package/dist/core/extensions/builtin/mcp/auth/token-store.d.ts +1 -0
  65. package/dist/core/extensions/builtin/mcp/auth/token-store.js +19 -90
  66. package/dist/core/extensions/builtin/mcp/catalog-cache.d.ts +7 -3
  67. package/dist/core/extensions/builtin/mcp/catalog-cache.js +61 -12
  68. package/dist/core/extensions/builtin/mcp/catalog.d.ts +3 -1
  69. package/dist/core/extensions/builtin/mcp/catalog.js +2 -0
  70. package/dist/core/extensions/builtin/mcp/connection-types.d.ts +2 -0
  71. package/dist/core/extensions/builtin/mcp/expose/call.d.ts +12 -0
  72. package/dist/core/extensions/builtin/mcp/expose/call.js +60 -0
  73. package/dist/core/extensions/builtin/mcp/expose/proxy.js +16 -3
  74. package/dist/core/extensions/builtin/mcp/expose/register.d.ts +3 -1
  75. package/dist/core/extensions/builtin/mcp/expose/register.js +41 -50
  76. package/dist/core/extensions/builtin/mcp/expose/session.d.ts +4 -0
  77. package/dist/core/extensions/builtin/mcp/expose/session.js +5 -1
  78. package/dist/core/extensions/builtin/mcp/expose/tier-b.js +15 -4
  79. package/dist/core/extensions/builtin/mcp/index.js +5 -26
  80. package/dist/core/extensions/builtin/mcp/invocation.d.ts +42 -0
  81. package/dist/core/extensions/builtin/mcp/invocation.js +118 -0
  82. package/dist/core/extensions/builtin/mcp/service-connection.d.ts +3 -0
  83. package/dist/core/extensions/builtin/mcp/service-connection.js +6 -0
  84. package/dist/core/extensions/builtin/mcp/service-register.d.ts +4 -0
  85. package/dist/core/extensions/builtin/mcp/service-register.js +45 -1
  86. package/dist/core/extensions/builtin/mcp/service-tools-changed.js +26 -3
  87. package/dist/core/extensions/builtin/mcp/service-types.d.ts +6 -0
  88. package/dist/core/extensions/builtin/mcp/service.js +83 -49
  89. package/dist/core/extensions/builtin/mcp/shared-connection.js +17 -4
  90. package/dist/core/extensions/builtin/mcp/sharing-policy.js +1 -0
  91. package/dist/core/extensions/builtin/mcp/startup-race.js +47 -9
  92. package/dist/core/extensions/builtin/permission-system/dispatch-metadata.d.ts +8 -0
  93. package/dist/core/extensions/builtin/permission-system/dispatch-metadata.js +23 -0
  94. package/dist/core/extensions/builtin/permission-system/dispatch-policy.d.ts +14 -0
  95. package/dist/core/extensions/builtin/permission-system/dispatch-policy.js +53 -0
  96. package/dist/core/extensions/builtin/permission-system/dispatch.d.ts +33 -0
  97. package/dist/core/extensions/builtin/permission-system/dispatch.js +106 -0
  98. package/dist/core/extensions/builtin/permission-system/index.js +64 -17
  99. package/dist/core/extensions/builtin/permission-system/prompt.d.ts +1 -1
  100. package/dist/core/extensions/builtin/permission-system/prompt.js +3 -1
  101. package/dist/core/extensions/builtin/permission-system/service.d.ts +11 -1
  102. package/dist/core/extensions/builtin/permission-system/service.js +14 -4
  103. package/dist/core/extensions/builtin/ttsr/detectors/collapse-near-duplicates.d.ts +1 -0
  104. package/dist/core/extensions/builtin/ttsr/detectors/collapse-near-duplicates.js +24 -5
  105. package/dist/index.d.ts +1 -1
  106. package/dist/index.js +1 -1
  107. package/dist/modes/interactive/interactive-mode.js +21 -4
  108. package/dist/modes/rpc/host-reservations.d.ts +1 -1
  109. package/dist/modes/rpc/host-reservations.js +9 -3
  110. package/dist/modes/rpc/rpc-client.js +14 -2
  111. package/dist/modes/rpc/rpc-request-deadline.d.ts +8 -0
  112. package/dist/modes/rpc/rpc-request-deadline.js +10 -0
  113. package/dist/modes/rpc/rpc-types.d.ts +7 -4
  114. package/dist/modes/rpc/session-binding.js +15 -1
  115. package/dist/modes/rpc/session-command-router.d.ts +1 -0
  116. package/dist/modes/rpc/session-command-router.js +16 -0
  117. package/dist/modes/rpc/session-registry-attach.js +8 -2
  118. package/dist/modes/rpc/session-registry.js +5 -7
  119. package/dist/modes/rpc/session-teardown.d.ts +6 -1
  120. package/dist/modes/rpc/session-teardown.js +26 -7
  121. package/dist/modes/rpc/session-worker-client.d.ts +2 -0
  122. package/dist/modes/rpc/session-worker-client.js +6 -0
  123. package/dist/modes/rpc/session-worker-protocol.d.ts +4 -0
  124. package/dist/modes/rpc/session-worker.js +6 -0
  125. package/dist/modes/rpc/worker-session-registry.js +6 -1
  126. package/docs/providers.md +3 -2
  127. package/docs/rpc.md +26 -10
  128. package/package.json +6 -6
  129. package/dist/bundle/chunks/chunk-RADHRQ4K.js +0 -7
  130. package/dist/bundle/chunks/chunk-USRAHAW4.js +0 -14
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
3
  import{enableStartupCompileCache}from"./chunks/chunk-F73COJ7R.js";import{getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync2,realpathSync as realpathSync3}from"node:fs";import{dirname as dirname3,join as join5}from"node:path";import{fileURLToPath}from"node:url";import{createHash}from"node:crypto";import{readFileSync as readFileSync3,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname2,join as join3,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync,mkdirSync,readdirSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";import{constants}from"node:fs";import{copyFile,link}from"node:fs/promises";function errorCode(error){return error instanceof Error&&"code"in error?error.code:void 0}var FILE_OPERATIONS={copyFile,link},COPY_CONCURRENCY=8;function nextCopyMode(mode,error,platform){let code=errorCode(error);if(!(code==="ENOENT"||code==="ENOTDIR"||code==="EEXIST"))switch(mode){case"clone":return platform==="darwin"&&code==="ENOSYS"?"clone-or-copy":"link";case"link":return"copy";case"clone-or-copy":case"copy":return}}function createSnapshotFileCopier(platform=process.platform,operations=FILE_OPERATIONS){let mode="clone",attempt=(current,source,target)=>{switch(current){case"clone":return operations.copyFile(source,target,constants.COPYFILE_FICLONE_FORCE);case"clone-or-copy":return operations.copyFile(source,target,constants.COPYFILE_FICLONE);case"link":return operations.link(source,target);case"copy":return operations.copyFile(source,target,0)}};return{get mode(){return mode},async copy(source,target){for(let current=mode;;)try{await attempt(current,source,target);return}catch(error){let next=nextCopyMode(current,error,platform);if(next===void 0)throw error;current=next,mode=next}}}}async function copyFiles(pairs,copier){let next=0,worker=async()=>{for(let index=next++;index<pairs.length;index=next++){let[source,target]=pairs[index]??[];source!==void 0&&target!==void 0&&await copier.copy(source,target)}};await Promise.all(Array.from({length:Math.min(COPY_CONCURRENCY,pairs.length)},worker))}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-",UNLOADED_FILE=/\.(?:d\.[cm]?ts|map)$/;function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function planTree(source,target,files,skipModules,seen=new Set){let real=realpathSync(source);if(!seen.has(real)){seen.add(real),mkdirSync(target,{recursive:!0});for(let entry of readdirSync(real,{withFileTypes:!0})){if(skipModules&&entry.name==="node_modules")continue;let from=join(real,entry.name),to=join(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen);else if(entry.isFile())UNLOADED_FILE.test(entry.name)||files.push([from,to]);else if(entry.isSymbolicLink()){let isDirectory;try{isDirectory=statSync(from).isDirectory()}catch(error){if(isMissing(error))continue;throw error}isDirectory?planTree(from,to,files,skipModules,seen):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname(current)){if(basename(current)!=="node_modules"){let candidate=join(current,"node_modules");existsSync(candidate)&&directories.push(candidate)}if(dirname(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join(modules,packageName);if(existsSync(join(root,"package.json")))return realpathSync(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return[];let names=new Set;for(let field of["dependencies","optionalDependencies","peerDependencies"]){let block=manifest[field];if(typeof block=="object"&&block!==null)for(let name of Object.keys(block))names.add(name)}return[...names]}function closureNames(packageDir,extra){let names=new Set(extra),visited=new Set,pending=[realpathSync(packageDir)];for(let dir=pending.pop();dir!==void 0;dir=pending.pop())if(!visited.has(dir)){visited.add(dir);for(let name of dependencyNames(dir)){names.add(name);let root=packageRootFrom(dir,name);root!==void 0&&!visited.has(root)&&pending.push(root)}}return names}function planModules(packageDir,snapshotRoot,externals,files){let self=realpathSync(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join(snapshotRoot,"node_modules",name))}for(let next=pending.shift();next!==void 0;next=pending.shift())for(let name of dependencyNames(next.installDir)){let expected=packageRootFrom(next.installDir,name);expected===void 0||expected===self||resolvePlaced(next.snapshotDir,name)!==expected&&place(expected,join(next.snapshotDir,"node_modules",name))}return placed}function verifyExternals(packageDir,snapshotBundleDir,externals,placed){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected===void 0)continue;let found=moduleDirectoriesFrom(snapshotBundleDir).map(modules=>join(modules,name)).find(root=>existsSync(join(root,"package.json")));if(found===void 0||placed.get(found)!==expected)throw new RuntimeSnapshotLayoutError(name)}}async function materializeRuntimeSnapshot(packageDir,target,manifest,copier=createSnapshotFileCopier()){let staging=join(dirname(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planTree(packageDir,staging,files,!0);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync(packageDir)};writeFileSync(join(staging,RUNTIME_SNAPSHOT_MARKER),`${JSON.stringify(marker)}
4
- `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-EHRZEBRO.js");tryPrintHelpWithoutEngine(args)&&process.exit()}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-CHDR33FZ.js")}
4
+ `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-W5W3FYYM.js");tryPrintHelpWithoutEngine(args)&&process.exit()}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-SZ54SQLA.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,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-MP2DMTI7.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-USRAHAW4.js";import"./chunks/chunk-QNAG7FYM.js";import{CURRENT_SESSION_VERSION,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionManager,SessionSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,keyHint,keyText,migrateSessionEntries,parseSessionEntries,rawKeyHint,sessionEntryToContextMessages}from"./chunks/chunk-Z7MMKKIY.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-H4UIUFU5.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-M2IHGL3M.js";import{sanitizeTerminalLabel}from"./chunks/chunk-J5MUMVWB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-ZSYRWQWG.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-7GVD54RM.js";import"./chunks/chunk-IZOTKUWG.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-H67EVDWG.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-4TK7VCZZ.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3A3C5VVO.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-RADHRQ4K.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-RRU5LXMS.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ODYQK5XJ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionControlSenderOf,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-C7LEZMWS.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-YV2XQFXG.js";import"./chunks/chunk-QNAG7FYM.js";import{CURRENT_SESSION_VERSION,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionManager,SessionSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,keyHint,keyText,migrateSessionEntries,parseSessionEntries,rawKeyHint,sessionEntryToContextMessages}from"./chunks/chunk-ZYHIRFGT.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-VGYIPYOK.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-VW74BGIC.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-64ZVBCTL.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-JMI5OCIJ.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-U3IL5N76.js";import"./chunks/chunk-IZOTKUWG.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-URQSNRHZ.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-WKMUAG23.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3OGEJMZ7.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-YG5UO3E4.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-RRU5LXMS.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-TALS4X7S.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,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-MP2DMTI7.js";import"./chunks/chunk-USRAHAW4.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-Z7MMKKIY.js";import{configureHttpDispatcher}from"./chunks/chunk-H4UIUFU5.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-M2IHGL3M.js";import"./chunks/chunk-J5MUMVWB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-ZSYRWQWG.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-7GVD54RM.js";import"./chunks/chunk-IZOTKUWG.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-H67EVDWG.js";import"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-4TK7VCZZ.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3A3C5VVO.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-RADHRQ4K.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import"./chunks/chunk-RRU5LXMS.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ODYQK5XJ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{main}from"./chunks/chunk-C7LEZMWS.js";import"./chunks/chunk-YV2XQFXG.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-ZYHIRFGT.js";import{configureHttpDispatcher}from"./chunks/chunk-VGYIPYOK.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-VW74BGIC.js";import"./chunks/chunk-64ZVBCTL.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-JMI5OCIJ.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-U3IL5N76.js";import"./chunks/chunk-IZOTKUWG.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-URQSNRHZ.js";import"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-WKMUAG23.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3OGEJMZ7.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-YG5UO3E4.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import"./chunks/chunk-RRU5LXMS.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-TALS4X7S.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -1 +1 @@
1
- {"buildId":"5434f555c22c740f","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"279f706c351fa1c9","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
@@ -112,6 +112,12 @@ export declare class AgentSessionRuntime {
112
112
  setPromptSurface(surface: PromptSurface): void;
113
113
  /** Moves this session to another browser engine; later replacements (switch, new, fork) keep it. */
114
114
  setBrowserEngine(engine: BrowserEngine): void;
115
+ /**
116
+ * Moves this session to another permission preset (a later `open_session.permissionPreset`): the
117
+ * permission extension enforces it from the next tool call, and later replacements (switch, new,
118
+ * fork) keep it.
119
+ */
120
+ setPermissionPreset(preset: string): void;
115
121
  /**
116
122
  * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements
117
123
  * (switch, new, fork) keep it. Callers set it before the first turn: a chain never changes under a
@@ -85,6 +85,15 @@ export class AgentSessionRuntime {
85
85
  this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), browserEngine: engine });
86
86
  this._session.setBrowserEngine(engine);
87
87
  }
88
+ /**
89
+ * Moves this session to another permission preset (a later `open_session.permissionPreset`): the
90
+ * permission extension enforces it from the next tool call, and later replacements (switch, new,
91
+ * fork) keep it.
92
+ */
93
+ setPermissionPreset(preset) {
94
+ this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), permissionPreset: preset });
95
+ this._session.extensionRunner.setFlagValue("permission-preset", preset);
96
+ }
88
97
  /**
89
98
  * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements
90
99
  * (switch, new, fork) keep it. Callers set it before the first turn: a chain never changes under a
@@ -193,6 +202,15 @@ export class AgentSessionRuntime {
193
202
  async apply(result, hold) {
194
203
  this._sessionHold = hold ?? holdActiveSession(result.session.sessionManager, false);
195
204
  this._session = result.session;
205
+ // The replacement was built from the profile read before its runtime was created; an attach
206
+ // that moved a setting while it was being built reached only the retired session (senpi#2842).
207
+ const profile = this._launchProfile;
208
+ if (profile?.permissionPreset !== undefined)
209
+ this._session.extensionRunner.setFlagValue("permission-preset", profile.permissionPreset);
210
+ if (profile?.promptSurface !== undefined)
211
+ this._session.setPromptSurface(profile.promptSurface);
212
+ if (profile?.browserEngine !== undefined)
213
+ this._session.setBrowserEngine(profile.browserEngine);
196
214
  this._services = result.services;
197
215
  this._diagnostics = result.diagnostics;
198
216
  this._modelFallbackMessage = result.modelFallbackMessage;
@@ -7593,7 +7593,6 @@ export class AgentSession {
7593
7593
  resetTimings("reload");
7594
7594
  const oldExtensionRunner = this._extensionRunner;
7595
7595
  const oldExtensionIdentities = oldExtensionRunner.getExtensionIdentities();
7596
- const previousFlagValues = oldExtensionRunner.getFlagValues();
7597
7596
  const previousActiveToolRegistrationIds = new Map();
7598
7597
  // Cover withheld eval-only tools too: the rebuild drops any seeded name missing from this
7599
7598
  // map, which would strand eval-only tools when the policy disarms during this reload.
@@ -7650,7 +7649,11 @@ export class AgentSession {
7650
7649
  try {
7651
7650
  this._buildRuntime({
7652
7651
  activeToolNames: requestedActiveToolNamesBeforeRebuild,
7653
- flagValues: previousFlagValues,
7652
+ // Read from the CURRENT runner at the swap, not before the awaits above and not from the
7653
+ // runner this reload started with: a flag set while this reload ran (an attach moving the
7654
+ // session's permission preset) carries over, also when an overlapping reload installed
7655
+ // another runner in the meantime and the attach wrote that one (senpi#2842).
7656
+ flagValues: this._extensionRunner.getFlagValues(),
7654
7657
  includeAllExtensionTools: true,
7655
7658
  previousActiveToolRegistrationIds,
7656
7659
  addedToolNames: addedDefaultTools,
@@ -148,7 +148,8 @@ export async function* queryWithAuthLane(input) {
148
148
  if (name.startsWith("SENPI_"))
149
149
  delete ambientEnvironment[name];
150
150
  }
151
- options.env = ambientEnvironment;
151
+ // Lane-owned variables from buildOptions (the compaction-owner overlay) win over the host.
152
+ options.env = { ...ambientEnvironment, ...options.env };
152
153
  yield* await createAttemptMessages(input, {
153
154
  accountName: "ambient",
154
155
  accounts: [],
@@ -169,7 +170,7 @@ export async function* queryWithAuthLane(input) {
169
170
  const options = input.buildOptions(pool.lane);
170
171
  const accounts = pool.accounts.map((account) => ({ ...account }));
171
172
  const prepared = await prepareSlot(pool, slot, signal);
172
- options.env = prepared.env;
173
+ options.env = { ...prepared.env, ...options.env };
173
174
  return createAttemptMessages(input, {
174
175
  accountName: slot.name,
175
176
  accounts,
@@ -3,7 +3,7 @@ import { dirname, join, relative, resolve } from "node:path";
3
3
  import { CONFIG_DIR_NAME, getAgentDir } from "../../../../config.js";
4
4
  import { PROJECT_RULES_END_MARKER, PROJECT_RULES_HEADING, PROJECT_RULES_REGION_END_MARKER, PROJECT_RULES_REGION_START_MARKER, PROJECT_RULES_START_MARKER, } from "../rules/rules/constants.js";
5
5
  import { presetAppendDeprecationGuidance } from "./guidance.js";
6
- import { loadAnthropicSubscriptionProviderSettingsFromDisk, resolveSystemPromptMode, } from "./settings.js";
6
+ import { loadAnthropicSubscriptionProviderSettingsFromDisk, resolveCompactionOwner, resolveSystemPromptMode, } from "./settings.js";
7
7
  import { loadOverrideSystemPrompt, resolveCustomSystemPrompt } from "./system-prompt.js";
8
8
  import { BUILTIN_SDK_TOOLS, canUseTool, HOST_TOOL_DENIAL_HOOKS } from "./tools.js";
9
9
  const ADAPTIVE_THINKING_MODEL_MARKERS = [
@@ -207,6 +207,7 @@ export function buildAnthropicSubscriptionQueryOptions(input) {
207
207
  const toolLessRequest = input.streamOptions?.toolChoice === "none";
208
208
  const emptyToolContext = (input.context.tools?.length ?? 0) === 0;
209
209
  const strictMcpConfig = toolLessRequest || (providerSettings.strictMcpConfig ?? !appendSystemPrompt);
210
+ const senpiOwnsCompaction = resolveCompactionOwner(providerSettings) === "senpi";
210
211
  const queryOptions = {
211
212
  cwd,
212
213
  model: input.model.id,
@@ -216,9 +217,17 @@ export function buildAnthropicSubscriptionQueryOptions(input) {
216
217
  canUseTool,
217
218
  hooks: HOST_TOOL_DENIAL_HOOKS,
218
219
  systemPrompt,
219
- settings: { autoCompactEnabled: true },
220
+ // Exactly one compaction owner: senpi by default, so Claude Code's native auto-compact is off
221
+ // (senpi's overflow recovery covers the hard limit); `compactionOwner: "sdk"` hands it back.
222
+ // configFingerprint hashes `settings`, so an owner change restarts the resident process.
223
+ settings: { autoCompactEnabled: !senpiOwnsCompaction },
220
224
  settingSources: resolveSettingSources(providerSettings, mode, authLane),
221
225
  };
226
+ // Claude Code's per-turn token-budget reminder changes the prompt every turn and defeats
227
+ // prompt-cache reuse; senpi's compaction carries its own budget reminder. The auth lane
228
+ // layers this over the subprocess environment it builds.
229
+ if (senpiOwnsCompaction)
230
+ queryOptions.env = { CLAUDE_CODE_TOTAL_TOKENS_REMINDER: "off" };
222
231
  if (input.pathToClaudeCodeExecutable)
223
232
  queryOptions.pathToClaudeCodeExecutable = input.pathToClaudeCodeExecutable;
224
233
  if (toolLessRequest)
@@ -72,8 +72,11 @@ export async function verifyRestoredTranscript(binding, cwd, authLane) {
72
72
  if (messages.length === 0 || messages.some((message) => message.session_id !== binding.sdkSessionId)) {
73
73
  return false;
74
74
  }
75
+ // A restored binding with no recorded assistant turn has nothing the transcript can prove: the
76
+ // store keeps only the newest boundary (`bindingFromStored` maps none when it is null), so the
77
+ // binding is never resumed unchecked. It is rejected, and the session is rebuilt (senpi#2858).
75
78
  if (binding.lastAssistantUuid === null)
76
- return true;
79
+ return false;
77
80
  const anchorIndex = messages.findIndex((message) => message.type === "assistant" &&
78
81
  message.uuid === binding.lastAssistantUuid &&
79
82
  message.parent_tool_use_id === null);
@@ -106,6 +106,9 @@ export function configFingerprint(options, context, authLane, accountName) {
106
106
  authLane,
107
107
  accountName,
108
108
  permissionMode: options.permissionMode,
109
+ // The compaction owner (`autoCompactEnabled`) is fixed at spawn: a changed owner must
110
+ // restart the resident process, or the old owner keeps compacting next to the new one.
111
+ settings: options.settings,
109
112
  // Bump HOST_TOOL_POLICY_FINGERPRINT in tools.ts when denial copy or hooks change.
110
113
  hostToolPolicy: HOST_TOOL_POLICY_FINGERPRINT,
111
114
  settingSources: options.settingSources,
@@ -3,6 +3,10 @@ import type { SettingSource } from "./sdk-boundary.ts";
3
3
  export type AnthropicSubscriptionSystemPromptMode = "preset-append" | "full" | "override";
4
4
  export type AnthropicSubscriptionResumeMode = "auto" | "off";
5
5
  export type AnthropicSubscriptionTokenInjection = "oauth-slots" | "config-dir" | "ambient";
6
+ /** Who compacts a resident lane: senpi's compaction stack (default) or the Claude Agent SDK's native auto-compact. */
7
+ export type AnthropicSubscriptionCompactionOwner = "senpi" | "sdk";
8
+ /** The one place the default lives: senpi owns compaction unless `compactionOwner: "sdk"` opts out. */
9
+ export declare function resolveCompactionOwner(settings: Pick<AnthropicSubscriptionProviderSettings, "compactionOwner">): AnthropicSubscriptionCompactionOwner;
6
10
  export interface AnthropicSubscriptionProviderSettings {
7
11
  /**
8
12
  * Explicit opt-in for the ambient (host Claude CLI) auth lane. Absent means
@@ -20,6 +24,7 @@ export interface AnthropicSubscriptionProviderSettings {
20
24
  readonly strictMcpConfig?: boolean;
21
25
  readonly pinnedAccount?: string;
22
26
  readonly tokenInjection?: AnthropicSubscriptionTokenInjection;
27
+ readonly compactionOwner?: AnthropicSubscriptionCompactionOwner;
23
28
  }
24
29
  export type ResolvedSystemPromptMode = {
25
30
  mode: AnthropicSubscriptionSystemPromptMode;
@@ -1,6 +1,10 @@
1
1
  import { getAgentDir } from "../../../../config.js";
2
2
  import { getFileContentRevision } from "../../../../utils/paths.js";
3
3
  import { getSettingsPath, SettingsManager } from "../../../settings-manager.js";
4
+ /** The one place the default lives: senpi owns compaction unless `compactionOwner: "sdk"` opts out. */
5
+ export function resolveCompactionOwner(settings) {
6
+ return settings.compactionOwner ?? "senpi";
7
+ }
4
8
  const systemPromptModeSources = new WeakMap();
5
9
  function isRecord(value) {
6
10
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -29,6 +33,9 @@ function parseResumeMode(value) {
29
33
  function parseTokenInjection(value) {
30
34
  return value === "oauth-slots" || value === "config-dir" || value === "ambient" ? value : undefined;
31
35
  }
36
+ function parseCompactionOwner(value) {
37
+ return value === "senpi" || value === "sdk" ? value : undefined;
38
+ }
32
39
  function parseEnvironmentBoolean(value) {
33
40
  if (value === undefined)
34
41
  return undefined;
@@ -58,6 +65,7 @@ function parseProviderSettings(value) {
58
65
  const strictMcpConfig = typeof value.strictMcpConfig === "boolean" ? value.strictMcpConfig : undefined;
59
66
  const pinnedAccount = parseNonEmptyString(value.pinnedAccount);
60
67
  const tokenInjection = parseTokenInjection(value.tokenInjection);
68
+ const compactionOwner = parseCompactionOwner(value.compactionOwner);
61
69
  return {
62
70
  ...(enabled !== undefined ? { enabled } : {}),
63
71
  ...(appendSystemPrompt !== undefined ? { appendSystemPrompt } : {}),
@@ -68,6 +76,7 @@ function parseProviderSettings(value) {
68
76
  ...(strictMcpConfig !== undefined ? { strictMcpConfig } : {}),
69
77
  ...(pinnedAccount !== undefined ? { pinnedAccount } : {}),
70
78
  ...(tokenInjection !== undefined ? { tokenInjection } : {}),
79
+ ...(compactionOwner !== undefined ? { compactionOwner } : {}),
71
80
  };
72
81
  }
73
82
  function parseEnvironmentSettings(environment) {
@@ -78,6 +87,7 @@ function parseEnvironmentSettings(environment) {
78
87
  const tokenInjection = parseTokenInjection(environment.SENPI_CLAUDE_SDK_OAUTH_TOKEN_INJECTION);
79
88
  const settingSources = parseEnvironmentSettingSources(environment.SENPI_CLAUDE_SDK_OAUTH_SETTING_SOURCES);
80
89
  const pinnedAccount = parseNonEmptyString(environment.SENPI_CLAUDE_SDK_OAUTH_PINNED_ACCOUNT);
90
+ const compactionOwner = parseCompactionOwner(environment.SENPI_CLAUDE_SDK_OAUTH_COMPACTION_OWNER);
81
91
  return {
82
92
  ...(enabled !== undefined ? { enabled } : {}),
83
93
  ...(systemPromptMode !== undefined ? { systemPromptMode } : {}),
@@ -86,6 +96,7 @@ function parseEnvironmentSettings(environment) {
86
96
  ...(tokenInjection !== undefined ? { tokenInjection } : {}),
87
97
  ...(settingSources !== undefined ? { settingSources } : {}),
88
98
  ...(pinnedAccount !== undefined ? { pinnedAccount } : {}),
99
+ ...(compactionOwner !== undefined ? { compactionOwner } : {}),
89
100
  };
90
101
  }
91
102
  export function resolveSystemPromptMode(settings) {
@@ -1,3 +1,4 @@
1
1
  import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from "@earendil-works/pi-ai";
2
+ export declare const NATIVE_COMPACTION_WHILE_SENPI_OWNS = "Claude Code compacted this session natively although senpi owns compaction on this lane (compactionOwner: \"senpi\"); the turn was stopped so only one side compacts. Run /compact, or set anthropicSubscriptionProvider.compactionOwner to \"sdk\" to let Claude Code compact.";
2
3
  export declare function streamAnthropicSubscription(model: Model<Api>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream;
3
4
  //# sourceMappingURL=stream.d.ts.map
@@ -11,13 +11,15 @@ import { dedupeUltraworkBlocks } from "./prompt-directive-dedupe.js";
11
11
  import { refusalError } from "./refusal.js";
12
12
  import { getSdkBoundary, loadClaudeAgentSdk } from "./sdk-boundary.js";
13
13
  import { emitContinuityObservation } from "./session-observability.js";
14
+ import { forgetBinding } from "./session-reattach.js";
14
15
  import { residentSessionMessages } from "./session-stream.js";
15
- import { loadAnthropicSubscriptionProviderSettingsFromDisk } from "./settings.js";
16
+ import { loadAnthropicSubscriptionProviderSettingsFromDisk, resolveCompactionOwner } from "./settings.js";
16
17
  import { applyStreamEvent } from "./stream-events.js";
17
18
  import { withAuthGuidance } from "./stream-guidance.js";
18
19
  import { emptyOutput, errorMessage, mapStopReason, updateUsage } from "./stream-protocol.js";
19
20
  import { toolWatch } from "./tool-watch.js";
20
21
  import { resolveSdkTools } from "./tools.js";
22
+ export const NATIVE_COMPACTION_WHILE_SENPI_OWNS = 'Claude Code compacted this session natively although senpi owns compaction on this lane (compactionOwner: "senpi"); the turn was stopped so only one side compacts. Run /compact, or set anthropicSubscriptionProvider.compactionOwner to "sdk" to let Claude Code compact.';
21
23
  export function streamAnthropicSubscription(model, context, options) {
22
24
  const stream = createAssistantMessageEventStream();
23
25
  void (async () => {
@@ -53,6 +55,7 @@ export function streamAnthropicSubscription(model, context, options) {
53
55
  let claudeCodeRun;
54
56
  let coldSeedAttempt = false;
55
57
  let coldSeedEstimate;
58
+ let nativeCompactionStopped = false;
56
59
  try {
57
60
  // Resident before the synchronous SDK member below (getSdkBoundary().query)
58
61
  // reads it - see sdk-boundary.lazy.ts.
@@ -64,6 +67,7 @@ export function streamAnthropicSubscription(model, context, options) {
64
67
  toolWatch.reconcileWithContext(sessionKey, context);
65
68
  const toolWatchNote = toolWatch.buildPromptNote(sessionKey, context, resolvedTools.customToolNameToSdk);
66
69
  const providerSettings = loadAnthropicSubscriptionProviderSettingsFromDisk(process.cwd());
70
+ const senpiOwnsCompaction = resolveCompactionOwner(providerSettings) === "senpi";
67
71
  const toolLessRequest = options?.toolChoice === "none";
68
72
  const mcpServers = toolLessRequest ? undefined : await buildCustomToolServers(resolvedTools.customTools);
69
73
  claudeCodeRun = resolveClaudeCodeRun(defaultExecutableDeps());
@@ -169,6 +173,13 @@ export function streamAnthropicSubscription(model, context, options) {
169
173
  applyStreamEvent({ model, output, blocks, stream, customToolNameToPi: resolvedTools.customToolNameToPi }, message.event);
170
174
  }
171
175
  else if (message.type === "system" && message.subtype === "compact_boundary") {
176
+ // The query was started with native auto-compact off: a boundary here means Claude
177
+ // Code compacted anyway. Fail the turn loudly instead of letting a second owner
178
+ // rewrite the transcript behind senpi's compaction.
179
+ if (senpiOwnsCompaction) {
180
+ nativeCompactionStopped = true;
181
+ throw new Error(NATIVE_COMPACTION_WHILE_SENPI_OWNS);
182
+ }
172
183
  // Native compactions must reach the ledger: attach the boundary as a
173
184
  // diagnostic so the lane-policy collector can build a ledger entry
174
185
  // instead of the boundary being discarded in the stream.
@@ -219,6 +230,11 @@ export function streamAnthropicSubscription(model, context, options) {
219
230
  catch (error) {
220
231
  // no-excuse-ok: catch
221
232
  // Provider boundary converts every thrown SDK value into the stream error contract.
233
+ // Unwinding the stopped attempt kept a retry checkpoint on the Claude Code session that
234
+ // just compacted natively. Drop it, so the next turn rebuilds the resident session from
235
+ // senpi's own history instead of resuming that rewritten transcript.
236
+ if (nativeCompactionStopped && options?.sessionId)
237
+ forgetBinding(options.sessionId);
222
238
  output.stopReason = options?.signal?.aborted ? "aborted" : "error";
223
239
  // A failed result still bills its tokens; managed and resident lanes
224
240
  // throw before the result reaches this loop, so account for it here.
@@ -1,15 +1,21 @@
1
1
  /**
2
- * Provider-scoped compaction opt-out for the `anthropic-subscription` main lane.
2
+ * Provider-scoped compaction ownership for the `anthropic-subscription` main lane.
3
3
  *
4
- * That lane keeps one resident SDK session per senpi session, and the Claude
5
- * Agent SDK runs its own native auto-compaction over that session's transcript.
6
- * Running senpi's compaction on top of it would rewrite a history senpi no
7
- * longer owns, so senpi stands down for the lane: no auto-compaction triggers,
8
- * no context reduction. Every other provider is untouched.
4
+ * That lane keeps one resident SDK session per senpi session. By default senpi
5
+ * owns its compaction (speculative, idle, restoration, degradation recovery): an
6
+ * accepted compaction invalidates the resident binding and the next turn
7
+ * cold-seeds the compacted branch (`tainted_compaction` always flattens), while
8
+ * the SDK's native auto-compact is pinned off so exactly one side compacts.
9
9
  *
10
- * The stand-down is conditional on the lane actually being resident: with the
11
- * `resumeMode: "off"` escape hatch senpi flattens its own history into every
12
- * request, so senpi's compaction must stay fully active there.
10
+ * `compactionOwner: "sdk"` opts out: the Claude Agent SDK runs its own native
11
+ * auto-compaction over the resident transcript and senpi stands down for the
12
+ * lane (no auto-compaction triggers, no context reduction). The stand-down lifts
13
+ * with the `resumeMode: "off"` escape hatch, where senpi flattens its own
14
+ * history into every request. Every other provider is untouched.
15
+ *
16
+ * The owner is read per call, from the same settings snapshot the query options
17
+ * use for the next turn, so a mid-session change can never leave the two sides
18
+ * disagreeing about who compacts.
13
19
  *
14
20
  * This module also owns the shape of the mirrored `compact_boundary` ledger
15
21
  * entry, so the SDK's native compactions stay visible in senpi history.
@@ -36,6 +42,8 @@ export interface SdkNativeLaneInput {
36
42
  model: LaneModel | undefined;
37
43
  /** Resolved `claudeSdkOauthProvider.resumeMode`; `undefined` means the "auto" default. */
38
44
  resumeMode?: string;
45
+ /** Resolved `anthropicSubscriptionProvider.compactionOwner`; `undefined` means the "senpi" default. */
46
+ compactionOwner?: string;
39
47
  }
40
48
  export interface LaneContext {
41
49
  cwd: string;
@@ -79,9 +87,9 @@ export interface CompactBoundaryEntry {
79
87
  */
80
88
  export declare function isSdkNativeCompactionLane(input: SdkNativeLaneInput): boolean;
81
89
  /**
82
- * Per-extension-instance policy holding one memoized provider-settings read.
83
- * Settings are only read when the active model actually belongs to the lane, so
84
- * other providers never pay for the lookup.
90
+ * Per-extension-instance lane policy. Settings are only read when the active
91
+ * model actually belongs to the lane, so other providers never pay for the
92
+ * lookup; the loader itself is cached by settings-file revision.
85
93
  */
86
94
  export declare function createCompactionLanePolicy(options?: {
87
95
  loadProviderSettings?: (cwd: string) => AnthropicSubscriptionProviderSettings;