@code-yeongyu/senpi 2026.10.10-3 → 2026.10.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 (83) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/bundle/chunks/{app-server-command-DVWM37GF.js → app-server-command-6FTH3TK6.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-H4UIUFU5.js → chunk-2PUAD5TD.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-MT2C4I5R.js → chunk-2UUTN6QT.js} +105 -104
  5. package/dist/bundle/chunks/{chunk-3A3C5VVO.js → chunk-3OGEJMZ7.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-J5MUMVWB.js → chunk-64ZVBCTL.js} +8 -7
  7. package/dist/bundle/chunks/chunk-TIMLYJMK.js +14 -0
  8. package/dist/bundle/chunks/{chunk-Z7MMKKIY.js → chunk-TZVDXVHB.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-7GVD54RM.js → chunk-U3IL5N76.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-H67EVDWG.js → chunk-URQSNRHZ.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-M2IHGL3M.js → chunk-VW74BGIC.js} +1 -1
  12. package/dist/bundle/chunks/chunk-YG5UO3E4.js +7 -0
  13. package/dist/bundle/chunks/{chunk-CTERKXVZ.js → chunk-ZSYRWQWG.js} +2 -2
  14. package/dist/bundle/chunks/{cli-main-B4S4DGBX.js → cli-main-UYTUBG64.js} +1 -1
  15. package/dist/bundle/chunks/{host-command-VATE7HRG.js → host-command-TOVYSHYH.js} +1 -1
  16. package/dist/bundle/chunks/{host-lifecycle-GC3GIR2N.js → host-lifecycle-5AV4JXDQ.js} +1 -1
  17. package/dist/bundle/chunks/{interactive-mode-QOFA64JL.js → interactive-mode-KJIOCRS7.js} +1 -1
  18. package/dist/bundle/chunks/{list-tips-IIRFXBTO.js → list-tips-BXAA4FG5.js} +1 -1
  19. package/dist/bundle/chunks/{multi-session-host-E5RDPWQN.js → multi-session-host-TEFLJTTA.js} +5 -5
  20. package/dist/bundle/chunks/{package-manager-cli-YGTWXRG5.js → package-manager-cli-QSJSIHUR.js} +1 -1
  21. package/dist/bundle/chunks/{rpc-mode-HDAGQ4X3.js → rpc-mode-RUKK7VBF.js} +1 -1
  22. package/dist/bundle/chunks/{schedule-command-EQ4PQCRP.js → schedule-command-K6CTAB4T.js} +1 -1
  23. package/dist/bundle/chunks/session-control-endpoint-GZDV2FOZ.js +3 -0
  24. package/dist/bundle/chunks/{session-picker-O7OESJWU.js → session-picker-6D4LC3KR.js} +1 -1
  25. package/dist/bundle/chunks/session-worker.js +178 -176
  26. package/dist/bundle/cli.js +1 -1
  27. package/dist/bundle/index.js +1 -1
  28. package/dist/bundle/rpc-entry.js +1 -1
  29. package/dist/bundle/runtime-manifest.json +1 -1
  30. package/dist/core/agent-session-runtime.d.ts +6 -0
  31. package/dist/core/agent-session-runtime.js +18 -0
  32. package/dist/core/agent-session.js +5 -2
  33. package/dist/core/extensions/builtin/html-render/bootstrap.d.ts +15 -0
  34. package/dist/core/extensions/builtin/html-render/bootstrap.js +123 -0
  35. package/dist/core/extensions/builtin/html-render/images.d.ts +16 -0
  36. package/dist/core/extensions/builtin/html-render/images.js +155 -0
  37. package/dist/core/extensions/builtin/html-render/index.d.ts +3 -0
  38. package/dist/core/extensions/builtin/html-render/index.js +5 -0
  39. package/dist/core/extensions/builtin/html-render/tool.d.ts +19 -0
  40. package/dist/core/extensions/builtin/html-render/tool.js +74 -0
  41. package/dist/core/extensions/builtin/index.js +4 -0
  42. package/dist/core/extensions/builtin/permission-system/index.js +40 -14
  43. package/dist/core/extensions/session-control-types.d.ts +25 -0
  44. package/dist/core/extensions/session-control-types.js +16 -0
  45. package/dist/core/external-admission.js +7 -1
  46. package/dist/core/resource-loader.js +63 -2
  47. package/dist/core/session-rebind.js +16 -1
  48. package/dist/index.d.ts +1 -1
  49. package/dist/index.js +1 -1
  50. package/dist/modes/interactive/components/extension-editor.js +4 -0
  51. package/dist/modes/interactive/components/remote-delivery-message.d.ts +6 -3
  52. package/dist/modes/interactive/components/remote-delivery-message.js +32 -3
  53. package/dist/modes/interactive/interactive-mode.d.ts +17 -0
  54. package/dist/modes/interactive/interactive-mode.js +79 -33
  55. package/dist/modes/interactive/interactive-stderr-guard.d.ts +8 -0
  56. package/dist/modes/interactive/interactive-stderr-guard.js +70 -0
  57. package/dist/modes/interactive/session-control-commands.d.ts +2 -1
  58. package/dist/modes/interactive/session-control-commands.js +21 -7
  59. package/dist/modes/interactive/session-control-session-commands.d.ts +22 -0
  60. package/dist/modes/interactive/session-control-session-commands.js +47 -0
  61. package/dist/modes/interactive/stdout-fd-redirect.d.ts +12 -0
  62. package/dist/modes/interactive/stdout-fd-redirect.js +114 -0
  63. package/dist/modes/rpc/connection-handler.js +6 -15
  64. package/dist/modes/rpc/host-reservations.d.ts +1 -1
  65. package/dist/modes/rpc/host-reservations.js +9 -3
  66. package/dist/modes/rpc/rpc-types.d.ts +13 -0
  67. package/dist/modes/rpc/session-control-actions-data.d.ts +17 -0
  68. package/dist/modes/rpc/session-control-actions-data.js +38 -0
  69. package/dist/modes/rpc/session-registry-attach.js +8 -2
  70. package/dist/modes/rpc/session-registry.js +5 -7
  71. package/dist/modes/rpc/session-teardown.d.ts +6 -1
  72. package/dist/modes/rpc/session-teardown.js +26 -7
  73. package/dist/modes/rpc/session-worker-client.d.ts +2 -0
  74. package/dist/modes/rpc/session-worker-client.js +6 -0
  75. package/dist/modes/rpc/session-worker-protocol.d.ts +4 -0
  76. package/dist/modes/rpc/session-worker.js +6 -0
  77. package/dist/modes/rpc/worker-session-registry.js +6 -1
  78. package/docs/extensions.md +1 -1
  79. package/docs/rpc.md +52 -8
  80. package/package.json +6 -6
  81. package/dist/bundle/chunks/chunk-PDSG6VER.js +0 -14
  82. package/dist/bundle/chunks/chunk-RADHRQ4K.js +0 -7
  83. package/dist/bundle/chunks/session-control-endpoint-NABTZHCZ.js +0 -3
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
3
  import{enableStartupCompileCache}from"./chunks/chunk-F73COJ7R.js";import{getLatestPiRelease,hasInheritedInspectorOption,isNewerPackageVersion,processBunRuntimeOptions,releaseInheritedInspectorForChild,resolveBunReexec}from"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync2,realpathSync as realpathSync3}from"node:fs";import{dirname as dirname3,join as join5}from"node:path";import{fileURLToPath}from"node:url";import{createHash}from"node:crypto";import{readFileSync as readFileSync3,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname2,join as join3,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync,mkdirSync,readdirSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";import{constants}from"node:fs";import{copyFile,link}from"node:fs/promises";function errorCode(error){return error instanceof Error&&"code"in error?error.code:void 0}var FILE_OPERATIONS={copyFile,link},COPY_CONCURRENCY=8;function nextCopyMode(mode,error,platform){let code=errorCode(error);if(!(code==="ENOENT"||code==="ENOTDIR"||code==="EEXIST"))switch(mode){case"clone":return platform==="darwin"&&code==="ENOSYS"?"clone-or-copy":"link";case"link":return"copy";case"clone-or-copy":case"copy":return}}function createSnapshotFileCopier(platform=process.platform,operations=FILE_OPERATIONS){let mode="clone",attempt=(current,source,target)=>{switch(current){case"clone":return operations.copyFile(source,target,constants.COPYFILE_FICLONE_FORCE);case"clone-or-copy":return operations.copyFile(source,target,constants.COPYFILE_FICLONE);case"link":return operations.link(source,target);case"copy":return operations.copyFile(source,target,0)}};return{get mode(){return mode},async copy(source,target){for(let current=mode;;)try{await attempt(current,source,target);return}catch(error){let next=nextCopyMode(current,error,platform);if(next===void 0)throw error;current=next,mode=next}}}}async function copyFiles(pairs,copier){let next=0,worker=async()=>{for(let index=next++;index<pairs.length;index=next++){let[source,target]=pairs[index]??[];source!==void 0&&target!==void 0&&await copier.copy(source,target)}};await Promise.all(Array.from({length:Math.min(COPY_CONCURRENCY,pairs.length)},worker))}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-",UNLOADED_FILE=/\.(?:d\.[cm]?ts|map)$/;function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function planTree(source,target,files,skipModules,seen=new Set){let real=realpathSync(source);if(!seen.has(real)){seen.add(real),mkdirSync(target,{recursive:!0});for(let entry of readdirSync(real,{withFileTypes:!0})){if(skipModules&&entry.name==="node_modules")continue;let from=join(real,entry.name),to=join(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen);else if(entry.isFile())UNLOADED_FILE.test(entry.name)||files.push([from,to]);else if(entry.isSymbolicLink()){let isDirectory;try{isDirectory=statSync(from).isDirectory()}catch(error){if(isMissing(error))continue;throw error}isDirectory?planTree(from,to,files,skipModules,seen):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname(current)){if(basename(current)!=="node_modules"){let candidate=join(current,"node_modules");existsSync(candidate)&&directories.push(candidate)}if(dirname(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join(modules,packageName);if(existsSync(join(root,"package.json")))return realpathSync(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return[];let names=new Set;for(let field of["dependencies","optionalDependencies","peerDependencies"]){let block=manifest[field];if(typeof block=="object"&&block!==null)for(let name of Object.keys(block))names.add(name)}return[...names]}function closureNames(packageDir,extra){let names=new Set(extra),visited=new Set,pending=[realpathSync(packageDir)];for(let dir=pending.pop();dir!==void 0;dir=pending.pop())if(!visited.has(dir)){visited.add(dir);for(let name of dependencyNames(dir)){names.add(name);let root=packageRootFrom(dir,name);root!==void 0&&!visited.has(root)&&pending.push(root)}}return names}function planModules(packageDir,snapshotRoot,externals,files){let self=realpathSync(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join(snapshotRoot,"node_modules",name))}for(let next=pending.shift();next!==void 0;next=pending.shift())for(let name of dependencyNames(next.installDir)){let expected=packageRootFrom(next.installDir,name);expected===void 0||expected===self||resolvePlaced(next.snapshotDir,name)!==expected&&place(expected,join(next.snapshotDir,"node_modules",name))}return placed}function verifyExternals(packageDir,snapshotBundleDir,externals,placed){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected===void 0)continue;let found=moduleDirectoriesFrom(snapshotBundleDir).map(modules=>join(modules,name)).find(root=>existsSync(join(root,"package.json")));if(found===void 0||placed.get(found)!==expected)throw new RuntimeSnapshotLayoutError(name)}}async function materializeRuntimeSnapshot(packageDir,target,manifest,copier=createSnapshotFileCopier()){let staging=join(dirname(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planTree(packageDir,staging,files,!0);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync(packageDir)};writeFileSync(join(staging,RUNTIME_SNAPSHOT_MARKER),`${JSON.stringify(marker)}
4
- `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync2,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync2(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync2(root,{recursive:!0});let lock=join2(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync2(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync2(join2(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync2(root,{recursive:!0});let lock=join2(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync2(lock),writeFileSync2(join2(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync2(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join2(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync2(join2(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join2(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join2(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync2(join2(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join2(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join2(root,keep),isAlive);for(let name of readdirSync2(root)){if(name===LOCK_NAME||name===keep)continue;let path=join2(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join2(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join2(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync3(join3(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname2(entryPath),runtimeRoot=join3(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join3("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync2(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join3(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join3(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync4}from"node:fs";import{join as join4}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync4(join4(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}async function handleBootstrapSelfUpdate(args2,dependencies={}){let parsed=parseBootstrapSelfUpdateArgs(args2);if(!parsed)return!1;let writeStdout=dependencies.writeStdout??(line=>console.log(line)),writeStderr=dependencies.writeStderr??(line=>console.error(line)),readNpmCommand=dependencies.readNpmCommand??readConfiguredNpmCommand,resolveSelfUpdateCommand=dependencies.getSelfUpdateCommand??getSelfUpdateCommand,resolveUnavailableInstruction=dependencies.getUnavailableInstruction??getSelfUpdateUnavailableInstruction,executeCommand=dependencies.runCommand??runCommand,brandUpdate=brandProfile()?.update;if(brandUpdate)return writeStdout(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with: ${brandUpdate.command}`),!0;let loadLatestRelease=dependencies.getLatestRelease??getLatestPiRelease,latestRelease;if(!parsed.force)try{latestRelease=await loadLatestRelease(VERSION)}catch{latestRelease=void 0}let updatePackageName=latestRelease?.packageName??PACKAGE_NAME;if(!(parsed.force||!latestRelease||updatePackageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)))return writeStdout(`${APP_NAME} is already up to date (v${VERSION})`),!0;let npmCommand=readNpmCommand(),selfUpdateCommand=resolveSelfUpdateCommand(PACKAGE_NAME,npmCommand,updatePackageName);if(!selfUpdateCommand)return writeStderr(`error: ${APP_NAME} cannot self-update this installation.`),writeStderr(resolveUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageName)),process.argv[1]&&(writeStderr(""),writeStderr(`Location of ${APP_NAME} executable: ${process.argv[1]}`)),process.exitCode=1,!0;latestRelease?.note?.trim()&&(writeStdout(""),writeStdout("Update note"),writeStdout(latestRelease.note.trim()),writeStdout("")),writeStdout(`Updating ${APP_NAME} with ${selfUpdateCommand.display}...`);for(let step of selfUpdateCommand.steps??[selfUpdateCommand])try{await executeCommand(step)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return writeStderr(`Error: ${message}`),writeStderr(`If this keeps failing, run this command yourself: ${selfUpdateCommand.display}`),process.exitCode=1,!0}return writeStdout(`Updated ${APP_NAME}`),!0}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path};function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync2,realpathSync3),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync3(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let result=spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],{stdio:"inherit",windowsHide:!0});return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}reexecUnderBunIfNeeded()&&process.exit();enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var args=process.argv.slice(2),PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync2(join5(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawn2(process.execPath,[...process.execArgv,fullCliPath,...args],{env:childEnvironment,stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&(console.log(DISPLAY_VERSION),process.exit());if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-EHRZEBRO.js");tryPrintHelpWithoutEngine(args)&&process.exit()}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-B4S4DGBX.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-EHRZEBRO.js");tryPrintHelpWithoutEngine(args)&&process.exit()}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname3(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-UYTUBG64.js")}
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-MT2C4I5R.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-PDSG6VER.js";import"./chunks/chunk-QNAG7FYM.js";import{CURRENT_SESSION_VERSION,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionManager,SessionSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,keyHint,keyText,migrateSessionEntries,parseSessionEntries,rawKeyHint,sessionEntryToContextMessages}from"./chunks/chunk-Z7MMKKIY.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-H4UIUFU5.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-M2IHGL3M.js";import{sanitizeTerminalLabel}from"./chunks/chunk-J5MUMVWB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-CTERKXVZ.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-7GVD54RM.js";import"./chunks/chunk-IZOTKUWG.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-H67EVDWG.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-4TK7VCZZ.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3A3C5VVO.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-RADHRQ4K.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-RRU5LXMS.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ODYQK5XJ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionRunner,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,prepareBranchEntries,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-2UUTN6QT.js";import{UnknownCommandError,readOwnFootprint,readProcessFootprint,runRpcMode}from"./chunks/chunk-TIMLYJMK.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-TZVDXVHB.js";import{SettingsManager,Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,parseSkillBlock}from"./chunks/chunk-2PUAD5TD.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-VW74BGIC.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-64ZVBCTL.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-ZSYRWQWG.js";import"./chunks/chunk-JABBHOD5.js";import{DEFAULT_HOST_LAUNCH_SPEC,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,REQUIRED_HOST_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,decideHostAction,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,parseHostProtocolInfo,probeHost,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest,stopHost}from"./chunks/chunk-U3IL5N76.js";import"./chunks/chunk-IZOTKUWG.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{gcHostEndpoints,listHostEndpoints}from"./chunks/chunk-URQSNRHZ.js";import{compareEngineOrdinal,engineBuildIdentity,engineBuildIdentityFrom}from"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-4TK7VCZZ.js";import"./chunks/chunk-F6EQ7EV3.js";import{getPowerShellConfig,getShellConfig,withBundledBunCommands}from"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3OGEJMZ7.js";import"./chunks/chunk-CIRZTP7W.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-YG5UO3E4.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-RRU5LXMS.js";import{parseArgs}from"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ODYQK5XJ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_HOST_LAUNCH_SPEC,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ENDPOINT_REGISTRY_VERSION,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,GENERATION_HANDOFF_CAPABILITY,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,HostLaunchSpecError,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,REQUIRED_HOST_CAPABILITIES,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readOwnFootprint,readProcessFootprint,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionControlSenderOf,sessionEntryToContextMessages,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{main}from"./chunks/chunk-MT2C4I5R.js";import"./chunks/chunk-PDSG6VER.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-Z7MMKKIY.js";import{configureHttpDispatcher}from"./chunks/chunk-H4UIUFU5.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-M2IHGL3M.js";import"./chunks/chunk-J5MUMVWB.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-CTERKXVZ.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-7GVD54RM.js";import"./chunks/chunk-IZOTKUWG.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-H67EVDWG.js";import"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-4TK7VCZZ.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3A3C5VVO.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-RADHRQ4K.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import"./chunks/chunk-RRU5LXMS.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ODYQK5XJ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{main}from"./chunks/chunk-2UUTN6QT.js";import"./chunks/chunk-TIMLYJMK.js";import"./chunks/chunk-QNAG7FYM.js";import"./chunks/chunk-TZVDXVHB.js";import{configureHttpDispatcher}from"./chunks/chunk-2PUAD5TD.js";import"./chunks/chunk-LYYI74CY.js";import"./chunks/chunk-VW74BGIC.js";import"./chunks/chunk-64ZVBCTL.js";import"./chunks/chunk-WIAXG52U.js";import"./chunks/chunk-U5KVIAHJ.js";import"./chunks/chunk-ZSYRWQWG.js";import"./chunks/chunk-JABBHOD5.js";import"./chunks/chunk-U3IL5N76.js";import"./chunks/chunk-IZOTKUWG.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-URQSNRHZ.js";import"./chunks/chunk-ZJHRDQCH.js";import"./chunks/chunk-UWYQPA26.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-4TK7VCZZ.js";import"./chunks/chunk-F6EQ7EV3.js";import"./chunks/chunk-JEZWV7JW.js";import"./chunks/chunk-S2TCHQTE.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-3OGEJMZ7.js";import"./chunks/chunk-CIRZTP7W.js";import"./chunks/chunk-YG5UO3E4.js";import"./chunks/chunk-YI7SPFDN.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-UMJL74VN.js";import"./chunks/chunk-RRU5LXMS.js";import"./chunks/chunk-MH2BFYGN.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-ODYQK5XJ.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-2VZJTDUX.js";import"./chunks/chunk-KC5TT7DH.js";import"./chunks/chunk-KEMQXWPY.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-463OK2Y4.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-RBCQOIAD.js";import"./chunks/chunk-JRGNL6WM.js";import"./chunks/chunk-RKJNJ3GI.js";import"./chunks/chunk-CWLCGRUS.js";import"./chunks/chunk-6WCOSBI7.js";import"./chunks/chunk-I5HLTDT4.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-YOPVJDSU.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-2WEI2XTZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-45SZOLCU.js";import"./chunks/chunk-TAV6QZFM.js";import"./chunks/chunk-PELNNWGO.js";import"./chunks/chunk-XL5KIYQF.js";import"./chunks/chunk-DMI55M2N.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-IKOFCODM.js";process.title=`${APP_NAME}-rpc`;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -1 +1 @@
1
- {"buildId":"aac3c6d54633f2c9","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"b60c27e14c9e0184","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
@@ -112,6 +112,12 @@ export declare class AgentSessionRuntime {
112
112
  setPromptSurface(surface: PromptSurface): void;
113
113
  /** Moves this session to another browser engine; later replacements (switch, new, fork) keep it. */
114
114
  setBrowserEngine(engine: BrowserEngine): void;
115
+ /**
116
+ * Moves this session to another permission preset (a later `open_session.permissionPreset`): the
117
+ * permission extension enforces it from the next tool call, and later replacements (switch, new,
118
+ * fork) keep it.
119
+ */
120
+ setPermissionPreset(preset: string): void;
115
121
  /**
116
122
  * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements
117
123
  * (switch, new, fork) keep it. Callers set it before the first turn: a chain never changes under a
@@ -85,6 +85,15 @@ export class AgentSessionRuntime {
85
85
  this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), browserEngine: engine });
86
86
  this._session.setBrowserEngine(engine);
87
87
  }
88
+ /**
89
+ * Moves this session to another permission preset (a later `open_session.permissionPreset`): the
90
+ * permission extension enforces it from the next tool call, and later replacements (switch, new,
91
+ * fork) keep it.
92
+ */
93
+ setPermissionPreset(preset) {
94
+ this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), permissionPreset: preset });
95
+ this._session.extensionRunner.setFlagValue("permission-preset", preset);
96
+ }
88
97
  /**
89
98
  * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements
90
99
  * (switch, new, fork) keep it. Callers set it before the first turn: a chain never changes under a
@@ -193,6 +202,15 @@ export class AgentSessionRuntime {
193
202
  async apply(result, hold) {
194
203
  this._sessionHold = hold ?? holdActiveSession(result.session.sessionManager, false);
195
204
  this._session = result.session;
205
+ // The replacement was built from the profile read before its runtime was created; an attach
206
+ // that moved a setting while it was being built reached only the retired session (senpi#2842).
207
+ const profile = this._launchProfile;
208
+ if (profile?.permissionPreset !== undefined)
209
+ this._session.extensionRunner.setFlagValue("permission-preset", profile.permissionPreset);
210
+ if (profile?.promptSurface !== undefined)
211
+ this._session.setPromptSurface(profile.promptSurface);
212
+ if (profile?.browserEngine !== undefined)
213
+ this._session.setBrowserEngine(profile.browserEngine);
196
214
  this._services = result.services;
197
215
  this._diagnostics = result.diagnostics;
198
216
  this._modelFallbackMessage = result.modelFallbackMessage;
@@ -7593,7 +7593,6 @@ export class AgentSession {
7593
7593
  resetTimings("reload");
7594
7594
  const oldExtensionRunner = this._extensionRunner;
7595
7595
  const oldExtensionIdentities = oldExtensionRunner.getExtensionIdentities();
7596
- const previousFlagValues = oldExtensionRunner.getFlagValues();
7597
7596
  const previousActiveToolRegistrationIds = new Map();
7598
7597
  // Cover withheld eval-only tools too: the rebuild drops any seeded name missing from this
7599
7598
  // map, which would strand eval-only tools when the policy disarms during this reload.
@@ -7650,7 +7649,11 @@ export class AgentSession {
7650
7649
  try {
7651
7650
  this._buildRuntime({
7652
7651
  activeToolNames: requestedActiveToolNamesBeforeRebuild,
7653
- flagValues: previousFlagValues,
7652
+ // Read from the CURRENT runner at the swap, not before the awaits above and not from the
7653
+ // runner this reload started with: a flag set while this reload ran (an attach moving the
7654
+ // session's permission preset) carries over, also when an overlapping reload installed
7655
+ // another runner in the meantime and the attach wrote that one (senpi#2842).
7656
+ flagValues: this._extensionRunner.getFlagValues(),
7654
7657
  includeAllExtensionTools: true,
7655
7658
  previousActiveToolRegistrationIds,
7656
7659
  addedToolNames: addedDefaultTools,
@@ -0,0 +1,15 @@
1
+ /**
2
+ * A page is a static snapshot: everything it shows is in the document (inline,
3
+ * data: or blob:), and it reaches no network. Its scripts run whenever it
4
+ * opens, but fetch, XHR, WebSocket, EventSource, remote scripts, styles,
5
+ * images and fonts, frames, form posts and <base> are refused. The policy is
6
+ * the document's first element, so nothing the page writes loads before it.
7
+ * Mirrors the desktop's packages/shared/src/htmlRenderBootstrap.ts.
8
+ */
9
+ export declare const HTML_RENDER_CONTENT_SECURITY_POLICY: string;
10
+ /**
11
+ * Inserts the theme bootstrap at the start of the document head, and the
12
+ * snapshot policy ahead of everything the page wrote.
13
+ */
14
+ export declare function injectHtmlRenderBootstrap(html: string): string;
15
+ //# sourceMappingURL=bootstrap.d.ts.map
@@ -0,0 +1,123 @@
1
+ // The theme bootstrap injection and base stylesheet, mirroring the desktop's
2
+ // packages/shared/src/htmlRender.ts (upstream t3code #15968). Kept small and
3
+ // dependency-light: pure string functions, no Effect, no server. A page the
4
+ // agent writes here is the same shape the desktop stores on publish.
5
+ const BASE_CSS = "html{background:var(--background);color:var(--foreground);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;scrollbar-width:none}" +
6
+ "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}";
7
+ const DARK_VARS = {
8
+ "--background": "#0a0a0a",
9
+ "--foreground": "#f5f5f5",
10
+ "--muted-foreground": "#818181",
11
+ "--chart-1": "#60a5fa",
12
+ "--font-sans": '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
13
+ "--font-mono": '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
14
+ "--radius": "0.625rem",
15
+ };
16
+ const LIGHT_VARS = {
17
+ ...DARK_VARS,
18
+ "--background": "#ffffff",
19
+ "--foreground": "#0a0a0a",
20
+ "--muted-foreground": "#525252",
21
+ "--chart-1": "#1d4ed8",
22
+ };
23
+ function rootRule(appearance, variables) {
24
+ const declarations = Object.entries(variables)
25
+ .map(([name, value]) => `${name}:${value};`)
26
+ .join("");
27
+ return `:root{color-scheme:${appearance};${declarations}}`;
28
+ }
29
+ const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme");if(!s)return;var b=${JSON.stringify(BASE_CSS)};try{var m=window.matchMedia("(prefers-color-scheme: light)");var a=function(){s.textContent=m.matches?${JSON.stringify(rootRule("light", LIGHT_VARS))}:${JSON.stringify(rootRule("dark", DARK_VARS))}+b;};a();if(m.addEventListener)m.addEventListener("change",a);}catch(e){}})();`;
30
+ function bootstrapMarkup(markup) {
31
+ const defaultCss = `${rootRule("dark", DARK_VARS)}@media (prefers-color-scheme: light){${rootRule("light", LIGHT_VARS)}}${BASE_CSS}`;
32
+ return [
33
+ /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
34
+ /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
35
+ ? ""
36
+ : '<meta name="viewport" content="width=device-width, initial-scale=1">',
37
+ `<style id="t3-theme">${defaultCss}</style>`,
38
+ `<script>${BOOTSTRAP_SCRIPT}</script>`,
39
+ ].join("");
40
+ }
41
+ const blankNonMarkup = (html) => {
42
+ const scan = html.replace(/<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi, (match) => " ".repeat(match.length));
43
+ const parts = [];
44
+ let depth = 0;
45
+ let start = 0;
46
+ let at = 0;
47
+ for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
48
+ if (!match[1]) {
49
+ if (depth++ === 0)
50
+ start = match.index;
51
+ }
52
+ else if (depth > 0 && --depth === 0) {
53
+ const end = match.index + match[0].length;
54
+ parts.push(scan.slice(at, start), " ".repeat(end - start));
55
+ at = end;
56
+ }
57
+ }
58
+ if (depth > 0) {
59
+ parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
60
+ at = scan.length;
61
+ }
62
+ parts.push(scan.slice(at));
63
+ return parts.join("");
64
+ };
65
+ /**
66
+ * A page is a static snapshot: everything it shows is in the document (inline,
67
+ * data: or blob:), and it reaches no network. Its scripts run whenever it
68
+ * opens, but fetch, XHR, WebSocket, EventSource, remote scripts, styles,
69
+ * images and fonts, frames, form posts and <base> are refused. The policy is
70
+ * the document's first element, so nothing the page writes loads before it.
71
+ * Mirrors the desktop's packages/shared/src/htmlRenderBootstrap.ts.
72
+ */
73
+ export const HTML_RENDER_CONTENT_SECURITY_POLICY = [
74
+ "default-src 'none'",
75
+ "script-src 'unsafe-inline' 'unsafe-eval' data: blob:",
76
+ "style-src 'unsafe-inline' data:",
77
+ "img-src data: blob:",
78
+ "font-src data:",
79
+ "media-src data: blob:",
80
+ "worker-src blob:",
81
+ "connect-src 'none'",
82
+ "frame-src 'none'",
83
+ "form-action 'none'",
84
+ "base-uri 'none'",
85
+ ].join("; ");
86
+ const POLICY_META = `<meta http-equiv="Content-Security-Policy" content="${HTML_RENDER_CONTENT_SECURITY_POLICY}">`;
87
+ // Every written page starts with a UTF-8 byte order mark, a standards-mode
88
+ // doctype and the policy, in that order and in plain ASCII. The mark makes the
89
+ // browser decode the file as UTF-8 whatever charset the page declares, so no
90
+ // declared encoding can turn the policy into text, and nothing the page wrote
91
+ // comes before it. A leading doctype of the page's own is dropped only when it is
92
+ // printable ASCII; anything else stays where it is, after the policy, where the
93
+ // parser ignores a doctype.
94
+ const PREAMBLE = `\uFEFF<!doctype html>${POLICY_META}`;
95
+ const LEADING_ASCII_DOCTYPE = /^\uFEFF?[\t\n\f\r ]*<!doctype[ -=?-~]*>/i;
96
+ /**
97
+ * Inserts the theme bootstrap at the start of the document head, and the
98
+ * snapshot policy ahead of everything the page wrote.
99
+ */
100
+ export function injectHtmlRenderBootstrap(html) {
101
+ return PREAMBLE + injectThemeBootstrap(html).replace(LEADING_ASCII_DOCTYPE, "");
102
+ }
103
+ function injectThemeBootstrap(html) {
104
+ const scan = blankNonMarkup(html);
105
+ const markup = bootstrapMarkup(scan);
106
+ const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
107
+ if (headOpen) {
108
+ const at = headOpen.index + headOpen[0].length;
109
+ return html.slice(0, at) + markup + html.slice(at);
110
+ }
111
+ const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
112
+ if (htmlOpen) {
113
+ const at = htmlOpen.index + htmlOpen[0].length;
114
+ return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
115
+ }
116
+ const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
117
+ if (doctype) {
118
+ const at = doctype[0].length;
119
+ return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
120
+ }
121
+ return `<!doctype html><head>${markup}</head>${html}`;
122
+ }
123
+ //# sourceMappingURL=bootstrap.js.map
@@ -0,0 +1,16 @@
1
+ export declare class HtmlRenderImagesNotFoundError extends Error {
2
+ readonly paths: readonly string[];
3
+ constructor(paths: readonly string[]);
4
+ }
5
+ export declare class HtmlRenderImageTooLargeError extends Error {
6
+ constructor(path: string, sizeBytes: number);
7
+ }
8
+ export declare class HtmlRenderPageTooLargeError extends Error {
9
+ constructor(sizeBytes: number);
10
+ }
11
+ /** Replaces every local image reference with a data URI; unreadable paths throw. */
12
+ export declare function inlineLocalImages(html: string): Promise<{
13
+ html: string;
14
+ missing: string[];
15
+ }>;
16
+ //# sourceMappingURL=images.d.ts.map
@@ -0,0 +1,155 @@
1
+ // Local-image preparation, mirroring the desktop's apps/server/src/htmlRender/
2
+ // HtmlRender.ts (upstream t3code #15968): absolute-path images are inlined as
3
+ // data URIs only after a magic-byte/SVG-root check, so a renamed secret is
4
+ // refused, and the page stays within the size caps. Pure byte/string work.
5
+ import { readFile, stat } from "node:fs/promises";
6
+ const MIB = 1024 * 1024;
7
+ const MAX_IMAGE_BYTES = 10 * MIB;
8
+ const MAX_PAGE_BYTES = 25 * MIB;
9
+ export class HtmlRenderImagesNotFoundError extends Error {
10
+ constructor(paths) {
11
+ super(`These local images could not be read: ${paths.join(", ")}. Use absolute paths to existing image files, or remove them.`);
12
+ this.name = "HtmlRenderImagesNotFoundError";
13
+ this.paths = paths;
14
+ }
15
+ }
16
+ export class HtmlRenderImageTooLargeError extends Error {
17
+ constructor(path, sizeBytes) {
18
+ super(`${path} is ${(sizeBytes / MIB).toFixed(1)} MiB; each local image must be at most 10 MiB.`);
19
+ this.name = "HtmlRenderImageTooLargeError";
20
+ }
21
+ }
22
+ export class HtmlRenderPageTooLargeError extends Error {
23
+ constructor(sizeBytes) {
24
+ super(`With its images inlined the page is ${(sizeBytes / MIB).toFixed(1)} MiB; the limit is 25 MiB. Use smaller images.`);
25
+ this.name = "HtmlRenderPageTooLargeError";
26
+ }
27
+ }
28
+ const IMAGE_MIME_TYPES = {
29
+ png: "image/png",
30
+ jpg: "image/jpeg",
31
+ jpeg: "image/jpeg",
32
+ gif: "image/gif",
33
+ webp: "image/webp",
34
+ avif: "image/avif",
35
+ svg: "image/svg+xml",
36
+ bmp: "image/bmp",
37
+ ico: "image/x-icon",
38
+ };
39
+ const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES).join("|");
40
+ const ABSOLUTE_PATH = String.raw `(?:/(?!/)|[a-z]:[\\/])`;
41
+ const LOCAL_IMAGE_PATTERN = new RegExp(String.raw `(["'\x60])(${ABSOLUTE_PATH}(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))\1` +
42
+ String.raw `|url\(\s*(${ABSOLUTE_PATH}[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))\s*\)`, "gid");
43
+ const findLocalImages = (html) => Array.from(html.matchAll(LOCAL_IMAGE_PATTERN)).flatMap((match) => {
44
+ const span = match.indices?.[2] ?? match.indices?.[3];
45
+ return span ? [{ start: span[0], end: span[1], path: html.slice(span[0], span[1]) }] : [];
46
+ });
47
+ const filePathFor = (reference) => /^[a-z]:/i.test(reference) ? reference.replaceAll("\\\\", "\\") : reference;
48
+ const dataUriPrefix = (path) => `data:${IMAGE_MIME_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"};base64,`;
49
+ const latin1 = (bytes, start, end) => String.fromCharCode(...bytes.subarray(start, end));
50
+ const after = (text, token, from) => {
51
+ const at = text.indexOf(token, from);
52
+ return at === -1 ? -1 : at + token.length;
53
+ };
54
+ const afterDoctype = (text, from) => {
55
+ let inSubset = false;
56
+ let at = from;
57
+ while (at !== -1 && at < text.length) {
58
+ const char = text[at];
59
+ if (char === '"' || char === "'")
60
+ at = after(text, char, at + 1);
61
+ else if (inSubset && text.startsWith("<!--", at))
62
+ at = after(text, "-->", at + 4);
63
+ else if (inSubset && text.startsWith("<?", at))
64
+ at = after(text, "?>", at + 2);
65
+ else if (char === ">" && !inSubset)
66
+ return at + 1;
67
+ else {
68
+ if (char === "[")
69
+ inSubset = true;
70
+ else if (char === "]")
71
+ inSubset = false;
72
+ at += 1;
73
+ }
74
+ }
75
+ return -1;
76
+ };
77
+ const hasSvgRoot = (text) => {
78
+ let at = 0;
79
+ while (at !== -1) {
80
+ while (/\s/.test(text.charAt(at)))
81
+ at += 1;
82
+ if (text.startsWith("<?", at))
83
+ at = after(text, "?>", at + 2);
84
+ else if (text.startsWith("<!--", at))
85
+ at = after(text, "-->", at + 4);
86
+ else if (text.slice(at, at + 9).toLowerCase() === "<!doctype")
87
+ at = afterDoctype(text, at + 9);
88
+ else
89
+ return /^<svg[ \t\r\n/>]/.test(text.slice(at, at + 5));
90
+ }
91
+ return false;
92
+ };
93
+ /** Whether file bytes are an image, whatever the file is named. */
94
+ const isImageBytes = (bytes) => {
95
+ const head = latin1(bytes, 0, 12);
96
+ if (head.startsWith("\x89PNG") ||
97
+ head.startsWith("\xff\xd8\xff") ||
98
+ head.startsWith("GIF8") ||
99
+ head.startsWith("\0\0\x01\0") ||
100
+ (head.startsWith("BM") && head.slice(6, 10) === "\0\0\0\0") ||
101
+ (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") ||
102
+ /^ftyp(?:avif|avis|mif1)$/.test(head.slice(4, 12))) {
103
+ return true;
104
+ }
105
+ return hasSvgRoot(new TextDecoder().decode(bytes.subarray(0, 4096)));
106
+ };
107
+ /** Replaces every local image reference with a data URI; unreadable paths throw. */
108
+ export async function inlineLocalImages(html) {
109
+ const references = findLocalImages(html);
110
+ const uniquePaths = [...new Set(references.map((reference) => reference.path))];
111
+ const files = await Promise.all(uniquePaths.map(async (path) => {
112
+ try {
113
+ const info = await stat(filePathFor(path));
114
+ return { path, size: info.isFile() ? Number(info.size) : undefined };
115
+ }
116
+ catch {
117
+ return { path, size: undefined };
118
+ }
119
+ }));
120
+ const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
121
+ if (oversized?.size !== undefined) {
122
+ throw new HtmlRenderImageTooLargeError(oversized.path, oversized.size);
123
+ }
124
+ const images = new Map();
125
+ let readBytes = 0;
126
+ for (const file of files.filter((entry) => entry.size !== undefined)) {
127
+ const bytes = new Uint8Array(await readFile(filePathFor(file.path)));
128
+ if (!isImageBytes(bytes))
129
+ continue;
130
+ if (bytes.byteLength > MAX_IMAGE_BYTES) {
131
+ throw new HtmlRenderImageTooLargeError(file.path, bytes.byteLength);
132
+ }
133
+ readBytes += Math.ceil(bytes.byteLength / 3) * 4;
134
+ if (readBytes > MAX_PAGE_BYTES)
135
+ throw new HtmlRenderPageTooLargeError(readBytes);
136
+ images.set(file.path, bytes);
137
+ }
138
+ const parts = [];
139
+ let cursor = 0;
140
+ for (const reference of references) {
141
+ const bytes = images.get(reference.path);
142
+ if (bytes === undefined)
143
+ continue;
144
+ parts.push(html.slice(cursor, reference.start), dataUriPrefix(reference.path) + Buffer.from(bytes).toString("base64"));
145
+ cursor = reference.end;
146
+ }
147
+ parts.push(html.slice(cursor));
148
+ const inlined = parts.join("");
149
+ if (Buffer.byteLength(inlined) > MAX_PAGE_BYTES) {
150
+ throw new HtmlRenderPageTooLargeError(Buffer.byteLength(inlined));
151
+ }
152
+ const missing = files.filter((file) => !images.has(file.path)).map((file) => file.path);
153
+ return { html: inlined, missing };
154
+ }
155
+ //# sourceMappingURL=images.js.map
@@ -0,0 +1,3 @@
1
+ import type { ExtensionAPI } from "../../types.ts";
2
+ export default function htmlRenderExtension(pi: ExtensionAPI): void;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ import { showHtmlPageTool } from "./tool.js";
2
+ export default function htmlRenderExtension(pi) {
3
+ pi.registerTool(showHtmlPageTool);
4
+ }
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,19 @@
1
+ import { Type } from "typebox";
2
+ export interface ShowHtmlPageDetails {
3
+ path: string;
4
+ title: string;
5
+ height: number | undefined;
6
+ prepared: boolean;
7
+ missingImages?: string[];
8
+ /**
9
+ * The page as the agent wrote it, for a host that publishes it itself (the
10
+ * desktop renders it in the thread). Never part of the model-visible content.
11
+ */
12
+ html: string;
13
+ }
14
+ export declare const showHtmlPageTool: import("../../types.ts").ToolDefinition<Type.TObject<{
15
+ html: Type.TString;
16
+ title: Type.TString;
17
+ height: Type.TOptional<Type.TInteger>;
18
+ }>, ShowHtmlPageDetails, any> & import("../../types.ts").ToolDefinition<any, any, any>;
19
+ //# sourceMappingURL=tool.d.ts.map