@code-yeongyu/senpi 2026.9.29-5 → 2026.9.30

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 (140) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/bundle/chunks/{anthropic-messages-HEVKB3PL.js → anthropic-messages-ADSIWAJ5.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-32AFWZEH.js → app-server-command-B3ZYM2WN.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-2WAKOPNA.js → chunk-4P4DUW66.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-7RVWDN5Z.js → chunk-6GV3L3GZ.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-OUG6SDT7.js → chunk-6JZQLUAJ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-MJQWYN2W.js → chunk-7MKMDWHC.js} +2 -2
  8. package/dist/bundle/chunks/{chunk-XBGO2JZD.js → chunk-A7AQSA6R.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-BJICJY47.js → chunk-DVVROXLZ.js} +1 -1
  10. package/dist/bundle/chunks/chunk-EIG6K5U3.js +6 -0
  11. package/dist/bundle/chunks/chunk-FAWC2EIR.js +2 -0
  12. package/dist/bundle/chunks/{chunk-WCAKUCN3.js → chunk-FNCILR4E.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-XHEMQA2T.js → chunk-HPESFBMB.js} +2 -2
  14. package/dist/bundle/chunks/{chunk-BBNWT72C.js → chunk-HVBFDRP4.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-63QHOG5A.js → chunk-I77ENHCQ.js} +81 -74
  16. package/dist/bundle/chunks/{chunk-UMLU3I2G.js → chunk-ITXF6FAM.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-77AUUH3Z.js → chunk-IXONH7ML.js} +2 -2
  18. package/dist/bundle/chunks/{chunk-K2SHQNAA.js → chunk-JX2CSKLG.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-4VWWEMCJ.js → chunk-JXZ5LDJP.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-VLTMFAWQ.js → chunk-KWI3KUF2.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-7CQX3QFV.js → chunk-L4QGZJKQ.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-AGVPQLIU.js → chunk-MDXUQDGF.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-2N3BZ5DV.js → chunk-OOA6OL42.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-2POUJCWM.js → chunk-OVGH7VP3.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-ZDNR3YVJ.js → chunk-RMVQ5YRX.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-SH6VUPE4.js → chunk-T5MOQDGL.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-CNYWF72S.js → chunk-VKECIIYV.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-U7BNOE23.js → chunk-VNYUGCC7.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-ZPMJIPQC.js → chunk-YSNNL5HU.js} +1 -1
  30. package/dist/bundle/chunks/cli-main-F6WNYPUT.js +3 -0
  31. package/dist/bundle/chunks/{help-fast-path-ZUNFOE53.js → help-fast-path-34Z6I2PH.js} +1 -1
  32. package/dist/bundle/chunks/{host-command-V2LDNNXB.js → host-command-PUOIPEBI.js} +1 -1
  33. package/dist/bundle/chunks/{host-lifecycle-PFLJRXEN.js → host-lifecycle-4VJUHV5U.js} +1 -1
  34. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  35. package/dist/bundle/chunks/{interactive-mode-J6KGDRR7.js → interactive-mode-KM454JPC.js} +1 -1
  36. package/dist/bundle/chunks/{list-tips-ASETMEFS.js → list-tips-GWRRD5UC.js} +1 -1
  37. package/dist/bundle/chunks/{multi-session-host-IBVJ3WN7.js → multi-session-host-ZFT6RM2S.js} +2 -2
  38. package/dist/bundle/chunks/{native-loader-WM7NDPEO.js → native-loader-HW7GQYPY.js} +1 -1
  39. package/dist/bundle/chunks/{openai-completions-SA2UJW7Q.js → openai-completions-32RTG3Q4.js} +1 -1
  40. package/dist/bundle/chunks/{package-manager-cli-JJ5R7UWV.js → package-manager-cli-LNQOWI3A.js} +1 -1
  41. package/dist/bundle/chunks/{rg-engine-G2YTYL2T.js → rg-engine-LWZA7TRH.js} +1 -1
  42. package/dist/bundle/chunks/{rotation-stream-EX7PWQ4S.js → rotation-stream-DIKK7U57.js} +1 -1
  43. package/dist/bundle/chunks/{rpc-mode-ITND2BVC.js → rpc-mode-H7QGQI4P.js} +1 -1
  44. package/dist/bundle/chunks/{schedule-command-D6JNRP3D.js → schedule-command-BUFJOM5L.js} +1 -1
  45. package/dist/bundle/chunks/session-control-endpoint-QIIA6MFR.js +3 -0
  46. package/dist/bundle/chunks/{session-picker-K5FIKV6C.js → session-picker-P53MTWTS.js} +1 -1
  47. package/dist/bundle/chunks/session-worker.js +110 -103
  48. package/dist/bundle/chunks/{state-store-IIQL55GC.js → state-store-QGLITAI4.js} +1 -1
  49. package/dist/bundle/cli.js +2 -2
  50. package/dist/bundle/index.js +1 -1
  51. package/dist/bundle/rpc-entry.js +1 -1
  52. package/dist/bundle/runtime-manifest.json +1 -1
  53. package/dist/cli.js +1 -1
  54. package/dist/core/dynamic-prompt/build.d.ts +4 -3
  55. package/dist/core/dynamic-prompt/build.js +4 -2
  56. package/dist/core/dynamic-prompt/handoff.d.ts +9 -1
  57. package/dist/core/dynamic-prompt/handoff.js +11 -1
  58. package/dist/core/dynamic-prompt/intent-gate.js +1 -1
  59. package/dist/core/dynamic-prompt/style.js +4 -2
  60. package/dist/core/dynamic-prompt/types.d.ts +7 -1
  61. package/dist/core/dynamic-prompt/types.js +3 -1
  62. package/dist/core/dynamic-prompt/verification.d.ts +1 -1
  63. package/dist/core/dynamic-prompt/verification.js +2 -1
  64. package/dist/core/extensions/builtin/anthropic-subscription/stream-protocol.d.ts +1 -1
  65. package/dist/core/extensions/builtin/anthropic-subscription/tools.d.ts +9 -2
  66. package/dist/core/extensions/builtin/anthropic-subscription/tools.js +9 -4
  67. package/dist/core/extensions/builtin/ask-user/resume.js +20 -9
  68. package/dist/core/extensions/builtin/ask-user/tool.d.ts +9 -0
  69. package/dist/core/extensions/builtin/ask-user/tool.js +1 -1
  70. package/dist/core/extensions/builtin/cache-keepalive/index.js +17 -4
  71. package/dist/core/extensions/builtin/chat-reply-scrub/index.d.ts +16 -0
  72. package/dist/core/extensions/builtin/chat-reply-scrub/index.js +39 -0
  73. package/dist/core/extensions/builtin/chat-reply-scrub/scaffold-strip.d.ts +7 -0
  74. package/dist/core/extensions/builtin/chat-reply-scrub/scaffold-strip.js +125 -0
  75. package/dist/core/extensions/builtin/index.js +3 -0
  76. package/dist/core/extensions/builtin/permission-system/cli.js +1 -0
  77. package/dist/core/extensions/builtin/permission-system/config.d.ts +1 -0
  78. package/dist/core/extensions/builtin/permission-system/config.js +10 -0
  79. package/dist/core/extensions/builtin/permission-system/index.js +2 -2
  80. package/dist/core/extensions/builtin/permission-system/settings.js +1 -1
  81. package/dist/core/extensions/builtin/permission-system/types.d.ts +1 -1
  82. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +5 -5
  83. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +6 -6
  84. package/dist/core/extensions/builtin/prompt-preset/claude-opus-5-5.js +4 -4
  85. package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +4 -4
  86. package/dist/core/extensions/builtin/prompt-preset/claude-sonnet-5-5.js +4 -4
  87. package/dist/core/extensions/builtin/prompt-preset/gpt-5.5.js +9 -6
  88. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +10 -7
  89. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +15 -6
  90. package/dist/core/extensions/builtin/prompt-preset/gpt-surface.d.ts +2 -2
  91. package/dist/core/extensions/builtin/prompt-preset/grok-4.5.js +4 -4
  92. package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +4 -4
  93. package/dist/core/extensions/builtin/prompt-preset/grok-4.7.js +3 -3
  94. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-6.js +1 -1
  95. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js +1 -1
  96. package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +6 -6
  97. package/dist/core/extensions/builtin/recommended-models/index.d.ts +1 -1
  98. package/dist/core/extensions/builtin/recommended-models/index.js +1 -1
  99. package/dist/core/extensions/builtin/todotools/first-turn.d.ts +6 -4
  100. package/dist/core/extensions/builtin/todotools/first-turn.js +17 -5
  101. package/dist/core/extensions/builtin/todotools/todo-ask.d.ts +1 -0
  102. package/dist/core/extensions/builtin/todotools/todo-ask.js +1 -1
  103. package/dist/core/extensions/builtin/todotools/tools/todo.js +4 -1
  104. package/dist/core/resource-loader.js +7 -3
  105. package/dist/modes/interactive/components/ask-user-async-widget.d.ts +2 -0
  106. package/dist/modes/interactive/components/ask-user-async-widget.js +10 -0
  107. package/dist/modes/interactive/components/ask-user-question-state.js +3 -1
  108. package/dist/modes/interactive/interactive-mode.js +7 -1
  109. package/dist/modes/interactive/session-control-commands.d.ts +2 -1
  110. package/dist/modes/interactive/session-control-commands.js +15 -6
  111. package/dist/modes/rpc/connection-question-bridge.js +5 -5
  112. package/dist/modes/rpc/custom-capability.d.ts +6 -0
  113. package/dist/modes/rpc/custom-capability.js +6 -0
  114. package/dist/modes/rpc/extension-ui-response.d.ts +11 -0
  115. package/dist/modes/rpc/extension-ui-response.js +18 -0
  116. package/dist/modes/rpc/host-lifecycle.d.ts +5 -2
  117. package/dist/modes/rpc/host-lifecycle.js +14 -8
  118. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  119. package/dist/modes/rpc/rpc-input-validation.d.ts +1 -1
  120. package/dist/modes/rpc/rpc-input-validation.js +3 -3
  121. package/dist/modes/rpc/rpc-mode.d.ts +3 -2
  122. package/dist/modes/rpc/rpc-mode.js +3 -2
  123. package/dist/modes/rpc/rpc-types.d.ts +4 -3
  124. package/dist/modes/rpc/session-command-router.js +4 -1
  125. package/dist/runtime-snapshot/enter.d.ts +1 -1
  126. package/dist/runtime-snapshot/enter.js +17 -7
  127. package/dist/runtime-snapshot/file-copier.d.ts +24 -0
  128. package/dist/runtime-snapshot/file-copier.js +76 -0
  129. package/dist/runtime-snapshot/layout.d.ts +8 -4
  130. package/dist/runtime-snapshot/layout.js +137 -70
  131. package/dist/runtime-snapshot/registry.d.ts +7 -0
  132. package/dist/runtime-snapshot/registry.js +63 -1
  133. package/dist/senpi +1 -1
  134. package/docs/providers.md +1 -1
  135. package/docs/rpc.md +34 -11
  136. package/package.json +6 -6
  137. package/dist/bundle/chunks/chunk-AWEAVBCR.js +0 -2
  138. package/dist/bundle/chunks/chunk-YLQTKWEC.js +0 -6
  139. package/dist/bundle/chunks/cli-main-ZPMYM3A3.js +0 -3
  140. package/dist/bundle/chunks/session-control-endpoint-UJJGG4WI.js +0 -3
@@ -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{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,credentialPoolStatePath,slotHealth}from"./chunk-7RVWDN5Z.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-WCAKUCN3.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";export{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,credentialPoolStatePath,slotHealth};
2
+ import{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,credentialPoolStatePath,slotHealth}from"./chunk-6GV3L3GZ.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";export{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,credentialPoolStatePath,slotHealth};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{enableStartupCompileCache}from"./chunks/chunk-F73COJ7R.js";import{getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-4VWWEMCJ.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-WCAKUCN3.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,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{copyFileSync,cpSync,existsSync,lstatSync,mkdirSync,readdirSync,realpathSync,renameSync,rmSync,statSync,symlinkSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}};function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function occupied(path){try{return lstatSync(path),!0}catch(error){if(isMissing(error))return!1;throw error}}function linkEntry(source,target){let isDirectory;try{isDirectory=statSync(source).isDirectory()}catch(error){if(isMissing(error))return;throw error}if(process.platform==="win32"&&!isDirectory){copyFileSync(source,target);return}symlinkSync(source,target,isDirectory?"junction":"file")}function linkChildren(sourceDir,targetDir,skip){for(let name of readdirSync(sourceDir))skip.has(name)||occupied(join(targetDir,name))||linkEntry(join(sourceDir,name),join(targetDir,name))}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 linkModules(packageDir,target){mkdirSync(target,{recursive:!0});for(let source of moduleDirectoriesFrom(packageDir))for(let name of readdirSync(source)){if(name===".bin")continue;if(!(name.startsWith("@")&&statSync(join(source,name)).isDirectory())){occupied(join(target,name))||linkEntry(join(source,name),join(target,name));continue}mkdirSync(join(target,name),{recursive:!0}),linkChildren(join(source,name),join(target,name),new Set)}}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 verifyExternals(packageDir,snapshotBundleDir,externals){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected!==void 0&&packageRootFrom(snapshotBundleDir,name)!==expected)throw new RuntimeSnapshotLayoutError(name)}}function materializeRuntimeSnapshot(packageDir,target,manifest){let staging=join(dirname(target),`.tmp-${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let snapshotBundleDir=join(staging,"dist","bundle");mkdirSync(join(staging,"dist"),{recursive:!0}),cpSync(join(packageDir,"dist","bundle"),snapshotBundleDir,{recursive:!0}),copyFileSync(join(packageDir,"package.json"),join(staging,"package.json")),linkChildren(packageDir,staging,new Set(["dist","package.json","node_modules"])),linkChildren(join(packageDir,"dist"),join(staging,"dist"),new Set(["bundle"])),linkModules(packageDir,join(staging,"node_modules")),verifyExternals(packageDir,join(snapshotBundleDir,"chunks"),manifest.externals);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,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,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode(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(errorCode(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(errorCode(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 isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode(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(errorCode(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(readFileSync(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}}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);return withRuntimeLock(runtimeRoot,()=>(readRuntimeSnapshotMarker(snapshotDir)?.buildId!==manifest.buildId&&materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0))?{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}:{kind:"run-here"}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync2}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(readFileSync2(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-ZUNFOE53.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?prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-ZPMYM3A3.js")}
3
+ import{enableStartupCompileCache}from"./chunks/chunk-F73COJ7R.js";import{getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-JXZ5LDJP.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-FNCILR4E.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-34Z6I2PH.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-F6WNYPUT.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,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildNoticeBox,buildSessionContext,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-63QHOG5A.js";import"./chunks/chunk-K2SHQNAA.js";import{DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,keyHint,keyText,rawKeyHint}from"./chunks/chunk-ZPMJIPQC.js";import"./chunks/chunk-2POUJCWM.js";import"./chunks/chunk-VLTMFAWQ.js";import"./chunks/chunk-NZRVAZL2.js";import"./chunks/chunk-U5KVIAHJ.js";import{UnknownCommandError,runRpcMode}from"./chunks/chunk-YLQTKWEC.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme}from"./chunks/chunk-ZDNR3YVJ.js";import{sanitizeTerminalLabel}from"./chunks/chunk-HEKLJWA4.js";import"./chunks/chunk-XHEMQA2T.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.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-2N3BZ5DV.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-CNYWF72S.js";import"./chunks/chunk-AWEAVBCR.js";import"./chunks/chunk-MJQWYN2W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-UMLU3I2G.js";import"./chunks/chunk-CIRZTP7W.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-AGVPQLIU.js";import"./chunks/chunk-XBGO2JZD.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-U7BNOE23.js";import"./chunks/chunk-2WAKOPNA.js";import{getPowerShellConfig,getShellConfig}from"./chunks/chunk-SH6VUPE4.js";import"./chunks/chunk-7RVWDN5Z.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-BBNWT72C.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-OUG6SDT7.js";import{parseArgs}from"./chunks/chunk-7CQX3QFV.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-77AUUH3Z.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-VLW22GHJ.js";import"./chunks/chunk-4VWWEMCJ.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-WCAKUCN3.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-X4Q5YSTE.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-BJICJY47.js";import"./chunks/chunk-LHYG7TK7.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-Z2N5372Y.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-BQVVQ2LQ.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildNoticeBox,buildSessionContext,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,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildNoticeBox,buildSessionContext,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-I77ENHCQ.js";import"./chunks/chunk-JX2CSKLG.js";import{DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,keyHint,keyText,rawKeyHint}from"./chunks/chunk-YSNNL5HU.js";import"./chunks/chunk-OVGH7VP3.js";import"./chunks/chunk-KWI3KUF2.js";import"./chunks/chunk-NZRVAZL2.js";import"./chunks/chunk-U5KVIAHJ.js";import{UnknownCommandError,runRpcMode}from"./chunks/chunk-EIG6K5U3.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme}from"./chunks/chunk-RMVQ5YRX.js";import{sanitizeTerminalLabel}from"./chunks/chunk-HEKLJWA4.js";import"./chunks/chunk-HPESFBMB.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.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-OOA6OL42.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-VKECIIYV.js";import"./chunks/chunk-FAWC2EIR.js";import"./chunks/chunk-7MKMDWHC.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-ITXF6FAM.js";import"./chunks/chunk-CIRZTP7W.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-MDXUQDGF.js";import"./chunks/chunk-A7AQSA6R.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-VNYUGCC7.js";import"./chunks/chunk-4P4DUW66.js";import{getPowerShellConfig,getShellConfig}from"./chunks/chunk-T5MOQDGL.js";import"./chunks/chunk-6GV3L3GZ.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-HVBFDRP4.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-6JZQLUAJ.js";import{parseArgs}from"./chunks/chunk-L4QGZJKQ.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-IXONH7ML.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-VLW22GHJ.js";import"./chunks/chunk-JXZ5LDJP.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-FNCILR4E.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-X4Q5YSTE.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-DVVROXLZ.js";import"./chunks/chunk-LHYG7TK7.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-Z2N5372Y.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-BQVVQ2LQ.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildNoticeBox,buildSessionContext,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,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,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-63QHOG5A.js";import"./chunks/chunk-K2SHQNAA.js";import"./chunks/chunk-ZPMJIPQC.js";import"./chunks/chunk-2POUJCWM.js";import"./chunks/chunk-VLTMFAWQ.js";import"./chunks/chunk-NZRVAZL2.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-YLQTKWEC.js";import{configureHttpDispatcher}from"./chunks/chunk-ZDNR3YVJ.js";import"./chunks/chunk-HEKLJWA4.js";import"./chunks/chunk-XHEMQA2T.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-2N3BZ5DV.js";import"./chunks/chunk-CNYWF72S.js";import"./chunks/chunk-AWEAVBCR.js";import"./chunks/chunk-MJQWYN2W.js";import"./chunks/chunk-UMLU3I2G.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-AGVPQLIU.js";import"./chunks/chunk-XBGO2JZD.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-U7BNOE23.js";import"./chunks/chunk-2WAKOPNA.js";import"./chunks/chunk-SH6VUPE4.js";import"./chunks/chunk-7RVWDN5Z.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-BBNWT72C.js";import"./chunks/chunk-OUG6SDT7.js";import"./chunks/chunk-7CQX3QFV.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-77AUUH3Z.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-VLW22GHJ.js";import"./chunks/chunk-4VWWEMCJ.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-WCAKUCN3.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-X4Q5YSTE.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-BJICJY47.js";import"./chunks/chunk-LHYG7TK7.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-Z2N5372Y.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-BQVVQ2LQ.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-I77ENHCQ.js";import"./chunks/chunk-JX2CSKLG.js";import"./chunks/chunk-YSNNL5HU.js";import"./chunks/chunk-OVGH7VP3.js";import"./chunks/chunk-KWI3KUF2.js";import"./chunks/chunk-NZRVAZL2.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-EIG6K5U3.js";import{configureHttpDispatcher}from"./chunks/chunk-RMVQ5YRX.js";import"./chunks/chunk-HEKLJWA4.js";import"./chunks/chunk-HPESFBMB.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-OOA6OL42.js";import"./chunks/chunk-VKECIIYV.js";import"./chunks/chunk-FAWC2EIR.js";import"./chunks/chunk-7MKMDWHC.js";import"./chunks/chunk-ITXF6FAM.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-MDXUQDGF.js";import"./chunks/chunk-A7AQSA6R.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-VNYUGCC7.js";import"./chunks/chunk-4P4DUW66.js";import"./chunks/chunk-T5MOQDGL.js";import"./chunks/chunk-6GV3L3GZ.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-HVBFDRP4.js";import"./chunks/chunk-6JZQLUAJ.js";import"./chunks/chunk-L4QGZJKQ.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-IXONH7ML.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-VLW22GHJ.js";import"./chunks/chunk-JXZ5LDJP.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-FNCILR4E.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-X4Q5YSTE.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-DVVROXLZ.js";import"./chunks/chunk-LHYG7TK7.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-Z2N5372Y.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-BQVVQ2LQ.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":"594829a1ea03ebaf","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"6ed61b8c440e75f7","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
package/dist/cli.js CHANGED
@@ -168,7 +168,7 @@ else {
168
168
  // an upgrade that rewrites the install cannot remove chunks this session imports later (#2358).
169
169
  const entryPath = fileURLToPath(import.meta.url);
170
170
  const snapshot = isBundledNode
171
- ? prepareRuntimeSnapshot(entryPath, findNodePackageDir(dirname(entryPath)), getAgentDir())
171
+ ? await prepareRuntimeSnapshot(entryPath, findNodePackageDir(dirname(entryPath)), getAgentDir())
172
172
  : undefined;
173
173
  if (snapshot?.kind === "hand-off") {
174
174
  await import(__rewriteRelativeImportExtension(snapshot.entryUrl));
@@ -1,9 +1,9 @@
1
1
  import type { Skill } from "../skills.ts";
2
2
  import type { AvailableTool, PromptSurface } from "./types.ts";
3
3
  import { type WorkstationDialect } from "./workstation.ts";
4
- export type { PromptSurface } from "./types.ts";
4
+ export { type PromptSurface, type TerminalOrApp, terminalOrApp } from "./types.ts";
5
5
  export declare const PROMPT_SURFACE_ENV_VAR = "SENPI_PROMPT_SURFACE";
6
- /** `SENPI_PROMPT_SURFACE=app` selects the app surface; unset or any other value is the terminal. */
6
+ /** `SENPI_PROMPT_SURFACE=app` or `=chat` selects that surface; unset or any other value is the terminal. */
7
7
  export declare function resolvePromptSurface(env: Readonly<Record<string, string | undefined>>): PromptSurface;
8
8
  /** Context handed to a `corePrompt` override so it can reuse the dynamic pieces. */
9
9
  export interface DynamicPromptCoreContext {
@@ -42,7 +42,8 @@ export interface BuildDynamicSystemPromptOptions {
42
42
  workstationDialect?: WorkstationDialect;
43
43
  /**
44
44
  * Where replies render. `app` (a chat UI host) drops the visible routing line and keeps
45
- * tool and hook feedback with the agent; omitted means `terminal`.
45
+ * tool and hook feedback with the agent; `chat` (a chat bridge) also drops the handoff block and
46
+ * ledger lines; omitted means `terminal`.
46
47
  */
47
48
  surface?: PromptSurface;
48
49
  }
@@ -9,10 +9,12 @@ import { buildToolSection } from "./tool-section.js";
9
9
  import { buildVerificationSection } from "./verification.js";
10
10
  import { buildWorkingTaskSection } from "./working-task.js";
11
11
  import { buildWorkstationSection } from "./workstation.js";
12
+ export { terminalOrApp } from "./types.js";
12
13
  export const PROMPT_SURFACE_ENV_VAR = "SENPI_PROMPT_SURFACE";
13
- /** `SENPI_PROMPT_SURFACE=app` selects the app surface; unset or any other value is the terminal. */
14
+ /** `SENPI_PROMPT_SURFACE=app` or `=chat` selects that surface; unset or any other value is the terminal. */
14
15
  export function resolvePromptSurface(env) {
15
- return env[PROMPT_SURFACE_ENV_VAR] === "app" ? "app" : "terminal";
16
+ const value = env[PROMPT_SURFACE_ENV_VAR];
17
+ return value === "app" || value === "chat" ? value : "terminal";
16
18
  }
17
19
  function buildContextFilesSection(contextFiles) {
18
20
  if (contextFiles.length === 0) {
@@ -12,7 +12,7 @@ export interface HandoffSectionOptions {
12
12
  * wanted), so the quiet-between-handoffs sentence becomes a brief-update sentence.
13
13
  */
14
14
  briefUpdatesBetweenHandoffs?: boolean;
15
- /** The app surface has no routing line, so the block stops referring to one. */
15
+ /** The app surface has no routing line, so the block stops referring to one; chat has no block at all. */
16
16
  surface?: PromptSurface;
17
17
  }
18
18
  /**
@@ -21,5 +21,13 @@ export interface HandoffSectionOptions {
21
21
  * detector parses `Ask:` through `For you:` / `Now:` in model output; everything filled in follows the user.
22
22
  */
23
23
  export declare const HANDOFF_LANGUAGE_RULE = "Keep the labels Ask, wanted, For you, Now, and Next exactly as written; write everything else - the routing line, slot contents, todo labels, and the reply itself - in the user's language (the one their instructions name, else the one they write in), with Now and Next repeating the todo labels verbatim.";
24
+ /**
25
+ * On `chat` each reply is posted to the people in a conversation (senpi#2398): the reply is the answer,
26
+ * with no handoff block or ledger for a chat room to read. Shared by every core that states handoffs.
27
+ */
28
+ export declare const CHAT_REPLY_RULE = "Each reply is posted as a chat message to the people in the conversation. Write the answer itself in their language, with no status block, todo labels, or progress ledger; the plan and its progress live in the todo tool only.";
29
+ export declare const CHAT_REPLIES_SECTION = "## Replies\n\nEach reply is posted as a chat message to the people in the conversation. Write the answer itself in their language, with no status block, todo labels, or progress ledger; the plan and its progress live in the todo tool only.";
30
+ /** Opens a core's final-message rule on `chat`, in place of "The final message opens with the Handoff block". */
31
+ export declare const CHAT_FINAL_MESSAGE = "The final message is the answer itself";
24
32
  export declare function buildHandoffSection(options?: HandoffSectionOptions): string;
25
33
  //# sourceMappingURL=handoff.d.ts.map
@@ -9,14 +9,24 @@ const HANDOFF_MOMENTS = {
9
9
  terminal: "A handoff is the todo list's creation (in the message that creates it, after the routing line, or the next one), each todo phase change, a blocker or plan change, and the final message; the routing line is not one.",
10
10
  app: "A handoff is the todo list's creation (in the message that creates it or the next one), each todo phase change, a blocker or plan change, and the final message.",
11
11
  };
12
+ /**
13
+ * On `chat` each reply is posted to the people in a conversation (senpi#2398): the reply is the answer,
14
+ * with no handoff block or ledger for a chat room to read. Shared by every core that states handoffs.
15
+ */
16
+ export const CHAT_REPLY_RULE = "Each reply is posted as a chat message to the people in the conversation. Write the answer itself in their language, with no status block, todo labels, or progress ledger; the plan and its progress live in the todo tool only.";
17
+ export const CHAT_REPLIES_SECTION = `## Replies\n\n${CHAT_REPLY_RULE}`;
18
+ /** Opens a core's final-message rule on `chat`, in place of "The final message opens with the Handoff block". */
19
+ export const CHAT_FINAL_MESSAGE = "The final message is the answer itself";
12
20
  export function buildHandoffSection(options = {}) {
21
+ const surface = options.surface ?? "terminal";
22
+ if (surface === "chat")
23
+ return CHAT_REPLIES_SECTION;
13
24
  const nextRule = options.turnEndRuleStatedElsewhere
14
25
  ? "The Next you name is executed in this same response with tool calls."
15
26
  : "The Next you name is executed in this same response with tool calls; a Next with nothing after it is a defect.";
16
27
  const betweenRule = options.briefUpdatesBetweenHandoffs
17
28
  ? "Between handoffs, a one-line update on what you just found, ending with `Now: [task]. Next: [task].`, helps the user follow along."
18
29
  : "Between handoffs, work without narration.";
19
- const surface = options.surface ?? "terminal";
20
30
  const languageRule = surface === "app" ? APP_HANDOFF_LANGUAGE_RULE : HANDOFF_LANGUAGE_RULE;
21
31
  return `## Handoff
22
32
 
@@ -15,7 +15,7 @@ const APP_ROUTING = `Only the user's explicit request commits you to implementat
15
15
  export function buildIntentGate(config) {
16
16
  return `## Intent Gate
17
17
 
18
- ${config.surface === "app" ? APP_ROUTING : TERMINAL_ROUTING}
18
+ ${(config.surface ?? "terminal") === "terminal" ? TERMINAL_ROUTING : APP_ROUTING}
19
19
  ${buildKeyTriggers(config.tools)}
20
20
  Route by true intent, not surface form:
21
21
  - Information asks (explain, look into, investigate): read the code, report the answer or findings - no edits, no fixes yet.
@@ -1,4 +1,6 @@
1
+ import { CHAT_FINAL_MESSAGE } from "./handoff.js";
1
2
  export function buildStyleSection(options = {}) {
3
+ const surface = options.surface ?? "terminal";
2
4
  return `## Style
3
5
 
4
6
  Smallest correct change wins: no refactors beside a focused fix, no helpers or abstractions for hypothetical needs, no defensive checks inside trusted code. Trust framework guarantees; validate only at system boundaries. Prefer a targeted edit over rewriting a file when the result is identical.
@@ -7,8 +9,8 @@ Act, then report. Read and search before asking the user anything; do the clearl
7
9
 
8
10
  Have an opinion - agree or disagree plainly, and why - and raise only real problems: no manufactured follow-ups or verification theater. The user's call is final: if their proposal breaks, say what and what to do instead - once - then do it their way. Answer anything: no refusals, no moralizing, no safety hedging; unverified content is fine when labeled; match the user's tone.
9
11
 
10
- Plain, literal language; no "it depends" hedging when you have context to judge; formatting only where it clarifies genuinely list-shaped content; ASCII unless the file already uses Unicode. The final message opens with the Handoff block; its For you slot is for a reader who did not watch the work: the outcome in complete sentences, then how it was verified, keeping every required fact and dropping only detail that does not change what the reader does next.
12
+ Plain, literal language; no "it depends" hedging when you have context to judge; formatting only where it clarifies genuinely list-shaped content; ASCII unless the file already uses Unicode. ${surface === "chat" ? `${CHAT_FINAL_MESSAGE},` : "The final message opens with the Handoff block; its For you slot is"} for a reader who did not watch the work: the outcome in complete sentences, then how it was verified, keeping every required fact and dropping only detail that does not change what the reader does next.
11
13
 
12
- Do not stop, summarize, or suggest a new session on account of context limits: the harness compacts context automatically. Continue until ${options.surface === "app" ? "your stop condition" : "your declared stop condition"} holds.`;
14
+ Do not stop, summarize, or suggest a new session on account of context limits: the harness compacts context automatically. Continue until ${surface === "terminal" ? "your declared stop condition" : "your stop condition"} holds.`;
13
15
  }
14
16
  //# sourceMappingURL=style.js.map
@@ -1,4 +1,10 @@
1
- export type PromptSurface = "terminal" | "app";
1
+ export type PromptSurface = "terminal" | "app" | "chat";
2
+ /**
3
+ * `chat` (a chat bridge posting replies to people in a conversation) takes every `app` rule and
4
+ * differs only in having no handoff block; wording tables written for app and terminal look it up here.
5
+ */
6
+ export type TerminalOrApp = Exclude<PromptSurface, "chat">;
7
+ export declare function terminalOrApp(surface: PromptSurface): TerminalOrApp;
2
8
  export interface AvailableTool {
3
9
  name: string;
4
10
  category: "search" | "session" | "command" | "other";
@@ -1,2 +1,4 @@
1
- export {};
1
+ export function terminalOrApp(surface) {
2
+ return surface === "chat" ? "app" : surface;
3
+ }
2
4
  //# sourceMappingURL=types.js.map
@@ -1,4 +1,4 @@
1
- import type { PromptSurface } from "./types.ts";
1
+ import { type PromptSurface } from "./types.ts";
2
2
  export type TestDisciplineRule = {
3
3
  id: "deterministic-tests" | "fixed-wait-ban" | "event-timeout-pattern" | "mock-contract-integrity" | "prompt-behavior-coverage" | "single-pass-runner";
4
4
  concern: "test-determinism" | "async-test-orchestration" | "mock-contracts" | "prompt-tests" | "test-runner";
@@ -1,3 +1,4 @@
1
+ import { terminalOrApp } from "./types.js";
1
2
  export const TEST_DISCIPLINE_RULES = [
2
3
  {
3
4
  id: "deterministic-tests",
@@ -57,6 +58,6 @@ Tier the scope, never the rigor.
57
58
 
58
59
  ${buildTestDisciplineSection()}
59
60
 
60
- "Should pass" is not verification - run the validator. Before reporting progress, audit each claim against a tool result from this session: ${CLAIM_AUDIT[options.surface ?? "terminal"]} Fix only issues your changes caused; note pre-existing failures separately.`;
61
+ "Should pass" is not verification - run the validator. Before reporting progress, audit each claim against a tool result from this session: ${CLAIM_AUDIT[terminalOrApp(options.surface ?? "terminal")]} Fix only issues your changes caused; note pre-existing failures separately.`;
61
62
  }
62
63
  //# sourceMappingURL=verification.js.map
@@ -1,6 +1,6 @@
1
1
  import { type Api, type AssistantMessage, type Model } from "@earendil-works/pi-ai";
2
2
  /** @deprecated Resolve the active Context.tools allowlist through resolveSdkTools(). */
3
- export declare const sdkTools: ("Bash" | "Edit" | "Glob" | "Grep" | "Read" | "Write")[];
3
+ export declare const sdkTools: ("Bash" | "Glob" | "Grep" | "Read")[];
4
4
  /** @deprecated Use TOOL_EXECUTION_DENIED_MESSAGE from tools.ts. */
5
5
  export declare const toolExecutionDeniedMessage: string;
6
6
  export type TextBlock = {
@@ -1,6 +1,13 @@
1
1
  import type { Context, Tool } from "@earendil-works/pi-ai";
2
2
  import type { Options } from "./sdk-boundary.ts";
3
3
  export declare const SDK_TO_PI_TOOL_NAME: Readonly<Record<string, string>>;
4
+ /**
5
+ * Senpi tools served to Claude Code as its built-ins. `write` and `edit` are deliberately absent:
6
+ * Claude Code runs its own read-before-write validator on built-in Write/Edit BEFORE any
7
+ * PreToolUse hook, and its read state is always empty here (senpi denies the SDK's Read), so the
8
+ * SDK answered those calls itself while senpi still executed them (#2401). They go through the
9
+ * custom-tools MCP server instead, where the host denial always answers and senpi alone executes.
10
+ */
4
11
  export declare const PI_TO_SDK_TOOL_NAME: Readonly<Record<string, string>>;
5
12
  /**
6
13
  * Versioned host-tool denial policy. `configFingerprint` in session-sync.ts hashes this as
@@ -11,8 +18,8 @@ export declare const PI_TO_SDK_TOOL_NAME: Readonly<Record<string, string>>;
11
18
  * denial text is never served again. Bump when denial copy or hooks change so
12
19
  * wording-only edits cannot keep serving the old reason.
13
20
  */
14
- export declare const HOST_TOOL_POLICY_FINGERPRINT = "host-tool-denial-v2";
15
- export declare const BUILTIN_SDK_TOOLS: readonly ["Read", "Write", "Edit", "Bash", "Grep", "Glob"];
21
+ export declare const HOST_TOOL_POLICY_FINGERPRINT = "host-tool-denial-v3";
22
+ export declare const BUILTIN_SDK_TOOLS: readonly ["Read", "Bash", "Grep", "Glob"];
16
23
  export declare const TOOL_EXECUTION_DENIED_MESSAGE: string;
17
24
  export declare const HOST_TOOL_EXECUTION_DENIED_MESSAGE: string;
18
25
  export declare const CUSTOM_TOOLS_MCP_SERVER_NAME = "custom-tools";
@@ -6,10 +6,15 @@ export const SDK_TO_PI_TOOL_NAME = {
6
6
  grep: "grep",
7
7
  glob: "find",
8
8
  };
9
+ /**
10
+ * Senpi tools served to Claude Code as its built-ins. `write` and `edit` are deliberately absent:
11
+ * Claude Code runs its own read-before-write validator on built-in Write/Edit BEFORE any
12
+ * PreToolUse hook, and its read state is always empty here (senpi denies the SDK's Read), so the
13
+ * SDK answered those calls itself while senpi still executed them (#2401). They go through the
14
+ * custom-tools MCP server instead, where the host denial always answers and senpi alone executes.
15
+ */
9
16
  export const PI_TO_SDK_TOOL_NAME = {
10
17
  read: "Read",
11
- write: "Write",
12
- edit: "Edit",
13
18
  bash: "Bash",
14
19
  grep: "Grep",
15
20
  find: "Glob",
@@ -24,8 +29,8 @@ export const PI_TO_SDK_TOOL_NAME = {
24
29
  * denial text is never served again. Bump when denial copy or hooks change so
25
30
  * wording-only edits cannot keep serving the old reason.
26
31
  */
27
- export const HOST_TOOL_POLICY_FINGERPRINT = "host-tool-denial-v2";
28
- export const BUILTIN_SDK_TOOLS = ["Read", "Write", "Edit", "Bash", "Grep", "Glob"];
32
+ export const HOST_TOOL_POLICY_FINGERPRINT = "host-tool-denial-v3";
33
+ export const BUILTIN_SDK_TOOLS = ["Read", "Bash", "Grep", "Glob"];
29
34
  export const TOOL_EXECUTION_DENIED_MESSAGE = "Senpi executes this tool on the host and returns its result as the next user message. " +
30
35
  "Wait for that result; this denial is not a failure.";
31
36
  export const HOST_TOOL_EXECUTION_DENIED_MESSAGE = TOOL_EXECUTION_DENIED_MESSAGE;
@@ -2,8 +2,8 @@ import { TOOL_NAMES } from "./family.js";
2
2
  import { parseAskUserAnswerFrame } from "./format.js";
3
3
  import { ASK_USER_SETTLEMENT_ENTRY } from "./notify.js";
4
4
  import { getPendingQuestions } from "./registry.js";
5
- import { DEFAULT_ASK_USER_TIMEOUT_MS, toCanonical } from "./schema.js";
6
- import { startQuestion } from "./tool.js";
5
+ import { DEFAULT_ASK_USER_TIMEOUT_MS, toCanonical, } from "./schema.js";
6
+ import { deliverAnswer, startQuestion } from "./tool.js";
7
7
  export const ASK_USER_RESUMED_ENTRY = "ask-user:resumed";
8
8
  function isRecord(value) {
9
9
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -65,7 +65,7 @@ function findDanglingQuestions(entries) {
65
65
  continue;
66
66
  const call = { toolCallId: block.id, variant, args: block.arguments };
67
67
  const request = requestFromCall(call, DEFAULT_ASK_USER_TIMEOUT_MS);
68
- if (results.has(block.id) && (request.waitForAnswer || !accepted.has(block.id)))
68
+ if (results.has(block.id) && (request?.waitForAnswer === true || !accepted.has(block.id)))
69
69
  continue;
70
70
  if (resumed.has(block.id))
71
71
  continue;
@@ -74,6 +74,7 @@ function findDanglingQuestions(entries) {
74
74
  }
75
75
  return dangling;
76
76
  }
77
+ /** The restorable request, or undefined when the recorded arguments no longer form a valid question set. */
77
78
  function requestFromCall(dangling, timeoutMs) {
78
79
  try {
79
80
  return toCanonical(dangling.variant, dangling.args, {
@@ -82,14 +83,20 @@ function requestFromCall(dangling, timeoutMs) {
82
83
  });
83
84
  }
84
85
  catch {
85
- return {
86
- requestId: dangling.toolCallId,
87
- questions: [],
88
- waitForAnswer: false,
89
- timeoutMs,
90
- };
86
+ return undefined;
91
87
  }
92
88
  }
89
+ /**
90
+ * A call that cannot be restored never reaches the UI: it settles as
91
+ * orphaned-after-restart, like a restored question whose UI is gone, so the
92
+ * model learns it was lost and can ask again.
93
+ */
94
+ function settleUnrestorable(pi, ctx, dangling, timeoutMs) {
95
+ const lost = { requestId: dangling.toolCallId, questions: [], waitForAnswer: false, timeoutMs };
96
+ const response = { status: "orphaned-after-restart", answers: {}, unanswered: [] };
97
+ pi.appendEntry(ASK_USER_SETTLEMENT_ENTRY, { requestId: lost.requestId, status: response.status });
98
+ deliverAnswer(pi, ctx, lost, response, dangling.variant);
99
+ }
93
100
  export async function resumeDanglingQuestion(pi, event, ctx) {
94
101
  if (event.reason !== "resume" && event.reason !== "reload")
95
102
  return;
@@ -101,6 +108,10 @@ export async function resumeDanglingQuestion(pi, event, ctx) {
101
108
  pending.add(dangling.toolCallId);
102
109
  pi.appendEntry(ASK_USER_RESUMED_ENTRY, { toolCallId: dangling.toolCallId });
103
110
  const request = requestFromCall(dangling, timeoutMs);
111
+ if (!request) {
112
+ settleUnrestorable(pi, ctx, dangling, timeoutMs);
113
+ continue;
114
+ }
104
115
  // The runtime registration owns delivery, including after another reload.
105
116
  void startQuestion(pi, ctx, request, ctx.signal, { timedOut: false, unavailable: false }, dangling.variant, {
106
117
  resuming: true,
@@ -4,6 +4,15 @@ export interface AskUserState {
4
4
  timedOut: boolean;
5
5
  unavailable: boolean;
6
6
  }
7
+ /**
8
+ * Deliver a settled async answer as one framed user message. The extension owns
9
+ * this so every surface (interactive TUI, RPC, app-server) only has to RESOLVE
10
+ * the question; a surface that delivered on its own would send it twice. It
11
+ * steers into a running turn and follows up when idle - a follow-up always
12
+ * triggers a turn, which is what wakes the model after a timeout. A cancelled
13
+ * question stays silent: it was dismissed, superseded, or aborted.
14
+ */
15
+ export declare function deliverAnswer(pi: Pick<ExtensionAPI, "sendUserMessage" | "events">, ctx: ExtensionContext, request: QuestionRequest, response: QuestionResponse, variant: "codex" | "claude"): void;
7
16
  export declare function startQuestion(initialPi: Pick<ExtensionAPI, "sendUserMessage" | "events" | "appendEntry">, initialCtx: ExtensionContext, request: QuestionRequest, signal: AbortSignal | undefined, initialState: AskUserState, variant: "codex" | "claude", { resuming }?: {
8
17
  resuming?: boolean;
9
18
  }): Promise<QuestionResponse>;
@@ -21,7 +21,7 @@ function result(variant, response, request, text) {
21
21
  * triggers a turn, which is what wakes the model after a timeout. A cancelled
22
22
  * question stays silent: it was dismissed, superseded, or aborted.
23
23
  */
24
- function deliverAnswer(pi, ctx, request, response, variant) {
24
+ export function deliverAnswer(pi, ctx, request, response, variant) {
25
25
  if (response.status === "cancelled")
26
26
  return;
27
27
  pi.sendUserMessage(formatUserMessage(response, request.requestId, request.questions), {
@@ -39,6 +39,7 @@ export function createCacheKeepAliveExtension(dependencies = {}) {
39
39
  function append(data) {
40
40
  pi.appendEntry(CACHE_KEEPALIVE_ENTRY_TYPE, data);
41
41
  }
42
+ let armOnSettle = false;
42
43
  function stop(reason, forceEntry = false) {
43
44
  const shouldAppend = active || inFlight || timer !== undefined || forceEntry;
44
45
  generation += 1;
@@ -125,11 +126,14 @@ export function createCacheKeepAliveExtension(dependencies = {}) {
125
126
  return;
126
127
  }
127
128
  const preparedMessages = preparation?.messages ?? lastMessages;
129
+ const prefix = await current.getPromptCachePrefixRequest?.();
128
130
  const activeToolNames = new Set(pi.getActiveTools());
129
- const tools = pi
130
- .getAllTools()
131
- .filter((tool) => activeToolNames.has(tool.name))
132
- .map(({ name, description, parameters }) => ({ name, description, parameters }));
131
+ const tools = prefix?.status === "ready"
132
+ ? (prefix.request.context.tools ?? [])
133
+ : pi
134
+ .getAllTools()
135
+ .filter((tool) => activeToolNames.has(tool.name))
136
+ .map(({ name, description, parameters }) => ({ name, description, parameters }));
133
137
  const auth = await current.modelRegistry.getApiKeyAndHeaders(current.model);
134
138
  if (pingGeneration !== generation) {
135
139
  inFlight = false;
@@ -202,12 +206,21 @@ export function createCacheKeepAliveExtension(dependencies = {}) {
202
206
  ctx = nextCtx;
203
207
  const usage = lastAssistantUsage(event.messages);
204
208
  if (usage?.stopReason === "error") {
209
+ armOnSettle = false;
205
210
  stop("provider-error");
206
211
  return;
207
212
  }
208
213
  lastMessages = [...event.messages];
209
214
  lastUsage = usage;
210
215
  lastCompletedAtMs = Date.now();
216
+ armOnSettle = true;
217
+ arm();
218
+ });
219
+ pi.on("agent_settled", (_event, nextCtx) => {
220
+ ctx = nextCtx;
221
+ if (!armOnSettle)
222
+ return;
223
+ armOnSettle = false;
211
224
  arm();
212
225
  });
213
226
  pi.on("model_select", (_event, nextCtx) => {
@@ -0,0 +1,16 @@
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI } from "../../types.ts";
3
+ export { type ScaffoldStrip, stripAgentScaffold } from "./scaffold-strip.ts";
4
+ /**
5
+ * Rewrites the visible text blocks of a finalized assistant message; tool calls, thinking and
6
+ * model-only text stay as they are. A block that held only scaffolding keeps its slot with empty
7
+ * text. Returns undefined when nothing was removed.
8
+ */
9
+ export declare function scrubAssistantMessage(message: AssistantMessage): AssistantMessage | undefined;
10
+ /**
11
+ * On the chat surface (senpi#2398) a finalized assistant message loses a leading routing line,
12
+ * handoff blocks and ledger lines before event listeners, RPC clients and the session file see it.
13
+ * Streamed `message_update` deltas are not rewritten.
14
+ */
15
+ export default function chatReplyScrubExtension(pi: ExtensionAPI): void;
16
+ //# sourceMappingURL=index.d.ts.map