@code-yeongyu/senpi 2026.10.4 → 2026.10.5

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 (91) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundle/chunks/{anthropic-messages-GE4OCV55.js → anthropic-messages-G5236QNK.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-I2AKSC6I.js → app-server-command-3Q5G4CAF.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-2CS2GZBE.js → chunk-2WV426OJ.js} +2 -2
  5. package/dist/bundle/chunks/{chunk-INGR4HFB.js → chunk-ECDLITEY.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-6O26XO2C.js → chunk-EEOKVSNF.js} +220 -252
  7. package/dist/bundle/chunks/{chunk-MNLBL232.js → chunk-JVSOW4QU.js} +1 -1
  8. package/dist/bundle/chunks/chunk-K3BXFPWZ.js +2 -0
  9. package/dist/bundle/chunks/{chunk-QOT4HXY2.js → chunk-UHRXXTFZ.js} +3 -3
  10. package/dist/bundle/chunks/chunk-UUAKEDVS.js +14 -0
  11. package/dist/bundle/chunks/{chunk-ZKLQIAG5.js → chunk-UXIQK5NQ.js} +1 -1
  12. package/dist/bundle/chunks/chunk-WTJU5B2C.js +51 -0
  13. package/dist/bundle/chunks/chunk-YSPHACIN.js +2 -0
  14. package/dist/bundle/chunks/{cli-main-BLXUYHLQ.js → cli-main-VZWSUHFB.js} +1 -1
  15. package/dist/bundle/chunks/{help-fast-path-TQWU6DPG.js → help-fast-path-SHZJ3QWQ.js} +1 -1
  16. package/dist/bundle/chunks/{host-command-JXNOYPAC.js → host-command-7JIGGOWR.js} +1 -1
  17. package/dist/bundle/chunks/{interactive-mode-CSVSUAS7.js → interactive-mode-JA7AHYYL.js} +1 -1
  18. package/dist/bundle/chunks/multi-session-host-34WOINP4.js +23 -0
  19. package/dist/bundle/chunks/{openai-completions-2DUKDEVN.js → openai-completions-VSH22FCN.js} +1 -1
  20. package/dist/bundle/chunks/{openai-responses-WCB4HIPI.js → openai-responses-WLBHCFYL.js} +1 -1
  21. package/dist/bundle/chunks/{package-manager-cli-Q5EQZL7I.js → package-manager-cli-2QLVGQSC.js} +1 -1
  22. package/dist/bundle/chunks/{rotation-stream-VZLJIEP5.js → rotation-stream-JUCEXHWU.js} +1 -1
  23. package/dist/bundle/chunks/{rpc-mode-6VMXY46C.js → rpc-mode-QEBSN2OH.js} +1 -1
  24. package/dist/bundle/chunks/{session-control-endpoint-K3RWX652.js → session-control-endpoint-UGQIP6ZN.js} +1 -1
  25. package/dist/bundle/chunks/{session-picker-IPG3MKRC.js → session-picker-HX4LOJZ7.js} +1 -1
  26. package/dist/bundle/chunks/session-worker.js +251 -242
  27. package/dist/bundle/cli.js +1 -1
  28. package/dist/bundle/index.js +1 -1
  29. package/dist/bundle/rpc-entry.js +1 -1
  30. package/dist/bundle/runtime-manifest.json +1 -1
  31. package/dist/core/agent-session-runtime.d.ts +5 -0
  32. package/dist/core/agent-session-runtime.js +5 -0
  33. package/dist/core/agent-session-services.d.ts +1 -0
  34. package/dist/core/agent-session-services.js +1 -0
  35. package/dist/core/agent-session.d.ts +14 -0
  36. package/dist/core/agent-session.js +31 -0
  37. package/dist/core/browser-engine.d.ts +7 -0
  38. package/dist/core/browser-engine.js +7 -0
  39. package/dist/core/continue-from-leaf.d.ts +18 -0
  40. package/dist/core/continue-from-leaf.js +30 -0
  41. package/dist/core/extensions/builtin/gpt-apply-patch/line-endings.d.ts +28 -0
  42. package/dist/core/extensions/builtin/gpt-apply-patch/line-endings.js +76 -0
  43. package/dist/core/extensions/builtin/gpt-apply-patch/parser.js +21 -23
  44. package/dist/core/extensions/builtin/gpt-apply-patch/patch-replace.js +5 -16
  45. package/dist/core/extensions/builtin/gpt-apply-patch/streaming-parser.js +3 -1
  46. package/dist/core/extensions/builtin/gpt-apply-patch/text.d.ts +8 -0
  47. package/dist/core/extensions/builtin/gpt-apply-patch/text.js +26 -3
  48. package/dist/core/extensions/builtin/gpt-apply-patch/types.d.ts +2 -0
  49. package/dist/core/extensions/builtin/terminal/tools/bash.d.ts +1 -0
  50. package/dist/core/extensions/builtin/terminal/tools/bash.js +8 -1
  51. package/dist/core/extensions/runner.d.ts +1 -0
  52. package/dist/core/extensions/runner.js +7 -0
  53. package/dist/core/extensions/types.d.ts +4 -0
  54. package/dist/core/model-resolver.js +1 -1
  55. package/dist/core/sdk.d.ts +3 -0
  56. package/dist/core/sdk.js +1 -0
  57. package/dist/core/tools/bash.js +3 -0
  58. package/dist/main.js +1 -0
  59. package/dist/modes/interactive/components/session-selector.d.ts +11 -0
  60. package/dist/modes/interactive/components/session-selector.js +30 -5
  61. package/dist/modes/rpc/connection-handler.js +18 -1
  62. package/dist/modes/rpc/custom-capability.d.ts +9 -0
  63. package/dist/modes/rpc/custom-capability.js +9 -0
  64. package/dist/modes/rpc/host-daemon-env.js +2 -0
  65. package/dist/modes/rpc/host-idle-handover.js +1 -0
  66. package/dist/modes/rpc/media-placeholders.d.ts +23 -1
  67. package/dist/modes/rpc/media-placeholders.js +16 -13
  68. package/dist/modes/rpc/rpc-client.d.ts +8 -0
  69. package/dist/modes/rpc/rpc-client.js +8 -0
  70. package/dist/modes/rpc/rpc-input-validation.d.ts +6 -0
  71. package/dist/modes/rpc/rpc-input-validation.js +11 -0
  72. package/dist/modes/rpc/rpc-types.d.ts +19 -0
  73. package/dist/modes/rpc/session-command-router.js +11 -2
  74. package/dist/modes/rpc/session-event-writer.d.ts +4 -0
  75. package/dist/modes/rpc/session-event-writer.js +12 -1
  76. package/dist/modes/rpc/session-registry-attach.js +4 -0
  77. package/dist/modes/rpc/session-worker-client.d.ts +3 -0
  78. package/dist/modes/rpc/session-worker-client.js +6 -0
  79. package/dist/modes/rpc/session-worker-protocol.d.ts +5 -0
  80. package/dist/modes/rpc/session-worker.js +6 -0
  81. package/dist/modes/rpc/tool-media-store.d.ts +59 -0
  82. package/dist/modes/rpc/tool-media-store.js +190 -0
  83. package/dist/modes/rpc/worker-session-registry.js +8 -3
  84. package/docs/environment-variables.md +1 -0
  85. package/docs/rpc.md +62 -3
  86. package/package.json +7 -6
  87. package/dist/bundle/chunks/chunk-KMMECBM2.js +0 -15
  88. package/dist/bundle/chunks/chunk-LHYG7TK7.js +0 -2
  89. package/dist/bundle/chunks/chunk-LJWC5IVX.js +0 -2
  90. package/dist/bundle/chunks/chunk-PC3E2YS6.js +0 -9
  91. package/dist/bundle/chunks/multi-session-host-5AFJKSSM.js +0 -23
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
3
  import{enableStartupCompileCache}from"./chunks/chunk-F73COJ7R.js";import{getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync2,realpathSync as realpathSync3}from"node:fs";import{dirname as dirname3,join as join5}from"node:path";import{fileURLToPath}from"node:url";import{createHash}from"node:crypto";import{readFileSync as readFileSync3,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname2,join as join3,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync,mkdirSync,readdirSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";import{constants}from"node:fs";import{copyFile,link}from"node:fs/promises";function errorCode(error){return error instanceof Error&&"code"in error?error.code:void 0}var FILE_OPERATIONS={copyFile,link},COPY_CONCURRENCY=8;function nextCopyMode(mode,error,platform){let code=errorCode(error);if(!(code==="ENOENT"||code==="ENOTDIR"||code==="EEXIST"))switch(mode){case"clone":return platform==="darwin"&&code==="ENOSYS"?"clone-or-copy":"link";case"link":return"copy";case"clone-or-copy":case"copy":return}}function createSnapshotFileCopier(platform=process.platform,operations=FILE_OPERATIONS){let mode="clone",attempt=(current,source,target)=>{switch(current){case"clone":return operations.copyFile(source,target,constants.COPYFILE_FICLONE_FORCE);case"clone-or-copy":return operations.copyFile(source,target,constants.COPYFILE_FICLONE);case"link":return operations.link(source,target);case"copy":return operations.copyFile(source,target,0)}};return{get mode(){return mode},async copy(source,target){for(let current=mode;;)try{await attempt(current,source,target);return}catch(error){let next=nextCopyMode(current,error,platform);if(next===void 0)throw error;current=next,mode=next}}}}async function copyFiles(pairs,copier){let next=0,worker=async()=>{for(let index=next++;index<pairs.length;index=next++){let[source,target]=pairs[index]??[];source!==void 0&&target!==void 0&&await copier.copy(source,target)}};await Promise.all(Array.from({length:Math.min(COPY_CONCURRENCY,pairs.length)},worker))}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-",UNLOADED_FILE=/\.(?:d\.[cm]?ts|map)$/;function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function planTree(source,target,files,skipModules,seen=new Set){let real=realpathSync(source);if(!seen.has(real)){seen.add(real),mkdirSync(target,{recursive:!0});for(let entry of readdirSync(real,{withFileTypes:!0})){if(skipModules&&entry.name==="node_modules")continue;let from=join(real,entry.name),to=join(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen);else if(entry.isFile())UNLOADED_FILE.test(entry.name)||files.push([from,to]);else if(entry.isSymbolicLink()){let isDirectory;try{isDirectory=statSync(from).isDirectory()}catch(error){if(isMissing(error))continue;throw error}isDirectory?planTree(from,to,files,skipModules,seen):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname(current)){if(basename(current)!=="node_modules"){let candidate=join(current,"node_modules");existsSync(candidate)&&directories.push(candidate)}if(dirname(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join(modules,packageName);if(existsSync(join(root,"package.json")))return realpathSync(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return[];let names=new Set;for(let field of["dependencies","optionalDependencies","peerDependencies"]){let block=manifest[field];if(typeof block=="object"&&block!==null)for(let name of Object.keys(block))names.add(name)}return[...names]}function closureNames(packageDir,extra){let names=new Set(extra),visited=new Set,pending=[realpathSync(packageDir)];for(let dir=pending.pop();dir!==void 0;dir=pending.pop())if(!visited.has(dir)){visited.add(dir);for(let name of dependencyNames(dir)){names.add(name);let root=packageRootFrom(dir,name);root!==void 0&&!visited.has(root)&&pending.push(root)}}return names}function planModules(packageDir,snapshotRoot,externals,files){let self=realpathSync(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join(snapshotRoot,"node_modules",name))}for(let next=pending.shift();next!==void 0;next=pending.shift())for(let name of dependencyNames(next.installDir)){let expected=packageRootFrom(next.installDir,name);expected===void 0||expected===self||resolvePlaced(next.snapshotDir,name)!==expected&&place(expected,join(next.snapshotDir,"node_modules",name))}return placed}function verifyExternals(packageDir,snapshotBundleDir,externals,placed){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected===void 0)continue;let found=moduleDirectoriesFrom(snapshotBundleDir).map(modules=>join(modules,name)).find(root=>existsSync(join(root,"package.json")));if(found===void 0||placed.get(found)!==expected)throw new RuntimeSnapshotLayoutError(name)}}async function materializeRuntimeSnapshot(packageDir,target,manifest,copier=createSnapshotFileCopier()){let staging=join(dirname(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planTree(packageDir,staging,files,!0);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync(packageDir)};writeFileSync(join(staging,RUNTIME_SNAPSHOT_MARKER),`${JSON.stringify(marker)}
4
- `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-TQWU6DPG.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-BLXUYHLQ.js")}
4
+ `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-SHZJ3QWQ.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-VZWSUHFB.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,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,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,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,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSessionEntries,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-6O26XO2C.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-PC3E2YS6.js";import"./chunks/chunk-QNAG7FYM.js";import{DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,keyHint,keyText,rawKeyHint}from"./chunks/chunk-KMMECBM2.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-ZKLQIAG5.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import{sanitizeTerminalLabel}from"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-INGR4HFB.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-2CS2GZBE.js";import"./chunks/chunk-LJWC5IVX.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-6JXPZACL.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-MNLBL232.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HKG7XL4H.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-22DAHAHO.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-XYDZ3LIE.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-6SMU7ANE.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-QOT4HXY2.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-LHYG7TK7.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-EEOKVSNF.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-UUAKEDVS.js";import"./chunks/chunk-QNAG7FYM.js";import{CURRENT_SESSION_VERSION,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionManager,SessionSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,keyHint,keyText,migrateSessionEntries,parseSessionEntries,rawKeyHint,sessionEntryToContextMessages}from"./chunks/chunk-WTJU5B2C.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-UXIQK5NQ.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import{sanitizeTerminalLabel}from"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-ECDLITEY.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-2WV426OJ.js";import"./chunks/chunk-K3BXFPWZ.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-6JXPZACL.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-JVSOW4QU.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HKG7XL4H.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-22DAHAHO.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-XYDZ3LIE.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-6SMU7ANE.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-UHRXXTFZ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-YSPHACIN.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -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-6O26XO2C.js";import"./chunks/chunk-PC3E2YS6.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-KMMECBM2.js";import{configureHttpDispatcher}from"./chunks/chunk-ZKLQIAG5.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-INGR4HFB.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-2CS2GZBE.js";import"./chunks/chunk-LJWC5IVX.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-6JXPZACL.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-MNLBL232.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HKG7XL4H.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-22DAHAHO.js";import"./chunks/chunk-XYDZ3LIE.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import"./chunks/chunk-6SMU7ANE.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-QOT4HXY2.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-LHYG7TK7.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{main}from"./chunks/chunk-EEOKVSNF.js";import"./chunks/chunk-UUAKEDVS.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-WTJU5B2C.js";import{configureHttpDispatcher}from"./chunks/chunk-UXIQK5NQ.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-V2VQ4BHG.js";import"./chunks/chunk-K4AZKFRB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-ECDLITEY.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-2WV426OJ.js";import"./chunks/chunk-K3BXFPWZ.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-6JXPZACL.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-JVSOW4QU.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-HKG7XL4H.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-22DAHAHO.js";import"./chunks/chunk-XYDZ3LIE.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-7Q3EY6HH.js";import"./chunks/chunk-6SMU7ANE.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-UHRXXTFZ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-YSPHACIN.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-BBK6SSYT.js";import"./chunks/chunk-BPX6QWPD.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -1 +1 @@
1
- {"buildId":"3308e7a6780d7587","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"f189e9b8598b3204","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
@@ -1,5 +1,6 @@
1
1
  import type { AgentSession } from "./agent-session.ts";
2
2
  import type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from "./agent-session-services.ts";
3
+ import type { BrowserEngine } from "./browser-engine.ts";
3
4
  import type { PromptSurface } from "./dynamic-prompt/types.ts";
4
5
  import type { HostMcpRegistry } from "./extensions/builtin/mcp/host-registry.ts";
5
6
  import type { ProjectTrustContext, ReplacedSessionContext, SessionContext, SessionKind, SessionStartEvent } from "./extensions/index.ts";
@@ -39,6 +40,8 @@ export interface AgentSessionLaunchProfile {
39
40
  autoTitle?: boolean;
40
41
  /** Per-session prompt surface (`open_session.promptSurface`); absent means `SENPI_PROMPT_SURFACE`. */
41
42
  promptSurface?: PromptSurface;
43
+ /** Per-session browser engine (`open_session.browserEngine`); absent means none was chosen. */
44
+ browserEngine?: BrowserEngine;
42
45
  }
43
46
  /**
44
47
  * Creates a full runtime for a target cwd and session manager.
@@ -92,6 +95,8 @@ export declare class AgentSessionRuntime {
92
95
  get launchProfile(): Readonly<AgentSessionLaunchProfile> | undefined;
93
96
  /** Moves this session to another prompt surface; later replacements (switch, new, fork) keep it. */
94
97
  setPromptSurface(surface: PromptSurface): void;
98
+ /** Moves this session to another browser engine; later replacements (switch, new, fork) keep it. */
99
+ setBrowserEngine(engine: BrowserEngine): void;
95
100
  setRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void;
96
101
  /**
97
102
  * Set a synchronous callback that runs after `session_shutdown` handlers finish
@@ -71,6 +71,11 @@ export class AgentSessionRuntime {
71
71
  this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), promptSurface: surface });
72
72
  this._session.setPromptSurface(surface);
73
73
  }
74
+ /** Moves this session to another browser engine; later replacements (switch, new, fork) keep it. */
75
+ setBrowserEngine(engine) {
76
+ this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), browserEngine: engine });
77
+ this._session.setBrowserEngine(engine);
78
+ }
74
79
  setRebindSession(rebindSession) {
75
80
  this.rebindSession = rebindSession;
76
81
  }
@@ -72,6 +72,7 @@ export interface CreateAgentSessionFromServicesOptions {
72
72
  customTools?: ToolDefinition[];
73
73
  autoTitleSessions?: boolean;
74
74
  promptSurface?: CreateAgentSessionOptions["promptSurface"];
75
+ browserEngine?: CreateAgentSessionOptions["browserEngine"];
75
76
  }
76
77
  /**
77
78
  * Coherent cwd-bound runtime services for one effective session cwd.
@@ -171,6 +171,7 @@ export async function createAgentSessionFromServices(options) {
171
171
  sessionStartEvent: options.sessionStartEvent,
172
172
  autoTitleSessions: options.autoTitleSessions,
173
173
  promptSurface: options.promptSurface,
174
+ browserEngine: options.browserEngine,
174
175
  });
175
176
  }
176
177
  //# sourceMappingURL=agent-session-services.js.map
@@ -18,6 +18,7 @@ import type { Api, ImageContent, Model, TextContent } from "@earendil-works/pi-a
18
18
  import { type AgentAbortSource } from "./agent-abort-provenance.ts";
19
19
  import { DeferredTurnClaim } from "./agent-settled-delivery.ts";
20
20
  import { type BashResult } from "./bash-executor.ts";
21
+ import type { BrowserEngine } from "./browser-engine.ts";
21
22
  import { type ClientMessageIdentity, type PreparedClientInput } from "./client-message-identity.ts";
22
23
  import { type CompactionResult } from "./compaction/index.ts";
23
24
  import { type CompactionLifecycleState } from "./compaction/lifecycle.ts";
@@ -339,6 +340,8 @@ export interface AgentSessionConfig {
339
340
  autoTitleSessions?: boolean;
340
341
  /** Where this session's replies render; omitted means `SENPI_PROMPT_SURFACE` decides. */
341
342
  promptSurface?: PromptSurface;
343
+ /** Browser engine this session's skills drive; omitted means none was chosen. */
344
+ browserEngine?: BrowserEngine;
342
345
  }
343
346
  type SessionModelEntry = {
344
347
  model: Model<any>;
@@ -661,6 +664,7 @@ export declare class AgentSession {
661
664
  private _baseSystemPromptOptions;
662
665
  private _systemPromptOverride?;
663
666
  private _promptSurface;
667
+ private _browserEngine;
664
668
  constructor(config: AgentSessionConfig);
665
669
  get modelRuntime(): ModelRuntime;
666
670
  get modelRegistry(): ModelRegistry;
@@ -1012,6 +1016,9 @@ export declare class AgentSession {
1012
1016
  * turn's `before_agent_start` hands presets the new surface through `systemPromptOptions`.
1013
1017
  */
1014
1018
  setPromptSurface(surface: PromptSurface): void;
1019
+ /** Moves this session to another browser engine (a later `open_session.browserEngine`); the next tool call sees it. */
1020
+ setBrowserEngine(engine: BrowserEngine): void;
1021
+ get browserEngine(): BrowserEngine | undefined;
1015
1022
  /** Current effective system prompt (includes any per-turn extension modifications) */
1016
1023
  get systemPrompt(): string;
1017
1024
  /** Current retry attempt (0 if not retrying) */
@@ -1724,6 +1731,13 @@ export declare class AgentSession {
1724
1731
  aborted?: boolean;
1725
1732
  summaryEntry?: BranchSummaryEntry;
1726
1733
  }>;
1734
+ /**
1735
+ * Start a turn from the current leaf with no new user prompt (senpi #1930): after an edited
1736
+ * assistant response becomes the leaf, the model continues from its edited text. Delivered as a
1737
+ * hidden custom message, never as a trailing assistant message (see continue-from-leaf.ts).
1738
+ * Refuses while streaming and on a session with no messages; resolves once the turn starts.
1739
+ */
1740
+ continueFromLeaf(): Promise<void>;
1727
1741
  /**
1728
1742
  * Replace an assistant response with an edited copy. The leaf moves to the target's parent and
1729
1743
  * the edited message is appended there as the new leaf, so the original and everything after it
@@ -40,6 +40,7 @@ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estima
40
40
  import { CompactionLifecycleCoordinator } from "./compaction/lifecycle.js";
41
41
  import { isTurnStuckOnContextOverflow } from "./compaction/stuck-overflow.js";
42
42
  import { isWarmSummaryAnchorValid } from "./compaction/warm-anchor.js";
43
+ import { CONTINUE_FROM_LEAF_CUSTOM_TYPE, CONTINUE_FROM_LEAF_DIRECTIVE, ContinueFromLeafError, } from "./continue-from-leaf.js";
43
44
  import { admitCursorHistory, cursorAdmissionBudgetBytes } from "./cursor-history-admission.js";
44
45
  import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
45
46
  import { resolveDiscoveredResourcePaths } from "./discovered-resource-scope.js";
@@ -488,6 +489,7 @@ export class AgentSession {
488
489
  }
489
490
  };
490
491
  this._promptSurface = config.promptSurface;
492
+ this._browserEngine = config.browserEngine;
491
493
  this.agent = config.agent;
492
494
  this.sessionManager = config.sessionManager;
493
495
  this.settingsManager = config.settingsManager;
@@ -2872,6 +2874,13 @@ export class AgentSession {
2872
2874
  this._systemPromptOverride = undefined;
2873
2875
  this._applyToolDeclarations(this.getActiveToolNames());
2874
2876
  }
2877
+ /** Moves this session to another browser engine (a later `open_session.browserEngine`); the next tool call sees it. */
2878
+ setBrowserEngine(engine) {
2879
+ this._browserEngine = engine;
2880
+ }
2881
+ get browserEngine() {
2882
+ return this._browserEngine;
2883
+ }
2875
2884
  /** Current effective system prompt (includes any per-turn extension modifications) */
2876
2885
  get systemPrompt() {
2877
2886
  return this.agent.state.systemPrompt;
@@ -7133,6 +7142,7 @@ export class AgentSession {
7133
7142
  };
7134
7143
  },
7135
7144
  getAskUserSettings: () => this.settingsManager.getAskUserSettings(),
7145
+ getBrowserEngine: () => this._browserEngine,
7136
7146
  getImageSettings: () => ({
7137
7147
  autoResize: this.settingsManager.getImageAutoResize(),
7138
7148
  blockImages: this.settingsManager.getBlockImages(),
@@ -8488,6 +8498,27 @@ export class AgentSession {
8488
8498
  async navigateTree(targetId, options = {}) {
8489
8499
  return this._navigateTree(targetId, options);
8490
8500
  }
8501
+ /**
8502
+ * Start a turn from the current leaf with no new user prompt (senpi #1930): after an edited
8503
+ * assistant response becomes the leaf, the model continues from its edited text. Delivered as a
8504
+ * hidden custom message, never as a trailing assistant message (see continue-from-leaf.ts).
8505
+ * Refuses while streaming and on a session with no messages; resolves once the turn starts.
8506
+ */
8507
+ async continueFromLeaf() {
8508
+ if (this.isStreaming)
8509
+ throw new ContinueFromLeafError("streaming");
8510
+ if (this.agent.state.messages.length === 0)
8511
+ throw new ContinueFromLeafError("nothing_to_continue");
8512
+ // Only an answer can be continued; a prompt left as the leaf (an edited one) is retried, not continued.
8513
+ const leaf = this.agent.state.messages[this.agent.state.messages.length - 1];
8514
+ if (leaf?.role !== "assistant")
8515
+ throw new ContinueFromLeafError("leaf_not_assistant");
8516
+ await this.sendCustomMessage({
8517
+ customType: CONTINUE_FROM_LEAF_CUSTOM_TYPE,
8518
+ content: CONTINUE_FROM_LEAF_DIRECTIVE,
8519
+ display: false,
8520
+ }, { triggerTurn: true });
8521
+ }
8491
8522
  /**
8492
8523
  * Replace an assistant response with an edited copy. The leaf moves to the target's parent and
8493
8524
  * the edited message is appended there as the new leaf, so the original and everything after it
@@ -0,0 +1,7 @@
1
+ export declare const BROWSER_ENGINES: readonly ["connected", "builtin", "none"];
2
+ /** Which browser a session's skills drive: the user's own, the app's built-in one, or none. */
3
+ export type BrowserEngine = (typeof BROWSER_ENGINES)[number];
4
+ /** The variable a session's tool subprocesses and eval kernels read the engine from. */
5
+ export declare const BROWSER_ENGINE_ENV = "OMO_BROWSER_ENGINE";
6
+ export declare function isBrowserEngine(value: unknown): value is BrowserEngine;
7
+ //# sourceMappingURL=browser-engine.d.ts.map
@@ -0,0 +1,7 @@
1
+ export const BROWSER_ENGINES = ["connected", "builtin", "none"];
2
+ /** The variable a session's tool subprocesses and eval kernels read the engine from. */
3
+ export const BROWSER_ENGINE_ENV = "OMO_BROWSER_ENGINE";
4
+ export function isBrowserEngine(value) {
5
+ return BROWSER_ENGINES.some((engine) => engine === value);
6
+ }
7
+ //# sourceMappingURL=browser-engine.js.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Continue a session from its current leaf with no new prompt (senpi #1930).
3
+ *
4
+ * A request may not end with an assistant message on the default models
5
+ * (Claude 4.6+ rejects assistant prefill, OpenAI's Responses API has none), so
6
+ * the continuation is a hidden custom message (display false) that drives the
7
+ * next turn, the same mechanism as the "." manual-continue shortcut. It has its
8
+ * own type so extensions that react to a manual continue (a blocked goal
9
+ * resuming) do not mistake it for one.
10
+ */
11
+ export declare const CONTINUE_FROM_LEAF_CUSTOM_TYPE = "continue-from-leaf";
12
+ export declare const CONTINUE_FROM_LEAF_DIRECTIVE = "<system-notice>\nContinue from where the conversation ends.\n\nYour last reply may have been edited by the user; treat its current text as your own words.\nCarry on from it without repeating it, apologizing for it, or commenting on the edit.\n</system-notice>";
13
+ export type ContinueFromLeafCode = "streaming" | "nothing_to_continue" | "leaf_not_assistant";
14
+ export declare class ContinueFromLeafError extends Error {
15
+ readonly code: ContinueFromLeafCode;
16
+ constructor(code: ContinueFromLeafCode);
17
+ }
18
+ //# sourceMappingURL=continue-from-leaf.d.ts.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Continue a session from its current leaf with no new prompt (senpi #1930).
3
+ *
4
+ * A request may not end with an assistant message on the default models
5
+ * (Claude 4.6+ rejects assistant prefill, OpenAI's Responses API has none), so
6
+ * the continuation is a hidden custom message (display false) that drives the
7
+ * next turn, the same mechanism as the "." manual-continue shortcut. It has its
8
+ * own type so extensions that react to a manual continue (a blocked goal
9
+ * resuming) do not mistake it for one.
10
+ */
11
+ export const CONTINUE_FROM_LEAF_CUSTOM_TYPE = "continue-from-leaf";
12
+ export const CONTINUE_FROM_LEAF_DIRECTIVE = `<system-notice>
13
+ Continue from where the conversation ends.
14
+
15
+ Your last reply may have been edited by the user; treat its current text as your own words.
16
+ Carry on from it without repeating it, apologizing for it, or commenting on the edit.
17
+ </system-notice>`;
18
+ const CONTINUE_FROM_LEAF_MESSAGES = {
19
+ streaming: "Wait for the current response to finish before continuing.",
20
+ nothing_to_continue: "There is nothing to continue: the session has no messages yet.",
21
+ leaf_not_assistant: "There is no answer to continue: the conversation ends on a user message. Send it, or retry it, instead.",
22
+ };
23
+ export class ContinueFromLeafError extends Error {
24
+ constructor(code) {
25
+ super(CONTINUE_FROM_LEAF_MESSAGES[code]);
26
+ this.name = "ContinueFromLeafError";
27
+ this.code = code;
28
+ }
29
+ }
30
+ //# sourceMappingURL=continue-from-leaf.js.map
@@ -0,0 +1,28 @@
1
+ export type LineReplacement = {
2
+ readonly start: number;
3
+ readonly oldLength: number;
4
+ readonly newLines: string[];
5
+ };
6
+ /** `[index in oldLines, index in newLines]` of a context line, which sits on both sides of a chunk. */
7
+ export type ContextLineIndex = readonly [number, number];
8
+ /**
9
+ * Splits a matched chunk into replacements that skip its context lines, so those source lines keep
10
+ * their exact text and ending (Codex `compute_replacements`, PreserveLineEndings mode). Context
11
+ * indices past the matched region belong to a trailing empty line the matcher already dropped.
12
+ */
13
+ export declare function replacementsAroundContext(start: number, oldLength: number, newLines: string[], contextLineIndices: readonly ContextLineIndex[]): LineReplacement[];
14
+ /**
15
+ * A file split into lines that remember their own line ending, so an update rewrites only the lines a
16
+ * patch touches. Mirrors Codex `codex-rs/apply-patch/src/text_file.rs`: unchanged lines keep their
17
+ * endings, inserted lines take the file's first ending (LF when it has none), and every line ends with
18
+ * an ending, which keeps apply_patch's trailing-newline behavior.
19
+ */
20
+ export declare class SourceText {
21
+ private readonly lines;
22
+ private readonly preferredEnding;
23
+ private constructor();
24
+ static parse(content: string): SourceText;
25
+ get texts(): string[];
26
+ replace(replacements: readonly LineReplacement[]): string;
27
+ }
28
+ //# sourceMappingURL=line-endings.d.ts.map
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Splits a matched chunk into replacements that skip its context lines, so those source lines keep
3
+ * their exact text and ending (Codex `compute_replacements`, PreserveLineEndings mode). Context
4
+ * indices past the matched region belong to a trailing empty line the matcher already dropped.
5
+ */
6
+ export function replacementsAroundContext(start, oldLength, newLines, contextLineIndices) {
7
+ const replacements = [];
8
+ let oldStart = 0;
9
+ let newStart = 0;
10
+ for (const [oldContext, newContext] of contextLineIndices) {
11
+ if (oldContext >= oldLength || newContext >= newLines.length)
12
+ break;
13
+ if (oldStart !== oldContext || newStart !== newContext) {
14
+ replacements.push({
15
+ start: start + oldStart,
16
+ oldLength: oldContext - oldStart,
17
+ newLines: newLines.slice(newStart, newContext),
18
+ });
19
+ }
20
+ oldStart = oldContext + 1;
21
+ newStart = newContext + 1;
22
+ }
23
+ if (oldStart !== oldLength || newStart !== newLines.length) {
24
+ replacements.push({
25
+ start: start + oldStart,
26
+ oldLength: oldLength - oldStart,
27
+ newLines: newLines.slice(newStart),
28
+ });
29
+ }
30
+ return replacements;
31
+ }
32
+ /**
33
+ * A file split into lines that remember their own line ending, so an update rewrites only the lines a
34
+ * patch touches. Mirrors Codex `codex-rs/apply-patch/src/text_file.rs`: unchanged lines keep their
35
+ * endings, inserted lines take the file's first ending (LF when it has none), and every line ends with
36
+ * an ending, which keeps apply_patch's trailing-newline behavior.
37
+ */
38
+ export class SourceText {
39
+ constructor(lines, preferredEnding) {
40
+ this.lines = lines;
41
+ this.preferredEnding = preferredEnding;
42
+ }
43
+ static parse(content) {
44
+ const lines = [];
45
+ let preferredEnding;
46
+ let lineStart = 0;
47
+ for (let cursor = 0; cursor < content.length; cursor++) {
48
+ const character = content[cursor];
49
+ if (character !== "\n" && character !== "\r")
50
+ continue;
51
+ const ending = character === "\r" && content[cursor + 1] === "\n" ? "\r\n" : character;
52
+ preferredEnding ??= ending;
53
+ lines.push({ text: content.slice(lineStart, cursor), ending });
54
+ cursor += ending.length - 1;
55
+ lineStart = cursor + 1;
56
+ }
57
+ if (lineStart < content.length)
58
+ lines.push({ text: content.slice(lineStart), ending: undefined });
59
+ return new SourceText(lines, preferredEnding ?? "\n");
60
+ }
61
+ get texts() {
62
+ return this.lines.map((line) => line.text);
63
+ }
64
+ replace(replacements) {
65
+ const next = [];
66
+ let sourceIndex = 0;
67
+ for (const { start, oldLength, newLines } of [...replacements].sort((left, right) => left.start - right.start)) {
68
+ next.push(...this.lines.slice(sourceIndex, start));
69
+ next.push(...newLines.map((text) => ({ text, ending: this.preferredEnding })));
70
+ sourceIndex = start + oldLength;
71
+ }
72
+ next.push(...this.lines.slice(sourceIndex));
73
+ return next.map((line) => line.text + (line.ending ?? this.preferredEnding)).join("");
74
+ }
75
+ }
76
+ //# sourceMappingURL=line-endings.js.map
@@ -1,18 +1,13 @@
1
- import { normalizePatchText, stripHeredoc } from "./text.js";
1
+ import { normalizePatchText, parseFileHeader, parseMoveTo, stripHeredoc } from "./text.js";
2
2
  const BEGIN_PATCH_MARKER = "*** Begin Patch";
3
3
  const END_PATCH_MARKER = "*** End Patch";
4
- const ADD_FILE_MARKER = "*** Add File: ";
5
- const DELETE_FILE_MARKER = "*** Delete File: ";
6
- const UPDATE_FILE_MARKER = "*** Update File: ";
7
- const MOVE_TO_MARKER = "*** Move to: ";
8
4
  const EOF_MARKER = "*** End of File";
9
- function parseAddHunk(lines, index, endIndex) {
10
- const filePath = (lines[index] ?? "").slice(ADD_FILE_MARKER.length);
5
+ function parseAddHunk(lines, filePath, index, endIndex) {
11
6
  const contentLines = [];
12
7
  let nextIndex = index + 1;
13
8
  while (nextIndex < endIndex) {
14
9
  const nextLine = lines[nextIndex] ?? "";
15
- if (nextLine.startsWith("*** "))
10
+ if (nextLine.trim().startsWith("*** "))
16
11
  break;
17
12
  if (!nextLine.startsWith("+"))
18
13
  throw new Error("Invalid patch format: Add File lines must start with '+'");
@@ -43,6 +38,7 @@ function collectChangeContexts(lines, index, endIndex) {
43
38
  function parseChunkLines(lines, index, endIndex) {
44
39
  const oldLines = [];
45
40
  const newLines = [];
41
+ const contextLineIndices = [];
46
42
  let isEndOfFile = false;
47
43
  let parsedLines = 0;
48
44
  let nextIndex = index;
@@ -60,10 +56,12 @@ function parseChunkLines(lines, index, endIndex) {
60
56
  const prefix = hunkLine[0];
61
57
  const value = hunkLine.slice(1);
62
58
  if (prefix === undefined) {
59
+ contextLineIndices.push([oldLines.length, newLines.length]);
63
60
  oldLines.push("");
64
61
  newLines.push("");
65
62
  }
66
63
  else if (prefix === " ") {
64
+ contextLineIndices.push([oldLines.length, newLines.length]);
67
65
  oldLines.push(value);
68
66
  newLines.push(value);
69
67
  }
@@ -84,16 +82,13 @@ function parseChunkLines(lines, index, endIndex) {
84
82
  }
85
83
  if (parsedLines === 0)
86
84
  throw new Error("Update hunk does not contain any lines");
87
- return [{ oldLines, newLines, isEndOfFile }, nextIndex];
85
+ return [{ oldLines, newLines, contextLineIndices, isEndOfFile }, nextIndex];
88
86
  }
89
- function parseUpdateHunk(lines, index, endIndex) {
90
- const filePath = (lines[index] ?? "").slice(UPDATE_FILE_MARKER.length);
87
+ function parseUpdateHunk(lines, filePath, index, endIndex) {
91
88
  let nextIndex = index + 1;
92
- let movePath;
93
- if ((lines[nextIndex] ?? "").startsWith(MOVE_TO_MARKER)) {
94
- movePath = (lines[nextIndex] ?? "").slice(MOVE_TO_MARKER.length);
89
+ const movePath = parseMoveTo(lines[nextIndex] ?? "");
90
+ if (movePath !== undefined)
95
91
  nextIndex++;
96
- }
97
92
  const chunks = [];
98
93
  while (nextIndex < endIndex) {
99
94
  const nextLine = lines[nextIndex] ?? "";
@@ -128,24 +123,27 @@ export function parsePatch(patchText) {
128
123
  const hunks = [];
129
124
  let index = 1;
130
125
  while (index < endIndex) {
131
- const line = lines[index] ?? "";
132
- if (!line.startsWith("*** ")) {
126
+ // Like Codex, headers are recognized after trimming and any other non-blank line between file sections
127
+ // is rejected below; skipping it would silently drop the section it introduces.
128
+ const line = (lines[index] ?? "").trim();
129
+ if (line === "") {
133
130
  index++;
134
131
  continue;
135
132
  }
136
- if (line.startsWith(ADD_FILE_MARKER)) {
137
- const [hunk, nextIndex] = parseAddHunk(lines, index, endIndex);
133
+ const header = parseFileHeader(line);
134
+ if (header?.kind === "add") {
135
+ const [hunk, nextIndex] = parseAddHunk(lines, header.path, index, endIndex);
138
136
  hunks.push(hunk);
139
137
  index = nextIndex;
140
138
  continue;
141
139
  }
142
- if (line.startsWith(DELETE_FILE_MARKER)) {
143
- hunks.push({ type: "delete", filePath: line.slice(DELETE_FILE_MARKER.length) });
140
+ if (header?.kind === "delete") {
141
+ hunks.push({ type: "delete", filePath: header.path });
144
142
  index++;
145
143
  continue;
146
144
  }
147
- if (line.startsWith(UPDATE_FILE_MARKER)) {
148
- const [hunk, nextIndex] = parseUpdateHunk(lines, index, endIndex);
145
+ if (header?.kind === "update") {
146
+ const [hunk, nextIndex] = parseUpdateHunk(lines, header.path, index, endIndex);
149
147
  hunks.push(hunk);
150
148
  index = nextIndex;
151
149
  continue;