@code-yeongyu/senpi 2026.11.10-1 → 2026.11.10-2

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 (129) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundle/chunks/{chunk-GPXZTSEX.js → chunk-2M54EAAY.js} +3 -3
  3. package/dist/bundle/chunks/{chunk-YPAQXRP3.js → chunk-47T6YMI2.js} +2 -2
  4. package/dist/bundle/chunks/{chunk-I5ASHSLZ.js → chunk-4JMGWVRH.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-HI5JSLG5.js → chunk-74IB3JPP.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-NH7SYIGN.js → chunk-DLPV4B3R.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-Y7Z7XPUF.js → chunk-DZQA5LVN.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-2CNSCMYC.js → chunk-E5O4SP5I.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-3IYWH6RO.js → chunk-IKJCA5SH.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-H33A33M4.js → chunk-M2VJVJMK.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-L6NRDUWJ.js → chunk-OF3XVGG4.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-THYEZBUG.js → chunk-Q4G5DECT.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-ARUV3US4.js → chunk-QATU6BBC.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-FAFIGBUD.js → chunk-TUEZNIBK.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-BELNOPAI.js → chunk-UOZDDYBN.js} +2 -2
  16. package/dist/bundle/chunks/{chunk-DBQBJTMF.js → chunk-VUY4BZDI.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-TGW4R7SI.js → chunk-XH24X5B2.js} +1 -1
  18. package/dist/bundle/chunks/chunk-XI6THO4F.js +2 -0
  19. package/dist/bundle/chunks/{chunk-X4XWAB3J.js → chunk-YCPURLPU.js} +38 -38
  20. package/dist/bundle/chunks/{chunk-LHEP3ACI.js → chunk-YNGEZBTP.js} +1 -1
  21. package/dist/bundle/chunks/{cli-main-VG3C2EXI.js → cli-main-Y6ALA5OI.js} +1 -1
  22. package/dist/bundle/chunks/{hand-entry-3LQKUTYS.js → hand-entry-IPDAIOGI.js} +1 -1
  23. package/dist/bundle/chunks/{host-command-CCASS7W4.js → host-command-2326GCUP.js} +1 -1
  24. package/dist/bundle/chunks/{host-lifecycle-WWC7HXQ6.js → host-lifecycle-TNHASSFJ.js} +1 -1
  25. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  26. package/dist/bundle/chunks/{host-session-command-YJB2FLKU.js → host-session-command-BZYBDOIE.js} +1 -1
  27. package/dist/bundle/chunks/{host-socket-request-DMYXC56U.js → host-socket-request-QN4Q2P5E.js} +1 -1
  28. package/dist/bundle/chunks/{interactive-mode-CUN3WMUF.js → interactive-mode-LBQB7DDR.js} +1 -1
  29. package/dist/bundle/chunks/{main-P7XRC2OI.js → main-FFRFP34W.js} +1 -1
  30. package/dist/bundle/chunks/{multi-session-host-244X3P6L.js → multi-session-host-NDIHHJ2L.js} +11 -8
  31. package/dist/bundle/chunks/{package-manager-cli-UVWJOQA3.js → package-manager-cli-XCPAMOYI.js} +1 -1
  32. package/dist/bundle/chunks/{rpc-mode-G4I3HHPB.js → rpc-mode-TKNZM4PZ.js} +1 -1
  33. package/dist/bundle/chunks/{rpc-monitor-source-C6VQ3BC4.js → rpc-monitor-source-PGTDSGWP.js} +1 -1
  34. package/dist/bundle/chunks/{run-attached-tui-R3RB5P7G.js → run-attached-tui-JDUKXDI2.js} +1 -1
  35. package/dist/bundle/chunks/{schedule-command-5FG2OKSR.js → schedule-command-HF2DHABB.js} +1 -1
  36. package/dist/bundle/chunks/{session-control-endpoint-XWCFLJYC.js → session-control-endpoint-A6R6W2JQ.js} +1 -1
  37. package/dist/bundle/chunks/{session-picker-2FZSNFS7.js → session-picker-GWA4S2PO.js} +1 -1
  38. package/dist/bundle/chunks/session-worker.js +119 -116
  39. package/dist/bundle/cli.js +2 -2
  40. package/dist/bundle/host-supervisor.js +1 -1
  41. package/dist/bundle/index.js +1 -1
  42. package/dist/bundle/rpc-entry.js +1 -1
  43. package/dist/bundle/runtime-manifest.json +1 -1
  44. package/dist/core/agent-session-runtime.d.ts +2 -0
  45. package/dist/core/agent-session-runtime.js +5 -0
  46. package/dist/core/agent-session.d.ts +1 -1
  47. package/dist/core/agent-session.js +30 -10
  48. package/dist/core/extensions/builtin/config-reload/change-groups.js +6 -2
  49. package/dist/core/extensions/builtin/mcp/auth/catalog-identity.js +32 -8
  50. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.d.ts +43 -0
  51. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.js +196 -0
  52. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +4 -17
  53. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +64 -75
  54. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.d.ts +1 -1
  55. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +25 -4
  56. package/dist/core/extensions/builtin/mcp/auth/oauth.js +10 -7
  57. package/dist/core/extensions/builtin/mcp/auth/token-store.d.ts +18 -0
  58. package/dist/core/extensions/builtin/mcp/auth/token-store.js +3 -0
  59. package/dist/core/extensions/builtin/mcp/catalog-cache.js +7 -6
  60. package/dist/core/extensions/builtin/mcp/catalog.js +3 -2
  61. package/dist/core/extensions/builtin/mcp/invocation.js +6 -0
  62. package/dist/core/extensions/builtin/mcp/service-register.js +16 -2
  63. package/dist/core/extensions/builtin/mcp/service-tools-changed.js +61 -54
  64. package/dist/core/extensions/builtin/mcp/startup-race.d.ts +2 -0
  65. package/dist/core/extensions/builtin/mcp/startup-race.js +25 -7
  66. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-2.js +6 -6
  67. package/dist/core/open-timing.d.ts +2 -0
  68. package/dist/core/open-timing.js +7 -1
  69. package/dist/core/session-manager.d.ts +2 -0
  70. package/dist/core/session-manager.js +15 -1
  71. package/dist/modes/interactive/session-control-rpc-commands.d.ts +1 -1
  72. package/dist/modes/interactive/session-control-rpc-commands.js +5 -0
  73. package/dist/modes/rpc/compact-admission-validation.js +4 -1
  74. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  75. package/dist/modes/rpc/connection-handler.js +10 -2
  76. package/dist/modes/rpc/custom-capability.d.ts +2 -0
  77. package/dist/modes/rpc/custom-capability.js +2 -0
  78. package/dist/modes/rpc/effect-commands.d.ts +21 -0
  79. package/dist/modes/rpc/host-capabilities.d.ts +1 -0
  80. package/dist/modes/rpc/host-capabilities.js +3 -1
  81. package/dist/modes/rpc/host-observe-request.d.ts +2 -0
  82. package/dist/modes/rpc/host-observe-request.js +6 -1
  83. package/dist/modes/rpc/host-park-ledger.d.ts +19 -0
  84. package/dist/modes/rpc/host-park-ledger.js +110 -0
  85. package/dist/modes/rpc/lifecycle-delivery.js +4 -1
  86. package/dist/modes/rpc/media-placeholders.js +1 -0
  87. package/dist/modes/rpc/method-classes-schema-host.d.ts +42 -1
  88. package/dist/modes/rpc/method-classes-schema-host.js +24 -21
  89. package/dist/modes/rpc/method-classes-schema.d.ts +42 -1
  90. package/dist/modes/rpc/method-classes-schema.js +5 -2
  91. package/dist/modes/rpc/method-classes.d.ts +2 -0
  92. package/dist/modes/rpc/method-classes.js +3 -0
  93. package/dist/modes/rpc/multi-session-host.js +1 -1
  94. package/dist/modes/rpc/rpc-host-command-types.d.ts +14 -1
  95. package/dist/modes/rpc/rpc-host-response-types.d.ts +21 -0
  96. package/dist/modes/rpc/session-attachment-gate.js +2 -0
  97. package/dist/modes/rpc/session-binding.d.ts +1 -0
  98. package/dist/modes/rpc/session-binding.js +6 -1
  99. package/dist/modes/rpc/session-connection-context.d.ts +2 -0
  100. package/dist/modes/rpc/session-connection-context.js +4 -0
  101. package/dist/modes/rpc/session-registry-attach.d.ts +2 -0
  102. package/dist/modes/rpc/session-registry-attach.js +15 -11
  103. package/dist/modes/rpc/session-registry-claims.js +2 -0
  104. package/dist/modes/rpc/session-registry-open.js +13 -7
  105. package/dist/modes/rpc/session-registry-opening.js +2 -1
  106. package/dist/modes/rpc/session-registry-types.d.ts +4 -0
  107. package/dist/modes/rpc/session-registry.d.ts +3 -0
  108. package/dist/modes/rpc/session-registry.js +27 -3
  109. package/dist/modes/rpc/session-router-close.js +1 -0
  110. package/dist/modes/rpc/session-router-context.d.ts +4 -2
  111. package/dist/modes/rpc/session-router-context.js +3 -0
  112. package/dist/modes/rpc/session-router-host-reads.js +1 -0
  113. package/dist/modes/rpc/session-router-occupancy.js +10 -1
  114. package/dist/modes/rpc/session-router-open-result.d.ts +12 -0
  115. package/dist/modes/rpc/session-router-open-result.js +63 -0
  116. package/dist/modes/rpc/session-router-open.d.ts +3 -0
  117. package/dist/modes/rpc/session-router-open.js +15 -63
  118. package/dist/modes/rpc/session-router-park.d.ts +15 -0
  119. package/dist/modes/rpc/session-router-park.js +176 -0
  120. package/dist/modes/rpc/session-router-routing.d.ts +1 -1
  121. package/dist/modes/rpc/session-router-routing.js +7 -0
  122. package/dist/modes/rpc/session-status-source.js +2 -2
  123. package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
  124. package/docs/engine-socket/fixtures/rpc-inbound-samples.json +22 -2
  125. package/docs/rpc.md +50 -0
  126. package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
  127. package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
  128. package/package.json +6 -6
  129. package/dist/bundle/chunks/chunk-436DNN4Z.js +0 -2
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunks/chunk-LHEP3ACI.js";import"./chunks/chunk-KU72IKV5.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-GLTOBXZY.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-3IYWH6RO.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-2SOVDETB.js";import{preparePrivateFdSpawn,runtimeExecArgv,spawnWithPrivateFds}from"./chunks/chunk-E266ORGA.js";import{releaseInheritedStartupFillers}from"./chunks/chunk-T2SMQPRE.js";import{HOST_STARTUP_EVENTS_ENV}from"./chunks/chunk-RUGTHELO.js";import{isFifoMode}from"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-IHES3JES.js";import"./chunks/chunk-5XHOHZIR.js";import"./chunks/chunk-HW6AAS3R.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-SODMQEHO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-FQXWKEVK.js";import"./chunks/chunk-IKOFCODM.js";releaseInheritedStartupFillers(process.env);import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync3,fstatSync,realpathSync as realpathSync5}from"node:fs";import{dirname as dirname4,join as join8}from"node:path";import{fileURLToPath}from"node:url";async function dispatchKillGuardCommand(args2){if(args2[0]!=="__kill-guard")return;let{runKillGuardCheckCommand}=await import("./chunks/check-command-KGFICS6A.js");process.exit(runKillGuardCheckCommand())}import{createHash}from"node:crypto";import{readFileSync as readFileSync5,realpathSync as realpathSync4}from"node:fs";import{basename as basename2,dirname as dirname3,join as join6,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync as existsSync2,readFileSync as readFileSync3,realpathSync as realpathSync3,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname as dirname2,join as join4}from"node:path";import{existsSync,readFileSync}from"node:fs";import{join}from"node:path";var INERT_TREE=/^(?:tests?|__tests__|__fixtures__|fixtures|docs?|examples?|bench(?:marks?)?)$/,ROOT_NOTES=/^(?:readme|changelog|history)(?:\.[^/]*)?$/i,ROOT_MARKDOWN=/^[^/]+\.md$/i,LICENSE=/^licen[cs]e(?:\.[^/]*)?$/i;function dependencyFileExclusions(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return()=>!1;let entryRoots=new Set,built=!1,visit=value=>{if(typeof value=="string"){let entry=value.replace(/^\.\//,"");entryRoots.add(entry.split("/")[0]??""),/\.[cm]?js$/.test(entry)&&existsSync(join(packageDir,entry))&&(built=!0)}else if(Array.isArray(value))for(let child of value)visit(child);else if(typeof value=="object"&&value!==null)for(let[condition,child]of Object.entries(value))condition!=="types"&&visit(child)};for(let[key,value]of Object.entries(manifest))["main","module","exports","bin","pi"].includes(key)&&visit(value);return path=>{let root=path.split("/")[0]??"";return entryRoots.has(root)||entryRoots.has("*")||entryRoots.has("**")?!1:INERT_TREE.test(root)||ROOT_NOTES.test(path)||ROOT_MARKDOWN.test(path)&&!LICENSE.test(path)?!0:built&&root==="src"&&/\.[cm]?tsx?$/.test(path)}}import{constants}from"node:fs";import{copyFile,link}from"node:fs/promises";function errorCode(error){return error instanceof Error&&"code"in error?error.code:void 0}var FILE_OPERATIONS={copyFile,link},COPY_CONCURRENCY=8;function nextCopyMode(mode,error,platform){let code=errorCode(error);if(!(code==="ENOENT"||code==="ENOTDIR"||code==="EEXIST"))switch(mode){case"clone":return platform==="darwin"&&code==="ENOSYS"?"clone-or-copy":"link";case"link":return"copy";case"clone-or-copy":case"copy":return}}function createSnapshotFileCopier(platform=process.platform,operations=FILE_OPERATIONS){let mode="clone",attempt=(current,source,target)=>{switch(current){case"clone":return operations.copyFile(source,target,constants.COPYFILE_FICLONE_FORCE);case"clone-or-copy":return operations.copyFile(source,target,constants.COPYFILE_FICLONE);case"link":return operations.link(source,target);case"copy":return operations.copyFile(source,target,0)}};return{get mode(){return mode},async copy(source,target){for(let current=mode;;)try{await attempt(current,source,target);return}catch(error){let next=nextCopyMode(current,error,platform);if(next===void 0)throw error;current=next,mode=next}}}}async function copyFiles(pairs,copier){let next=0,worker=async()=>{for(let index=next++;index<pairs.length;index=next++){let[source,target]=pairs[index]??[];source!==void 0&&target!==void 0&&await copier.copy(source,target)}};await Promise.all(Array.from({length:Math.min(COPY_CONCURRENCY,pairs.length)},worker))}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{dirname,join as join3}from"node:path";import{mkdirSync,readdirSync,realpathSync,statSync}from"node:fs";import{join as join2}from"node:path";var UNLOADED_FILE=/\.(?:d\.[cm]?ts|map)$/;function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function planTree(source,target,files,skipModules,seen=new Set,excluded=()=>!1,relativeDir=""){let real=realpathSync(source);if(!seen.has(real)){seen.add(real),mkdirSync(target,{recursive:!0});for(let entry of readdirSync(real,{withFileTypes:!0})){if(skipModules&&entry.name==="node_modules")continue;let relativePath=relativeDir===""?entry.name:`${relativeDir}/${entry.name}`;if(excluded(relativePath))continue;let from=join2(real,entry.name),to=join2(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen,excluded,relativePath);else if(entry.isFile())UNLOADED_FILE.test(entry.name)||files.push([from,to]);else if(entry.isSymbolicLink()){let isDirectory;try{isDirectory=statSync(from).isDirectory()}catch(error){if(isMissing(error))continue;throw error}isDirectory?planTree(from,to,files,skipModules,seen,excluded,relativePath):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}var ALWAYS_SHIPPED=/^(?:package\.json|readme(?:\..*)?|licen[cs]e(?:\..*)?)$/i;function globToRegExp(glob){let source="";for(let index=0;index<glob.length;index++){let char=glob[index];glob.startsWith("**/",index)?(source+="(?:.*/)?",index+=2):glob.startsWith("**",index)?(source+=".*",index+=1):char==="*"?source+="[^/]*":char==="?"?source+="[^/]":source+=char.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${source}(?:/.*)?$`)}function shippedEntries(packageDir){let manifest=JSON.parse(readFileSync2(join3(packageDir,"package.json"),"utf8")),listed=typeof manifest=="object"&&manifest!==null?manifest.files:void 0;if(!Array.isArray(listed)||!listed.every(entry=>typeof entry=="string"))return;let normalize=entry=>entry.replace(/^\.\//,"").replace(/\/+$/,"");return{include:listed.filter(entry=>!entry.startsWith("!")).map(normalize),exclude:listed.filter(entry=>entry.startsWith("!")).map(entry=>globToRegExp(normalize(entry.slice(1))))}}function planPackageRoot(packageDir,target,files){let shipped=shippedEntries(packageDir);if(shipped===void 0){planTree(packageDir,target,files,!0);return}let root=realpathSync2(packageDir),excluded=relativePath=>shipped.exclude.some(pattern=>pattern.test(relativePath)),planned=new Set,plan=relativePath=>{if(planned.has(relativePath)||excluded(relativePath))return;let from=join3(root,relativePath),isDirectory;try{isDirectory=statSync2(from).isDirectory()}catch(error){if(isMissing(error))return;throw error}planned.add(relativePath);let to=join3(target,relativePath);isDirectory?planTree(from,to,files,!0,new Set([root]),excluded,relativePath):UNLOADED_FILE.test(relativePath)||(mkdirSync2(dirname(to),{recursive:!0}),files.push([realpathSync2(from),to]))};mkdirSync2(target,{recursive:!0});let topLevel=readdirSync2(root).filter(name=>name!=="node_modules");for(let name of topLevel)ALWAYS_SHIPPED.test(name)&&plan(name);for(let entry of shipped.include){let segments=entry.split("/"),wildcard=segments.findIndex(segment=>/[*?]/.test(segment));if(wildcard===-1)plan(entry);else if(wildcard>0)plan(segments.slice(0,wildcard).join("/"));else{let pattern=globToRegExp(segments[0]??"");for(let name of topLevel)pattern.test(name)&&plan(name)}}}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-";function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname2(current)){if(basename(current)!=="node_modules"){let candidate=join4(current,"node_modules");existsSync2(candidate)&&directories.push(candidate)}if(dirname2(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join4(modules,packageName);if(existsSync2(join4(root,"package.json")))return realpathSync3(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync3(join4(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return[];let names=new Set;for(let field of["dependencies","optionalDependencies","peerDependencies"]){let block=manifest[field];if(typeof block=="object"&&block!==null)for(let name of Object.keys(block))names.add(name)}return[...names]}function closureNames(packageDir,extra){let names=new Set(extra),visited=new Set,pending=[realpathSync3(packageDir)];for(let dir=pending.pop();dir!==void 0;dir=pending.pop())if(!visited.has(dir)){visited.add(dir);for(let name of dependencyNames(dir)){names.add(name);let root=packageRootFrom(dir,name);root!==void 0&&!visited.has(root)&&pending.push(root)}}return names}function planModules(packageDir,snapshotRoot,externals,files){let self=realpathSync3(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0,new Set,dependencyFileExclusions(installDir)),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname2(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join4(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname2(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join4(snapshotRoot,"node_modules",name))}for(let next=pending.shift();next!==void 0;next=pending.shift())for(let name of dependencyNames(next.installDir)){let expected=packageRootFrom(next.installDir,name);expected===void 0||expected===self||resolvePlaced(next.snapshotDir,name)!==expected&&place(expected,join4(next.snapshotDir,"node_modules",name))}return placed}function verifyExternals(packageDir,snapshotBundleDir,externals,placed){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected===void 0)continue;let found=moduleDirectoriesFrom(snapshotBundleDir).map(modules=>join4(modules,name)).find(root=>existsSync2(join4(root,"package.json")));if(found===void 0||placed.get(found)!==expected)throw new RuntimeSnapshotLayoutError(name)}}async function materializeRuntimeSnapshot(packageDir,target,manifest,copier=createSnapshotFileCopier()){let staging=join4(dirname2(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planPackageRoot(packageDir,staging,files);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join4(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync3(packageDir)};writeFileSync(join4(staging,RUNTIME_SNAPSHOT_MARKER),`${JSON.stringify(marker)}
4
- `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync3,readdirSync as readdirSync3,readFileSync as readFileSync4,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync3,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join5}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync3(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync3(root,{recursive:!0});let lock=join5(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync3(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync4(join5(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync3(root,{recursive:!0});let lock=join5(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync3(lock),writeFileSync2(join5(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync3(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join5(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync3(join5(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join5(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join5(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync3(join5(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join5(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join5(root,keep),isAlive);for(let name of readdirSync3(root)){if(name===LOCK_NAME||name===keep)continue;let path=join5(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join5(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join5(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync5(join6(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname3(entryPath),runtimeRoot=join6(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join6("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync4(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join6(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join6(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync6}from"node:fs";import{join as join7}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync6(join7(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit",windowsHide:!0});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 reexecStdio(){let base=channelStdio();if(!process.env[HOST_STARTUP_EVENTS_ENV])return base;try{let stat=fstatSync(16);if(!stat.isSocket()&&!isFifoMode(stat.mode))return base}catch{return base}let slots=typeof base=="string"?[base,base,base]:[...base];for(;slots.length<16;)slots.push("ignore");return slots[16]=16,slots}function channelStdio(){let argv=process.argv.slice(2),presenter=argv.indexOf("--mcp-presenter-fd");if(presenter<0||argv[presenter+1]!=="4")return"inherit";try{let stat=fstatSync(4);if(!stat.isSocket()&&!stat.isFIFO())return"inherit"}catch{return"inherit"}let owner=argv.indexOf("--owner-fd");return["inherit","inherit","inherit",owner>=0&&argv[owner+1]==="3"||process.env.SENPI_RPC_HOST_WATCH_FD==="3"?3:"ignore",4]}function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync3,realpathSync5),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync5(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let transfer=preparePrivateFdSpawn({stdio:reexecStdio(),windowsHide:!0}),result=(()=>{try{return spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],transfer.options)}finally{transfer.close()}})();return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}await dispatchKillGuardCommand(process.argv.slice(2));reexecUnderBunIfNeeded()&&process.exit();var args=process.argv.slice(2);await dispatchAgentDirectoryCommand(args);await enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync3(join8(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:runtimeExecArgv().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={...process.env,[ISOLATED_CHILD_ENV]:"1"};return await new Promise((resolve,reject)=>{let child=spawnWithPrivateFds(spawn2,process.execPath,[...runtimeExecArgv(),fullCliPath,...args],{env:childEnvironment,stdio:reexecStdio()});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&await printThenExit(()=>console.log(DISPLAY_VERSION));if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-5SCPY3OH.js"),help=await captureStdout(()=>tryPrintHelpWithoutEngine(args));help.result&&await exitAfterOutput(help.output),process.stdout.write(help.output)}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname4(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-VG3C2EXI.js")}
3
+ import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunks/chunk-YNGEZBTP.js";import"./chunks/chunk-KU72IKV5.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-GLTOBXZY.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-IKJCA5SH.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-2SOVDETB.js";import{preparePrivateFdSpawn,runtimeExecArgv,spawnWithPrivateFds}from"./chunks/chunk-E266ORGA.js";import{releaseInheritedStartupFillers}from"./chunks/chunk-T2SMQPRE.js";import{HOST_STARTUP_EVENTS_ENV}from"./chunks/chunk-RUGTHELO.js";import{isFifoMode}from"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-IHES3JES.js";import"./chunks/chunk-5XHOHZIR.js";import"./chunks/chunk-HW6AAS3R.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-SODMQEHO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-FQXWKEVK.js";import"./chunks/chunk-IKOFCODM.js";releaseInheritedStartupFillers(process.env);import{spawn as spawn2,spawnSync}from"node:child_process";import{existsSync as existsSync3,fstatSync,realpathSync as realpathSync5}from"node:fs";import{dirname as dirname4,join as join8}from"node:path";import{fileURLToPath}from"node:url";async function dispatchKillGuardCommand(args2){if(args2[0]!=="__kill-guard")return;let{runKillGuardCheckCommand}=await import("./chunks/check-command-KGFICS6A.js");process.exit(runKillGuardCheckCommand())}import{createHash}from"node:crypto";import{readFileSync as readFileSync5,realpathSync as realpathSync4}from"node:fs";import{basename as basename2,dirname as dirname3,join as join6,relative}from"node:path";import{pathToFileURL}from"node:url";import{existsSync as existsSync2,readFileSync as readFileSync3,realpathSync as realpathSync3,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname as dirname2,join as join4}from"node:path";import{existsSync,readFileSync}from"node:fs";import{join}from"node:path";var INERT_TREE=/^(?:tests?|__tests__|__fixtures__|fixtures|docs?|examples?|bench(?:marks?)?)$/,ROOT_NOTES=/^(?:readme|changelog|history)(?:\.[^/]*)?$/i,ROOT_MARKDOWN=/^[^/]+\.md$/i,LICENSE=/^licen[cs]e(?:\.[^/]*)?$/i;function dependencyFileExclusions(packageDir){let manifest=JSON.parse(readFileSync(join(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return()=>!1;let entryRoots=new Set,built=!1,visit=value=>{if(typeof value=="string"){let entry=value.replace(/^\.\//,"");entryRoots.add(entry.split("/")[0]??""),/\.[cm]?js$/.test(entry)&&existsSync(join(packageDir,entry))&&(built=!0)}else if(Array.isArray(value))for(let child of value)visit(child);else if(typeof value=="object"&&value!==null)for(let[condition,child]of Object.entries(value))condition!=="types"&&visit(child)};for(let[key,value]of Object.entries(manifest))["main","module","exports","bin","pi"].includes(key)&&visit(value);return path=>{let root=path.split("/")[0]??"";return entryRoots.has(root)||entryRoots.has("*")||entryRoots.has("**")?!1:INERT_TREE.test(root)||ROOT_NOTES.test(path)||ROOT_MARKDOWN.test(path)&&!LICENSE.test(path)?!0:built&&root==="src"&&/\.[cm]?tsx?$/.test(path)}}import{constants}from"node:fs";import{copyFile,link}from"node:fs/promises";function errorCode(error){return error instanceof Error&&"code"in error?error.code:void 0}var FILE_OPERATIONS={copyFile,link},COPY_CONCURRENCY=8;function nextCopyMode(mode,error,platform){let code=errorCode(error);if(!(code==="ENOENT"||code==="ENOTDIR"||code==="EEXIST"))switch(mode){case"clone":return platform==="darwin"&&code==="ENOSYS"?"clone-or-copy":"link";case"link":return"copy";case"clone-or-copy":case"copy":return}}function createSnapshotFileCopier(platform=process.platform,operations=FILE_OPERATIONS){let mode="clone",attempt=(current,source,target)=>{switch(current){case"clone":return operations.copyFile(source,target,constants.COPYFILE_FICLONE_FORCE);case"clone-or-copy":return operations.copyFile(source,target,constants.COPYFILE_FICLONE);case"link":return operations.link(source,target);case"copy":return operations.copyFile(source,target,0)}};return{get mode(){return mode},async copy(source,target){for(let current=mode;;)try{await attempt(current,source,target);return}catch(error){let next=nextCopyMode(current,error,platform);if(next===void 0)throw error;current=next,mode=next}}}}async function copyFiles(pairs,copier){let next=0,worker=async()=>{for(let index=next++;index<pairs.length;index=next++){let[source,target]=pairs[index]??[];source!==void 0&&target!==void 0&&await copier.copy(source,target)}};await Promise.all(Array.from({length:Math.min(COPY_CONCURRENCY,pairs.length)},worker))}import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{dirname,join as join3}from"node:path";import{mkdirSync,readdirSync,realpathSync,statSync}from"node:fs";import{join as join2}from"node:path";var UNLOADED_FILE=/\.(?:d\.[cm]?ts|map)$/;function isMissing(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")}function planTree(source,target,files,skipModules,seen=new Set,excluded=()=>!1,relativeDir=""){let real=realpathSync(source);if(!seen.has(real)){seen.add(real),mkdirSync(target,{recursive:!0});for(let entry of readdirSync(real,{withFileTypes:!0})){if(skipModules&&entry.name==="node_modules")continue;let relativePath=relativeDir===""?entry.name:`${relativeDir}/${entry.name}`;if(excluded(relativePath))continue;let from=join2(real,entry.name),to=join2(target,entry.name);if(entry.isDirectory())planTree(from,to,files,skipModules,seen,excluded,relativePath);else if(entry.isFile())UNLOADED_FILE.test(entry.name)||files.push([from,to]);else if(entry.isSymbolicLink()){let isDirectory;try{isDirectory=statSync(from).isDirectory()}catch(error){if(isMissing(error))continue;throw error}isDirectory?planTree(from,to,files,skipModules,seen,excluded,relativePath):UNLOADED_FILE.test(entry.name)||files.push([realpathSync(from),to])}}seen.delete(real)}}var ALWAYS_SHIPPED=/^(?:package\.json|readme(?:\..*)?|licen[cs]e(?:\..*)?)$/i;function globToRegExp(glob){let source="";for(let index=0;index<glob.length;index++){let char=glob[index];glob.startsWith("**/",index)?(source+="(?:.*/)?",index+=2):glob.startsWith("**",index)?(source+=".*",index+=1):char==="*"?source+="[^/]*":char==="?"?source+="[^/]":source+=char.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${source}(?:/.*)?$`)}function shippedEntries(packageDir){let manifest=JSON.parse(readFileSync2(join3(packageDir,"package.json"),"utf8")),listed=typeof manifest=="object"&&manifest!==null?manifest.files:void 0;if(!Array.isArray(listed)||!listed.every(entry=>typeof entry=="string"))return;let normalize=entry=>entry.replace(/^\.\//,"").replace(/\/+$/,"");return{include:listed.filter(entry=>!entry.startsWith("!")).map(normalize),exclude:listed.filter(entry=>entry.startsWith("!")).map(entry=>globToRegExp(normalize(entry.slice(1))))}}function planPackageRoot(packageDir,target,files){let shipped=shippedEntries(packageDir);if(shipped===void 0){planTree(packageDir,target,files,!0);return}let root=realpathSync2(packageDir),excluded=relativePath=>shipped.exclude.some(pattern=>pattern.test(relativePath)),planned=new Set,plan=relativePath=>{if(planned.has(relativePath)||excluded(relativePath))return;let from=join3(root,relativePath),isDirectory;try{isDirectory=statSync2(from).isDirectory()}catch(error){if(isMissing(error))return;throw error}planned.add(relativePath);let to=join3(target,relativePath);isDirectory?planTree(from,to,files,!0,new Set([root]),excluded,relativePath):UNLOADED_FILE.test(relativePath)||(mkdirSync2(dirname(to),{recursive:!0}),files.push([realpathSync2(from),to]))};mkdirSync2(target,{recursive:!0});let topLevel=readdirSync2(root).filter(name=>name!=="node_modules");for(let name of topLevel)ALWAYS_SHIPPED.test(name)&&plan(name);for(let entry of shipped.include){let segments=entry.split("/"),wildcard=segments.findIndex(segment=>/[*?]/.test(segment));if(wildcard===-1)plan(entry);else if(wildcard>0)plan(segments.slice(0,wildcard).join("/"));else{let pattern=globToRegExp(segments[0]??"");for(let name of topLevel)pattern.test(name)&&plan(name)}}}var RuntimeSnapshotLayoutError=class extends Error{constructor(packageName){super(`runtime snapshot resolves ${packageName} differently from the install`),this.packageName=packageName}},STAGING_PREFIX=".tmp-";function moduleDirectoriesFrom(dir){let directories=[];for(let current=dir;;current=dirname2(current)){if(basename(current)!=="node_modules"){let candidate=join4(current,"node_modules");existsSync2(candidate)&&directories.push(candidate)}if(dirname2(current)===current)return directories}}function packageRootFrom(dir,packageName){for(let modules of moduleDirectoriesFrom(dir)){let root=join4(modules,packageName);if(existsSync2(join4(root,"package.json")))return realpathSync3(root)}}function dependencyNames(packageDir){let manifest=JSON.parse(readFileSync3(join4(packageDir,"package.json"),"utf8"));if(typeof manifest!="object"||manifest===null)return[];let names=new Set;for(let field of["dependencies","optionalDependencies","peerDependencies"]){let block=manifest[field];if(typeof block=="object"&&block!==null)for(let name of Object.keys(block))names.add(name)}return[...names]}function closureNames(packageDir,extra){let names=new Set(extra),visited=new Set,pending=[realpathSync3(packageDir)];for(let dir=pending.pop();dir!==void 0;dir=pending.pop())if(!visited.has(dir)){visited.add(dir);for(let name of dependencyNames(dir)){names.add(name);let root=packageRootFrom(dir,name);root!==void 0&&!visited.has(root)&&pending.push(root)}}return names}function planModules(packageDir,snapshotRoot,externals,files){let self=realpathSync3(packageDir),placed=new Map,pending=[],place=(installDir,snapshotDir)=>{planTree(installDir,snapshotDir,files,!0,new Set,dependencyFileExclusions(installDir)),placed.set(snapshotDir,installDir),pending.push({installDir,snapshotDir})},resolvePlaced=(from,name)=>{for(let dir=from;;dir=dirname2(dir)){if(basename(dir)!=="node_modules"){let found=placed.get(join4(dir,"node_modules",name));if(found!==void 0)return found}if(dir===snapshotRoot||dirname2(dir)===dir)return}};for(let name of closureNames(packageDir,externals)){let source=packageRootFrom(packageDir,name);source!==void 0&&source!==self&&place(source,join4(snapshotRoot,"node_modules",name))}for(let next=pending.shift();next!==void 0;next=pending.shift())for(let name of dependencyNames(next.installDir)){let expected=packageRootFrom(next.installDir,name);expected===void 0||expected===self||resolvePlaced(next.snapshotDir,name)!==expected&&place(expected,join4(next.snapshotDir,"node_modules",name))}return placed}function verifyExternals(packageDir,snapshotBundleDir,externals,placed){for(let name of externals){let expected=packageRootFrom(packageDir,name);if(expected===void 0)continue;let found=moduleDirectoriesFrom(snapshotBundleDir).map(modules=>join4(modules,name)).find(root=>existsSync2(join4(root,"package.json")));if(found===void 0||placed.get(found)!==expected)throw new RuntimeSnapshotLayoutError(name)}}async function materializeRuntimeSnapshot(packageDir,target,manifest,copier=createSnapshotFileCopier()){let staging=join4(dirname2(target),`${STAGING_PREFIX}${basename(target)}-${process.pid}`);rmSync(staging,{recursive:!0,force:!0});try{let files=[];planPackageRoot(packageDir,staging,files);let placed=planModules(packageDir,staging,manifest.externals,files);await copyFiles(files,copier),verifyExternals(packageDir,join4(staging,"dist","bundle","chunks"),manifest.externals,placed);let marker={buildId:manifest.buildId,installPackageDir:realpathSync3(packageDir)};writeFileSync(join4(staging,RUNTIME_SNAPSHOT_MARKER),`${JSON.stringify(marker)}
4
+ `),rmSync(target,{recursive:!0,force:!0}),renameSync(staging,target)}catch(error){throw rmSync(staging,{recursive:!0,force:!0}),error}}import{mkdirSync as mkdirSync3,readdirSync as readdirSync3,readFileSync as readFileSync4,renameSync as renameSync2,rmSync as rmSync2,statSync as statSync3,unlinkSync,utimesSync,writeFileSync as writeFileSync2}from"node:fs";import{join as join5}from"node:path";var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25,BUILD_LOCK_PREFIX=".build-",BUILD_WAIT_MS=12e4,BUILD_RETRY_MS=50,UNOWNED_BUILD_LOCK_MS=3e4,UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode2(error){return error instanceof Error&&"code"in error?error.code:void 0}function ageMs(path,now){try{return now-statSync3(path).mtimeMs}catch(error){if(errorCode2(error)==="ENOENT")return Number.POSITIVE_INFINITY;throw error}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync3(root,{recursive:!0});let lock=join5(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync3(lock);break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function buildLockHolder(lock){try{let pid=Number(readFileSync4(join5(lock,"pid"),"utf8"));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}catch(error){if(errorCode2(error)==="ENOENT"||errorCode2(error)==="ENOTDIR")return;throw error}}function isAbandonedBuildLock(lock,now,isAlive){let holder=buildLockHolder(lock);return holder===void 0?ageMs(lock,now)>UNOWNED_BUILD_LOCK_MS:!isAlive(holder)}async function withBuildLock(root,id,build,isAlive=isProcessAlive){mkdirSync3(root,{recursive:!0});let lock=join5(root,`${BUILD_LOCK_PREFIX}${id}`),deadline=Date.now()+BUILD_WAIT_MS;for(;;){try{mkdirSync3(lock),writeFileSync2(join5(lock,"pid"),String(process.pid));break}catch(error){if(errorCode2(error)!=="EEXIST")throw error}if(isAbandonedBuildLock(lock,Date.now(),isAlive))rmSync2(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(BUILD_RETRY_MS)}}try{for(let name of readdirSync3(root))name.startsWith(`${STAGING_PREFIX}${id}-`)&&rmSync2(join5(root,name),{recursive:!0,force:!0});return await build()}finally{rmSync2(lock,{recursive:!0,force:!0})}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode2(error)!=="ESRCH"}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync3(join5(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync2(join5(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join5(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}function reapClaims(snapshotDir,isAlive){let names;try{names=readdirSync3(join5(snapshotDir,CLAIMS_DIR))}catch(error){if(errorCode2(error)==="ENOENT")return 0;throw error}let live=0;for(let name of names){let pid=Number(name);Number.isSafeInteger(pid)&&pid>0&&isAlive(pid)?live+=1:unlinkSync(join5(snapshotDir,CLAIMS_DIR,name))}return live}function pruneRuntimeSnapshots(root,keep,now,isAlive=isProcessAlive){reapClaims(join5(root,keep),isAlive);for(let name of readdirSync3(root)){if(name===LOCK_NAME||name===keep)continue;let path=join5(root,name);if(name.startsWith(".")){ageMs(path,now)>LEFTOVER_MS&&rmSync2(path,{recursive:!0,force:!0});continue}if(reapClaims(path,isAlive)>0||ageMs(join5(path,RUNTIME_SNAPSHOT_MARKER),now)<=UNUSED_SNAPSHOT_GRACE_MS)continue;let trash=join5(root,`.trash-${name}-${process.pid}`);renameSync2(path,trash),rmSync2(trash,{recursive:!0,force:!0})}}var RUNTIME_MANIFEST="runtime-manifest.json";function readRuntimeManifest(bundleDir){let parsed;try{parsed=JSON.parse(readFileSync5(join6(bundleDir,RUNTIME_MANIFEST),"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&/^[A-Za-z0-9._-]+$/.test(parsed.buildId)&&"externals"in parsed&&Array.isArray(parsed.externals)&&parsed.externals.every(name=>typeof name=="string"))return{buildId:parsed.buildId,externals:parsed.externals}}async function prepareRuntimeSnapshot(entryPath,packageDir,agentDir){let bundleDir=dirname3(entryPath),runtimeRoot=join6(agentDir,"runtime");try{if(readRuntimeSnapshotMarker(packageDir))return withRuntimeLock(runtimeRoot,()=>claimRuntimeSnapshot(packageDir,process.pid)),{kind:"run-here"};let manifest=readRuntimeManifest(bundleDir);if(!manifest||relative(packageDir,bundleDir)!==join6("dist","bundle"))return{kind:"run-here"};let installId=createHash("sha256").update(realpathSync4(packageDir)).digest("hex").slice(0,12),snapshotId=`${manifest.buildId}-${installId}`,snapshotDir=join6(runtimeRoot,snapshotId),isBuilt=()=>readRuntimeSnapshotMarker(snapshotDir)?.buildId===manifest.buildId,claim=()=>withRuntimeLock(runtimeRoot,()=>isBuilt()?(claimRuntimeSnapshot(snapshotDir,process.pid),pruneRuntimeSnapshots(runtimeRoot,snapshotId,Date.now()),!0):!1),claimed=claim();return claimed===!1&&await withBuildLock(runtimeRoot,snapshotId,async()=>(isBuilt()||await materializeRuntimeSnapshot(packageDir,snapshotDir,manifest),!0))&&(claimed=claim()),claimed!==!0?{kind:"run-here"}:{kind:"hand-off",entryUrl:pathToFileURL(join6(snapshotDir,"dist","bundle",basename2(entryPath))).href,snapshotDir}}catch{return{kind:"run-here"}}}import{spawn}from"node:child_process";import{readFileSync as readFileSync6}from"node:fs";import{join as join7}from"node:path";function parseBootstrapSelfUpdateArgs(args2){let[command,...rest]=args2;if(command!=="update")return;let force=!1,selfFlag=!1,extensionsFlag=!1,extensionFlag=!1,source;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help")return;if(arg==="--force"){force=!0;continue}if(arg==="--self"){selfFlag=!0;continue}if(arg==="--extensions"){extensionsFlag=!0;continue}if(arg==="--extension"){extensionFlag=!0,index++;continue}if(arg.startsWith("-")||source)return;source=arg}if(extensionFlag)return;let sourceIsSelf=source==="self"||source==="pi"||source===APP_NAME;if(!(source&&!sourceIsSelf)&&!(!selfFlag&&!sourceIsSelf&&extensionsFlag))return{force}}function getObjectProperty(value,key){if(!(!value||typeof value!="object"))return Object.getOwnPropertyDescriptor(value,key)?.value}function readConfiguredNpmCommand(){try{let parsed=JSON.parse(readFileSync6(join7(getAgentDir(),"settings.json"),"utf-8")),npmCommand=getObjectProperty(parsed,"npmCommand");return!Array.isArray(npmCommand)||npmCommand.some(part=>typeof part!="string")?void 0:npmCommand.length>0?npmCommand:void 0}catch{return}}async function runCommand(step){await new Promise((resolve,reject)=>{let child=spawn(step.command,step.args,{stdio:"inherit",windowsHide:!0});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 reexecStdio(){let base=channelStdio();if(!process.env[HOST_STARTUP_EVENTS_ENV])return base;try{let stat=fstatSync(16);if(!stat.isSocket()&&!isFifoMode(stat.mode))return base}catch{return base}let slots=typeof base=="string"?[base,base,base]:[...base];for(;slots.length<16;)slots.push("ignore");return slots[16]=16,slots}function channelStdio(){let argv=process.argv.slice(2),presenter=argv.indexOf("--mcp-presenter-fd");if(presenter<0||argv[presenter+1]!=="4")return"inherit";try{let stat=fstatSync(4);if(!stat.isSocket()&&!stat.isFIFO())return"inherit"}catch{return"inherit"}let owner=argv.indexOf("--owner-fd");return["inherit","inherit","inherit",owner>=0&&argv[owner+1]==="3"||process.env.SENPI_RPC_HOST_WATCH_FD==="3"?3:"ignore",4]}function reexecUnderBunIfNeeded(){let options=processBunRuntimeOptions(existsSync3,realpathSync5),scriptRealPath=process.argv[1]??fileURLToPath(import.meta.url);try{scriptRealPath=realpathSync5(scriptRealPath)}catch{}let decision=resolveBunReexec({scriptRealPath,versions:process.versions,hasInheritedInspectorOption:hasInheritedInspectorOption(),options});if(decision.action==="stay")return!1;let transfer=preparePrivateFdSpawn({stdio:reexecStdio(),windowsHide:!0}),result=(()=>{try{return spawnSync(decision.bunPath,[scriptRealPath,...process.argv.slice(2)],transfer.options)}finally{transfer.close()}})();return result.signal?(process.kill(process.pid,result.signal),!0):(process.exitCode=result.status??1,!0)}await dispatchKillGuardCommand(process.argv.slice(2));reexecUnderBunIfNeeded()&&process.exit();var args=process.argv.slice(2);await dispatchAgentDirectoryCommand(args);await enableStartupCompileCache();process.title=APP_NAME;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT=APP_NAME;process.emitWarning=(()=>{});var PACKAGE_COMMANDS=new Set(["install","remove","uninstall","update","list","config"]);function isRootCommand(args2){let firstArg=args2[0];return firstArg===void 0||!PACKAGE_COMMANDS.has(firstArg)}function isPackageManagerInstall(packageDir){return packageDir.replace(/\\/g,"/").includes("/node_modules/@code-yeongyu/senpi")}function isMissingBundledWorkspaceDependencies(packageDir){return isPackageManagerInstall(packageDir)?["pi-agent-core","pi-ai","pi-tui"].some(name=>!existsSync3(join8(packageDir,"node_modules","@earendil-works",name,"dist","index.js"))):!1}var ISOLATED_CHILD_ENV="SENPI_CLI_ISOLATED_CHILD";function requiresIsolatedProcess(){return process.env[ISOLATED_CHILD_ENV]==="1"?!1:runtimeExecArgv().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={...process.env,[ISOLATED_CHILD_ENV]:"1"};return await new Promise((resolve,reject)=>{let child=spawnWithPrivateFds(spawn2,process.execPath,[...runtimeExecArgv(),fullCliPath,...args],{env:childEnvironment,stdio:reexecStdio()});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{if(signal){process.kill(process.pid,signal),resolve(1);return}resolve(code??1)})})}isRootCommand(args)&&(args.includes("--version")||args.includes("-v"))&&await printThenExit(()=>console.log(DISPLAY_VERSION));if(isRootCommand(args)&&args.some(arg=>arg==="--help"||arg==="-h")){let{tryPrintHelpWithoutEngine}=await import("./chunks/help-fast-path-5SCPY3OH.js"),help=await captureStdout(()=>tryPrintHelpWithoutEngine(args));help.result&&await exitAfterOutput(help.output),process.stdout.write(help.output)}isMissingBundledWorkspaceDependencies(getInstallPackageDir())&&await handleBootstrapSelfUpdate(args)&&process.exit();if(requiresIsolatedProcess())process.exitCode=await spawnFullCli();else{let entryPath=fileURLToPath(import.meta.url),snapshot=isBundledNode?await prepareRuntimeSnapshot(entryPath,findNodePackageDir(dirname4(entryPath)),getAgentDir()):void 0;snapshot?.kind==="hand-off"?await import(__rewriteRelativeImportExtension(snapshot.entryUrl)):await import("./chunks/cli-main-Y6ALA5OI.js")}
@@ -13,7 +13,7 @@ renameSync(temporary, launcher);
13
13
  `);return}let source=parsed,name=readString(source,"name");if(!name){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} without a "name"
14
14
  `);return}let configDir=readString(source,"configDir")||`.${name}`;if(!isSafeConfigDirName(configDir)){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} with an unsafe "configDir"
15
15
  `);return}let changelog=readChangelog(source);return{name,command:readString(source,"command"),displayVersion:readString(source,"displayVersion"),configDir,flatLayout:source.flatLayout===!0,envPrefix:(readString(source,"envPrefix")||name).toUpperCase(),userAgent:readString(source,"userAgent")||name,originator:readString(source,"originator"),logo:readString(source,"logo"),update:readUpdateChannel(source),...changelog?{changelog}:{}}}function consumeBrandProfile(env=process.env){return parseBrandProfile(env[BRAND_ENV_VAR])}function scrubBrandFromEnvironment(env=process.env){delete env[BRAND_ENV_VAR]}function brandProfile(){return profileResolved||(cachedProfile=consumeBrandProfile(),profileResolved=!0),cachedProfile}function brandEnvNames(suffix,profile=brandProfile()){let prefixes=[profile?.envPrefix,...LEGACY_ENV_PREFIXES].filter(prefix=>typeof prefix=="string"&&prefix.length>0);return[...new Set(prefixes)].map(prefix=>`${prefix}_${suffix}`)}function envValue(suffix,env=process.env){for(let name of brandEnvNames(suffix)){let value=env[name];if(value!==void 0)return value}}var BRAND_ENV_VAR,LEGACY_ENV_PREFIXES,cachedProfile,profileResolved,init_brand=__esm({"packages/coding-agent/dist/core/brand.js"(){BRAND_ENV_VAR="SENPI_BRAND";LEGACY_ENV_PREFIXES=["SENPI","PI"],profileResolved=!1}});import{lstatSync}from"node:fs";import{dirname,join,normalize}from"node:path";function isDirectory(path2){try{return lstatSync(path2).isDirectory()}catch{return!1}}function isFile(path2){try{return lstatSync(path2).isFile()}catch{return!1}}function findNearestParentConfigDir(cwd,homeDir,configDirName,requiredChildDir,requiredChildFile){let normalizedHomeDir=normalize(homeDir),currentDir=normalize(cwd);for(let depth=0;depth<=MAX_PARENT_CONFIG_SEARCH_DEPTH;depth+=1){if(currentDir===normalizedHomeDir)return;let configDir=join(currentDir,configDirName),hasRequiredChild=requiredChildFile?isFile(join(configDir,requiredChildFile)):!requiredChildDir||isDirectory(join(configDir,requiredChildDir));if(isDirectory(configDir)&&hasRequiredChild)return configDir;let parentDir=dirname(currentDir);if(parentDir===currentDir)return;currentDir=parentDir}}var MAX_PARENT_CONFIG_SEARCH_DEPTH,init_nearest_parent_config=__esm({"packages/coding-agent/dist/nearest-parent-config.js"(){MAX_PARENT_CONFIG_SEARCH_DEPTH=100}});import{readFileSync}from"node:fs";import{isAbsolute,join as join2,relative}from"node:path";function readRuntimeSnapshotMarker(packageRoot){let text;try{text=readFileSync(join2(packageRoot,RUNTIME_SNAPSHOT_MARKER),"utf8")}catch(error62){if(error62 instanceof Error&&"code"in error62&&(error62.code==="ENOENT"||error62.code==="ENOTDIR"))return;throw error62}let parsed=JSON.parse(text);if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&"installPackageDir"in parsed&&typeof parsed.installPackageDir=="string")return{buildId:parsed.buildId,installPackageDir:parsed.installPackageDir}}var RUNTIME_SNAPSHOT_MARKER,init_marker=__esm({"packages/coding-agent/dist/runtime-snapshot/marker.js"(){RUNTIME_SNAPSHOT_MARKER="runtime-snapshot.json"}});var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs2=__require("fs");function checkPathExt(path2,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return!0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path2.substr(-p.length).toLowerCase()===p)return!0}return!1}function checkStat(stat5,path2,options){return!stat5.isSymbolicLink()&&!stat5.isFile()?!1:checkPathExt(path2,options)}function isexe(path2,options,cb){fs2.stat(path2,function(er,stat5){cb(er,er?!1:checkStat(stat5,path2,options))})}function sync(path2,options){return checkStat(fs2.statSync(path2),path2,options)}}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs2=__require("fs");function isexe(path2,options,cb){fs2.stat(path2,function(er,stat5){cb(er,er?!1:checkStat(stat5,options))})}function sync(path2,options){return checkStat(fs2.statSync(path2),options)}function checkStat(stat5,options){return stat5.isFile()&&checkMode(stat5,options)}function checkMode(stat5,options){var mod=stat5.mode,uid=stat5.uid,gid=stat5.gid,myUid=options.uid!==void 0?options.uid:process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports,module){var fs2=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path2,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve5,reject){isexe(path2,options||{},function(er,is){er?reject(er):resolve5(is)})})}core(path2,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is)})}function sync(path2,options){try{return core.sync(path2,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return!1;throw er}}}});var require_which=__commonJS({"node_modules/which/which.js"(exports,module){var isWindows=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",path2=__require("path"),COLON=isWindows?";":":",isexe=require_isexe(),getNotFoundError=cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),getPathInfo=(cmd,opt)=>{let colon=opt.colon||COLON,pathEnv=cmd.match(/\//)||isWindows&&cmd.match(/\\/)?[""]:[...isWindows?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((resolve5,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve5(found):reject(getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path2.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve5(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve5,reject)=>{if(ii===pathExt.length)return resolve5(step(i+1));let ext=pathExt[ii];isexe(p+ext,{pathExt:pathExtExe},(er,is)=>{if(!er&&is)if(opt.all)found.push(p+ext);else return resolve5(p+ext);return resolve5(subStep(p,i,ii+1))})});return cb?step(0).then(res=>cb(null,res),cb):step(0)},whichSync=(cmd,opt)=>{opt=opt||{};let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[];for(let i=0;i<pathEnv.length;i++){let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path2.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j=0;j<pathExt.length;j++){let cur=p+pathExt[j];try{if(isexe.sync(cur,{pathExt:pathExtExe}))if(opt.all)found.push(cur);else return cur}catch{}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)};module.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports,module){"use strict";var pathKey=(options={})=>{let environment=options.env||process.env;return(options.platform||process.platform)!=="win32"?"PATH":Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"};module.exports=pathKey;module.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports,module){"use strict";var path2=__require("path"),which=require_which(),getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){let env=parsed.options.env||process.env,cwd=process.cwd(),hasCustomCwd=parsed.options.cwd!=null,shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd)try{process.chdir(parsed.options.cwd)}catch{}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path2.delimiter:void 0})}catch{}finally{shouldSwitchCwd&&process.chdir(cwd)}return resolved&&(resolved=path2.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports,module){"use strict";var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){return arg=arg.replace(metaCharsRegExp,"^$1"),arg}function escapeArgument(arg,doubleEscapeMetaChars){return arg=`${arg}`,arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1"),arg=`"${arg}"`,arg=arg.replace(metaCharsRegExp,"^$1"),doubleEscapeMetaChars&&(arg=arg.replace(metaCharsRegExp,"^$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports,module){"use strict";var shebangRegex=require_shebang_regex();module.exports=(string4="")=>{let match=string4.match(shebangRegex);if(!match)return null;let[path2,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path2.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){"use strict";var fs2=__require("fs"),shebangCommand=require_shebang_command();function readShebang(command){let buffer=Buffer.alloc(150),fd;try{fd=fs2.openSync(command,"r"),fs2.readSync(fd,buffer,0,150,0),fs2.closeSync(fd)}catch{}return shebangCommand(buffer.toString())}module.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports,module){"use strict";var path2=__require("path"),resolveCommand=require_resolveCommand(),escape=require_escape(),readShebang=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);let shebang=parsed.file&&readShebang(parsed.file);return shebang?(parsed.args.unshift(parsed.file),parsed.command=shebang,resolveCommand(parsed)):parsed.file}function parseNonShell(parsed){if(!isWin)return parsed;let commandFile=detectShebang(parsed),needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){let needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path2.normalize(parsed.command),parsed.command=escape.command(parsed.command),parsed.args=parsed.args.map(arg=>escape.argument(arg,needsDoubleEscapeMetaChars));let shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0}return parsed}function parse4(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=parse4}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports,module){"use strict";var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}function hookChildProcess(cp,parsed){if(!isWin)return;let originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){let err=verifyENOENT(arg1,parsed);if(err)return originalEmit.call(cp,"error",err)}return originalEmit.apply(cp,arguments)}}function verifyENOENT(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawn"):null}function verifyENOENTSync(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawnSync"):null}module.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports,module){"use strict";var cp=__require("child_process"),parse4=require_parse(),enoent=require_enoent();function spawn(command,args,options){let parsed=parse4(command,args,options),spawned=cp.spawn(parsed.command,parsed.args,parsed.options);return enoent.hookChildProcess(spawned,parsed),spawned}function spawnSync(command,args,options){let parsed=parse4(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync;module.exports._parse=parse4;module.exports._enoent=enoent}});var import_cross_spawn,init_child_process=__esm({"packages/coding-agent/dist/utils/child-process.js"(){import_cross_spawn=__toESM(require_cross_spawn(),1)}});import{homedir as homedir2}from"node:os";import{isAbsolute as isAbsolute2,join as join3,resolve as nodeResolvePath,parse,relative as relative2,sep}from"node:path";import{fileURLToPath}from"node:url";function normalizeWindowsShellPath(filePath){if(!filePath.startsWith("/")||filePath.startsWith("//")||filePath.includes("\\"))return filePath;let match=filePath.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!match)return filePath;let suffix=match[2]?.replaceAll("/","\\");return`${match[1].toUpperCase()}:\\${suffix??""}`}function normalizePath(input2,options={}){let normalized=options.trim?input2.trim():input2;if(options.normalizeUnicodeSpaces&&(normalized=normalized.replace(UNICODE_SPACES," ")),options.stripAtPrefix&&normalized.startsWith("@")&&(normalized=normalized.slice(1)),process.platform==="win32"&&(normalized=normalizeWindowsShellPath(normalized)),options.expandTilde??!0){let home=options.homeDir??homedir2();if(normalized==="~")return home;if(normalized.startsWith("~/")||process.platform==="win32"&&normalized.startsWith("~\\"))return join3(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath(normalized):normalized}var UNICODE_SPACES,init_paths=__esm({"packages/coding-agent/dist/utils/paths.js"(){init_child_process();UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g}});function splitBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function stripBom(content){return splitBom(content).text}var init_text=__esm({"packages/coding-agent/dist/utils/text.js"(){}});import{accessSync,constants,existsSync,readFileSync as readFileSync2,realpathSync}from"fs";import{homedir as homedir3,userInfo}from"os";import{basename,dirname as dirname2,join as join4,resolve,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath2}from"url";function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname2(dir);){if(existsSync(join4(dir,"package.json"))){let parent=dirname2(dir);return basename(dir)==="dist"&&existsSync(join4(parent,"package.json"))?parent:dir}dir=dirname2(dir)}return startDir}function getPackageDir(){let envDir=envValue("PACKAGE_DIR");return envDir?normalizePath(envDir):isBunBinary?dirname2(process.execPath):(nodePackageDir??=findNodePackageDir(__dirname),nodePackageDir)}function getPackageJsonPath(){return join4(getPackageDir(),"package.json")}function resolveAgentDir(cwd,homeDir,envDir){if(envDir)return normalizePath(envDir,{homeDir});if(CONFIG_FLAT_LAYOUT)return findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,void 0,FLAT_LAYOUT_SENTINEL)??join4(homeDir,CONFIG_DIR_NAME);let projectConfigDir=findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,"agent");return projectConfigDir?join4(projectConfigDir,"agent"):join4(homeDir,CONFIG_DIR_NAME,"agent")}function isGuardedTestRun(env){return env.SENPI_TEST_AGENT_DIR_GUARD==="1"}function realHomeDir(){try{return userInfo().homedir}catch{return}}function assertAgentDirAllowedInTests(agentDir,activeConfigDirName,env=process.env){if(!isGuardedTestRun(env)||env.SENPI_TEST_USE_REAL_AGENT_DIR==="1")return;let home=realHomeDir();if(!home)return;let target=resolve(agentDir);for(let configDir of new Set([...KNOWN_BRAND_CONFIG_DIRS,activeConfigDirName])){let root=join4(home,configDir);if(target===root||target.startsWith(root+sep2))throw new RealAgentDirInTestError(target)}}function getAgentDir(){let agentDir=resolveAgentDir(process.cwd(),homedir3(),envValue("CODING_AGENT_DIR"));return assertAgentDirAllowedInTests(agentDir,CONFIG_DIR_NAME),agentDir}var __filename,__dirname,isBunBinary,isBunRuntime,isBundledNode,nodePackageDir,pkg,piConfigName,BRAND,PACKAGE_NAME,APP_NAME,APP_COMMAND,APP_TITLE,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,VERSION,DISPLAY_VERSION,ENV_PREFIX,ENV_AGENT_DIR,ENV_SESSION_DIR,FLAT_LAYOUT_SENTINEL,KNOWN_BRAND_CONFIG_DIRS,RealAgentDirInTestError,init_config=__esm({"packages/coding-agent/dist/config.js"(){init_bun_global_launcher();init_brand();init_nearest_parent_config();init_marker();init_child_process();init_paths();init_text();__filename=fileURLToPath2(import.meta.url),__dirname=dirname2(__filename),isBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),isBunRuntime=!!process.versions.bun,isBundledNode=!0;pkg={};try{pkg=JSON.parse(stripBom(readFileSync2(getPackageJsonPath(),"utf-8")))}catch(e){if(e.code!=="ENOENT")throw e}piConfigName=pkg.piConfig?.name,BRAND=brandProfile(),PACKAGE_NAME=pkg.name||"@earendil-works/pi-coding-agent",APP_NAME=BRAND?.name||piConfigName||"pi",APP_COMMAND=BRAND?.command??APP_NAME,APP_TITLE=BRAND?.name||(piConfigName?APP_NAME:"\u03C0"),CONFIG_DIR_NAME=BRAND?.configDir||pkg.piConfig?.configDir||".pi",CONFIG_FLAT_LAYOUT=BRAND?.flatLayout===!0,VERSION=pkg.version||"0.0.0",DISPLAY_VERSION=BRAND?.displayVersion||VERSION,ENV_PREFIX=BRAND?.envPrefix||APP_NAME.toUpperCase(),ENV_AGENT_DIR=`${ENV_PREFIX}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`,FLAT_LAYOUT_SENTINEL="settings.json";KNOWN_BRAND_CONFIG_DIRS=[".senpi",".omo",".pi"],RealAgentDirInTestError=class extends Error{constructor(agentDir){super(`Refusing to use the real agent directory ${agentDir} from a test run. Point <BRAND>_CODING_AGENT_DIR at a temp dir, or set SENPI_TEST_USE_REAL_AGENT_DIR=1 to opt in.`),this.name="RealAgentDirInTestError",this.agentDir=agentDir}}}});var require_signals=__commonJS({"node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/signal-exit/index.js"(exports,module){var process2=global.process,processOk=function(process3){return process3&&typeof process3=="object"&&typeof process3.removeListener=="function"&&typeof process3.emit=="function"&&typeof process3.reallyExit=="function"&&typeof process3.listeners=="function"&&typeof process3.kill=="function"&&typeof process3.pid=="number"&&typeof process3.on=="function"};processOk(process2)?(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process2.__signal_exit_emitter__?emitter=process2.__signal_exit_emitter__:(emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch{}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process2.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process2.kill(process2.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch{return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process2.exitCode=code||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode))},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process2.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});import{stat}from"node:fs/promises";async function openLockDatabase(lockPath){if(typeof globalThis.Bun<"u"){let{Database}=await import("bun:sqlite"),database2=new Database(lockPath,{create:!0});return{exec:sql=>database2.exec(sql),close:()=>database2.close(!1)}}let{DatabaseSync}=await import("node:sqlite"),database=new DatabaseSync(lockPath);return{exec:sql=>database.exec(sql),close:()=>database.close()}}async function acquireOwnershipSafeLock(lockPath,options={}){let retries=options.retries??DEFAULT_RETRIES,deadline=Date.now()+retries.retries*retries.maxTimeout;for(;;){await rejectLegacyDirectory(lockPath);let busyMs=Math.max(1,Math.min(retries.maxTimeout,deadline-Date.now())),database;try{database=await openLockDatabase(lockPath),database.exec(`PRAGMA busy_timeout = ${busyMs}; BEGIN EXCLUSIVE;`);let released=!1,held=database;return async()=>{if(!released){released=!0;try{held.exec("COMMIT;")}finally{held.close()}}}}catch(error62){try{database?.close()}catch{}if(await rejectLegacyDirectory(lockPath),isBusy(error62)&&Date.now()<deadline){await new Promise(resolve5=>setTimeout(resolve5,Math.min(retries.minTimeout,Math.max(1,deadline-Date.now()))));continue}throw error62}}}async function rejectLegacyDirectory(lockPath){try{if((await stat(lockPath)).isDirectory())throw new LegacyLockArtifactError(lockPath)}catch(error62){if(error62 instanceof LegacyLockArtifactError||error62.code!=="ENOENT")throw error62}}function isBusy(error62){let message=error62 instanceof Error?error62.message:String(error62);return/busy|locked/i.test(message)||error62?.code==="SQLITE_BUSY"}var LegacyLockArtifactError,DEFAULT_RETRIES,init_ownership_safe_lock=__esm({"packages/coding-agent/dist/modes/rpc/ownership-safe-lock.js"(){LegacyLockArtifactError=class extends Error{constructor(lockPath){super(`Legacy lock directory is present at ${lockPath}`),this.code="ELEGACY_LOCK_ARTIFACT",this.name="LegacyLockArtifactError",this.lockPath=lockPath}},DEFAULT_RETRIES={retries:100,minTimeout:20,maxTimeout:100}}});import{execFile,execFileSync}from"node:child_process";function processStartTimeMs(identity){if(/^\d+$/.test(identity)){let parsed2=Number((BigInt(identity)-WINDOWS_FILETIME_EPOCH)/10000n);return Number.isFinite(parsed2)?parsed2:void 0}let localIdentity=identity.trim(),korean=/^(\d{4})\uB144\s+(\d{1,2})\uC6D4\s+(\d{1,2})\uC77C\s+[\uC6D4\uD654\uC218\uBAA9\uAE08\uD1A0\uC77C]\uC694\uC77C\s+(\d{1,2})\uC2DC\s+(\d{1,2})\uBD84\s+(\d{1,2})\uCD08$/.exec(localIdentity),japanese=/^[\u65E5\u6708\u706B\u6C34\u6728\u91D1\u571F](?:\u66DC\u65E5)?\s+(\d{1,2})\/\s*(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(localIdentity),parts=korean?korean.slice(1):japanese?[japanese[6],japanese[1],japanese[2],japanese[3],japanese[4],japanese[5]]:void 0;if(parts===void 0){let parsed2=Date.parse(identity);return Number.isFinite(parsed2)?parsed2:void 0}let[year=NaN,month=NaN,day=NaN,hour=NaN,minute=NaN,second=NaN]=parts.map(Number),parsed=new Date(year,month-1,day,hour,minute,second,0);return parsed.getFullYear()===year&&parsed.getMonth()===month-1&&parsed.getDate()===day&&parsed.getHours()===hour&&parsed.getMinutes()===minute&&parsed.getSeconds()===second?parsed.getTime():void 0}function sameProcessStartMs(recorded,observed){return recorded!==void 0&&observed!==void 0&&Number.isFinite(recorded)&&Number.isFinite(observed)&&Math.abs(recorded-observed)<=PROCESS_START_TOLERANCE_MS}function parseDaemonPidFile(text){let parsed;try{parsed=JSON.parse(text)}catch(error62){if(error62 instanceof SyntaxError)return;throw error62}let unguarded=parsed!==null&&isRecord(parsed)&&parsed.processStartTime===null;if(!(!isRecord(parsed)||typeof parsed.pid!="number"||!unguarded&&typeof parsed.processStartTime!="string")&&!(!Number.isInteger(parsed.pid)||parsed.pid<=0)){if(unguarded)return{pid:parsed.pid,processStartTime:null};if(!(typeof parsed.processStartTime!="string"||parsed.processStartTime.trim()===""))return{pid:parsed.pid,processStartTime:parsed.processStartTime}}}async function readProcessIdentity(pid,platform=process.platform,timeoutMs,isLive=processIsLive,timeZone){let command=platform==="win32"?{executable:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`$process = Get-CimInstance Win32_Process -Filter "ProcessId=${String(pid)}" -ErrorAction Stop; if ($null -eq $process) { Write-Output '__SENPI_ABSENT__'; exit 0 }; $process.CreationDate.ToFileTimeUtc().ToString("D", [Globalization.CultureInfo]::InvariantCulture)`]}:{executable:"ps",args:["-o","stat=,lstart=","-p",String(pid)]};return new Promise(resolve5=>{let effectiveTimeoutMs=timeoutMs??(platform==="win32"?1e3:void 0);execFile(command.executable,command.args,{windowsHide:!0,...effectiveTimeoutMs===void 0?{}:{timeout:effectiveTimeoutMs},...platform==="win32"&&timeZone===void 0?{}:{env:{...process.env,LC_ALL:"C",LANG:"C",...timeZone?{TZ:timeZone}:{}}}},(error62,stdout)=>{if(error62){let code="code"in error62?error62.code:void 0;if(platform!=="win32"&&code===1||!isLive(pid)){resolve5({kind:"absent"});return}resolve5({kind:"error",error:error62});return}let snapshot=stdout.trim();if(snapshot==="__SENPI_ABSENT__")return resolve5({kind:"absent"});let state3=platform==="win32"?"":snapshot.split(/\s+/,1)[0]??"";if(state3.startsWith("Z"))return resolve5({kind:"absent"});let output2=platform==="win32"?snapshot:snapshot.slice(state3.length).trim();if(!output2||platform==="win32"&&!/^\d+$/.test(output2))return resolve5({kind:"error",error:new Error("invalid process identity output")});resolve5({kind:"present",identity:timeZone&&platform!=="win32"?`${output2} UTC`:output2})}).once("error",error62=>resolve5({kind:"error",error:error62}))})}async function readProcessStartTime(pid,platform=process.platform,timeoutMs){return readProcessIdentity(pid,platform,timeoutMs).then(result=>{if(result.kind==="error")throw result.error;return result.kind==="present"?result.identity:void 0})}function processIsLive(pid){try{return process.kill(pid,0),!0}catch(error62){if(isNodeErrorCode(error62,"ESRCH"))return!1;if(isNodeErrorCode(error62,"EPERM"))return!0;throw error62}}async function waitForStartTime(pid,timeoutMs,readStartTime=readProcessStartTime,isLive=processIsLive){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){let startTime;try{startTime=await readStartTime(pid)}catch{}if(startTime)return startTime;await delay(20)}if(!isLive(pid))throw new Error(`spawned daemon pid ${pid} had no process start time`)}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode(error62,code){return error62 instanceof Error&&"code"in error62&&error62.code===code}var WINDOWS_FILETIME_EPOCH,PROCESS_START_TOLERANCE_MS,init_process_identity=__esm({"packages/coding-agent/dist/utils/process-identity.js"(){WINDOWS_FILETIME_EPOCH=116444736000000000n,PROCESS_START_TOLERANCE_MS=3e3}});import{createHmac,timingSafeEqual}from"node:crypto";function launchProofRecordRefusal(id){return{...id===void 0?{}:{id},type:"response",command:RPC_LAUNCH_PROOF_RECORD,success:!1,error:"reserved_record",errorCode:"reserved_record"}}function rpcAuthProof(key,label,...parts){return createHmac("sha256",key).update([`senpi-rpc-${label}`,...parts].join(`
16
- `),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}var RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,RpcEndpointAuthError,init_rpc_auth_proof=__esm({"packages/coding-agent/dist/modes/rpc/rpc-auth-proof.js"(){RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,RPC_LAUNCH_PROOF_RECORD="launch_proven";RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}}}});function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record3=request;return record3.type==="warm"||record3.type==="authenticate"||record3.type===RPC_LAUNCH_PROOF_RECORD?!0:record3[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record3.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record3=request;if(record3[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record3.type))return;let hold=record3[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}var OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,HOLD_HOST_FIELD,OBSERVING_COMMANDS,init_host_observe_request=__esm({"packages/coding-agent/dist/modes/rpc/host-observe-request.js"(){init_host_identity_env();init_rpc_auth_proof();OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"])}});import{StringDecoder}from"node:string_decoder";import{isBigIntObject,isBooleanObject,isNumberObject,isStringObject}from"node:util/types";function isStackOverflow(cause){return cause instanceof RangeError&&cause.message.startsWith("Maximum call stack size exceeded")}function jsonStep(input2,key){let value=input2;if(typeof value=="object"&&value!==null||typeof value=="function"||typeof value=="bigint"){let toJSON=value.toJSON;typeof toJSON=="function"&&(value=toJSON.call(value,key))}if(typeof value=="object"&&value!==null){if(isNumberObject(value))value=+value;else if(isStringObject(value))value=String(value);else if(isBooleanObject(value))value=Boolean.prototype.valueOf.call(value);else if(isBigIntObject(value))throw new TypeError("Do not know how to serialize a BigInt")}if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");return typeof value=="number"?Number.isFinite(value)?Object.is(value,-0)?0:value:null:typeof value>"u"||typeof value=="function"||typeof value=="symbol"?OMITTED:value}function jsonNormalValue(input2){let ancestors=new Set,stack=[],enter=(input3,key)=>{let value=jsonStep(input3,key);if(typeof value!="object"||value===null)return value;if(ancestors.has(value))throw new TypeError("Converting circular structure to JSON");if(ancestors.add(value),Array.isArray(value)){let out2=[];return stack.push({source:value,out:out2,keys:void 0,length:value.length,index:0}),out2}let keys=Object.keys(value),out={};return stack.push({source:value,out,keys,length:keys.length,index:0}),out},root=enter(input2,"");for(;stack.length>0;){let frame=stack[stack.length-1];if(frame.index===frame.length){ancestors.delete(frame.source),stack.pop();continue}let index=frame.index++;if(frame.keys===void 0){let child2=enter(frame.source[index],String(index));frame.out.push(child2===OMITTED?null:child2);continue}let name=frame.keys[index],child=enter(frame.source[name],name);child!==OMITTED&&Object.defineProperty(frame.out,name,{value:child,enumerable:!0,configurable:!0,writable:!0})}return root===OMITTED?void 0:root}function normalJsonText(root){let parts=[],stack=[],open4=value=>{typeof value!="object"||value===null?parts.push(JSON.stringify(value)):Array.isArray(value)?(parts.push("["),stack.push({value,index:0})):(parts.push("{"),stack.push({value,keys:Object.keys(value),index:0}))};for(open4(root);stack.length>0;){let frame=stack[stack.length-1],{keys}=frame,length=keys===void 0?frame.value.length:keys.length;if(frame.index===length){parts.push(keys===void 0?"]":"}"),stack.pop();continue}let index=frame.index++;if(index>0&&parts.push(","),keys===void 0)open4(frame.value[index]);else{let name=keys[index];parts.push(JSON.stringify(name),":"),open4(frame.value[name])}}return parts.join("")}function legacyJsonText(value){try{return JSON.stringify(value)}catch(cause){if(!isStackOverflow(cause))throw cause;let normal=jsonNormalValue(value);return normal===void 0?void 0:normalJsonText(normal)}}function serializeJsonLine(value){return`${legacyJsonText(value)}
16
+ `),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}var RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,RpcEndpointAuthError,init_rpc_auth_proof=__esm({"packages/coding-agent/dist/modes/rpc/rpc-auth-proof.js"(){RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,RPC_LAUNCH_PROOF_RECORD="launch_proven";RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}}}});function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record3=request;return record3.type==="warm"||record3.type==="park_session"||record3.type==="authenticate"||record3.type===RPC_LAUNCH_PROOF_RECORD?!0:record3[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record3.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record3=request;if(record3[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record3.type))return;let hold=record3[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}var OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,HOLD_HOST_FIELD,OBSERVING_COMMANDS,init_host_observe_request=__esm({"packages/coding-agent/dist/modes/rpc/host-observe-request.js"(){init_host_identity_env();init_rpc_auth_proof();OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"])}});import{StringDecoder}from"node:string_decoder";import{isBigIntObject,isBooleanObject,isNumberObject,isStringObject}from"node:util/types";function isStackOverflow(cause){return cause instanceof RangeError&&cause.message.startsWith("Maximum call stack size exceeded")}function jsonStep(input2,key){let value=input2;if(typeof value=="object"&&value!==null||typeof value=="function"||typeof value=="bigint"){let toJSON=value.toJSON;typeof toJSON=="function"&&(value=toJSON.call(value,key))}if(typeof value=="object"&&value!==null){if(isNumberObject(value))value=+value;else if(isStringObject(value))value=String(value);else if(isBooleanObject(value))value=Boolean.prototype.valueOf.call(value);else if(isBigIntObject(value))throw new TypeError("Do not know how to serialize a BigInt")}if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");return typeof value=="number"?Number.isFinite(value)?Object.is(value,-0)?0:value:null:typeof value>"u"||typeof value=="function"||typeof value=="symbol"?OMITTED:value}function jsonNormalValue(input2){let ancestors=new Set,stack=[],enter=(input3,key)=>{let value=jsonStep(input3,key);if(typeof value!="object"||value===null)return value;if(ancestors.has(value))throw new TypeError("Converting circular structure to JSON");if(ancestors.add(value),Array.isArray(value)){let out2=[];return stack.push({source:value,out:out2,keys:void 0,length:value.length,index:0}),out2}let keys=Object.keys(value),out={};return stack.push({source:value,out,keys,length:keys.length,index:0}),out},root=enter(input2,"");for(;stack.length>0;){let frame=stack[stack.length-1];if(frame.index===frame.length){ancestors.delete(frame.source),stack.pop();continue}let index=frame.index++;if(frame.keys===void 0){let child2=enter(frame.source[index],String(index));frame.out.push(child2===OMITTED?null:child2);continue}let name=frame.keys[index],child=enter(frame.source[name],name);child!==OMITTED&&Object.defineProperty(frame.out,name,{value:child,enumerable:!0,configurable:!0,writable:!0})}return root===OMITTED?void 0:root}function normalJsonText(root){let parts=[],stack=[],open4=value=>{typeof value!="object"||value===null?parts.push(JSON.stringify(value)):Array.isArray(value)?(parts.push("["),stack.push({value,index:0})):(parts.push("{"),stack.push({value,keys:Object.keys(value),index:0}))};for(open4(root);stack.length>0;){let frame=stack[stack.length-1],{keys}=frame,length=keys===void 0?frame.value.length:keys.length;if(frame.index===length){parts.push(keys===void 0?"]":"}"),stack.pop();continue}let index=frame.index++;if(index>0&&parts.push(","),keys===void 0)open4(frame.value[index]);else{let name=keys[index];parts.push(JSON.stringify(name),":"),open4(frame.value[name])}}return parts.join("")}function legacyJsonText(value){try{return JSON.stringify(value)}catch(cause){if(!isStackOverflow(cause))throw cause;let normal=jsonNormalValue(value);return normal===void 0?void 0:normalJsonText(normal)}}function serializeJsonLine(value){return`${legacyJsonText(value)}
17
17
  `}function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
18
18
  `,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
19
19
  `,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}var OMITTED,MAX_RPC_LINE_CHARACTERS,init_jsonl=__esm({"packages/coding-agent/dist/modes/rpc/jsonl.js"(){OMITTED=Symbol("omitted");MAX_RPC_LINE_CHARACTERS=16*1024*1024}});import{createHash as createHash2,randomBytes as randomBytes2,timingSafeEqual as timingSafeEqual2}from"node:crypto";import{constants as constants2}from"node:fs";import{chmod as chmod2,link,mkdir as mkdir2,open,readFile as readFile4,realpath,rename as rename2,unlink,writeFile as writeFile3}from"node:fs/promises";import{basename as basename6,dirname as dirname7,join as join12,win32 as win323}from"node:path";function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path2){let existing=await readSecretEntry(path2);if(existing?.length===SOCKET_SECRET_BYTES)return existing;await mkdir2(dirname7(path2),{recursive:!0,mode:448});let release=await acquireOwnershipSafeLock(await socketSecretLockPath(path2));try{let current=await readSecretEntry(path2);if(current?.length===SOCKET_SECRET_BYTES)return current;if(process.platform==="win32")return await writeSocketSecretInPlace(path2);let candidate=randomBytes2(SOCKET_SECRET_BYTES);if(current===void 0){if(await publishSocketSecretIfAbsent(path2,candidate)==="published")return candidate;let winner=await readSecretEntry(path2);if(winner?.length===SOCKET_SECRET_BYTES)return winner;throw new Error(`RPC socket secret is invalid and was not replaced: ${path2}`)}return await replaceSocketSecret(path2,candidate),candidate}finally{await release()}}async function readSecretEntry(path2){let handle;try{handle=await open(path2,constants2.O_RDONLY|(constants2.O_NOFOLLOW??0))}catch(error62){if(isNodeErrorCode3(error62,"ENOENT"))return;throw isNodeErrorCode3(error62,"ELOOP")?new Error(`RPC socket secret is not a regular file: ${path2}`):error62}try{if(!(await handle.stat()).isFile())throw new Error(`RPC socket secret is not a regular file: ${path2}`);let buffer=Buffer.alloc(SOCKET_SECRET_BYTES+1),length=0;for(;length<buffer.length;){let{bytesRead}=await handle.read(buffer,length,buffer.length-length,null);if(bytesRead===0)break;length+=bytesRead}return buffer.subarray(0,length)}finally{await handle.close()}}async function createSocketSecret(path2){if(process.platform==="win32")return writeSocketSecretInPlace(path2);await mkdir2(dirname7(path2),{recursive:!0,mode:448});let candidate=randomBytes2(SOCKET_SECRET_BYTES);if(await readSecretEntry(path2)===void 0&&await publishSocketSecretIfAbsent(path2,candidate)==="published")return candidate;let winner=await readSecretEntry(path2);if(winner?.length!==SOCKET_SECRET_BYTES)throw new Error(`RPC socket secret is invalid and was not replaced: ${path2}`);return winner}async function publishSocketSecretIfAbsent(path2,candidate){let staging=stagingPath(path2);await writeStaging(staging,candidate);try{return await link(staging,path2),await syncDirectory(dirname7(path2)),"published"}catch(error62){if(isNodeErrorCode3(error62,"EEXIST"))return"collision";throw error62}finally{await unlink(staging).catch(error62=>{if(!isNodeErrorCode3(error62,"ENOENT"))throw error62})}}async function writeStaging(staging,candidate){let handle=await open(staging,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL|(constants2.O_NOFOLLOW??0),384),failure2;try{await handle.chmod(384);let offset=0;for(;offset<candidate.length;){let{bytesWritten}=await handle.write(candidate,offset,candidate.length-offset,null);if(bytesWritten===0)throw new Error(`short write to the RPC socket secret staging file: ${staging}`);offset+=bytesWritten}await handle.sync()}catch(error62){failure2=error62}if(await handle.close().catch(error62=>{failure2??=error62}),failure2!==void 0)throw await unlink(staging).catch(()=>{}),failure2}async function syncDirectory(dir){let handle=await open(dir,constants2.O_RDONLY);try{await handle.sync()}finally{await handle.close()}}async function socketSecretLockPath(path2){let lockPath=join12(await realpath(dirname7(path2)),`${basename6(path2)}.publish.lock`),handle=await open(lockPath,constants2.O_RDONLY|constants2.O_CREAT|(constants2.O_NOFOLLOW??0),384);try{if(!(await handle.stat()).isFile())throw new Error(`RPC socket secret lock is not a regular file: ${lockPath}`)}finally{await handle.close()}return lockPath}async function replaceSocketSecret(path2,candidate){let staging=stagingPath(path2);await writeStaging(staging,candidate);try{await rename2(staging,path2)}catch(error62){throw await unlink(staging).catch(()=>{}),error62}await syncDirectory(dirname7(path2))}function stagingPath(path2){return join12(dirname7(path2),`.${basename6(path2)}.stage-${process.pid}-${randomBytes2(8).toString("hex")}`)}async function writeSocketSecretInPlace(path2){await mkdir2(dirname7(path2),{recursive:!0});let secret=randomBytes2(SOCKET_SECRET_BYTES);return await writeFile3(path2,secret,{mode:384}),await chmod2(path2,384),secret}async function readSocketSecret(path2){let secret=await readFile4(path2);if(secret.length!==SOCKET_SECRET_BYTES)throw new Error(`invalid RPC socket secret: ${path2}`);return secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash2("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual2(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode3(error62,code){return error62 instanceof Error&&"code"in error62&&error62.code===code}var WINDOWS_PIPE_PREFIX,SOCKET_SECRET_BYTES,SOCKET_SECRET_SUFFIX,SOCKET_SECRET_FILE_ENV,SOCKET_HANDSHAKE_TIMEOUT_MS,init_socket_transport=__esm({"packages/coding-agent/dist/modes/rpc/socket-transport.js"(){init_ownership_safe_lock();WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3}});import{randomBytes as randomBytes3,randomUUID as randomUUID3}from"node:crypto";import{constants as constants3,unlinkSync as unlinkSync2}from"node:fs";import*as fs from"node:fs/promises";import{join as join13}from"node:path";async function checkRpcKeyDirectory(path2,privateKeys=!1){let checked=privateKeys?path2:await fs.realpath(path2),problem=keyDirectoryProblem(await fs.lstat(checked),checked,privateKeys);if(problem!==void 0)throw new RpcEndpointAuthError("unsafe_key_record",`${checked} ${problem}`)}function keyDirectoryProblem(info,path2,privateKeys){if(!info.isDirectory())return"is not a directory";if(info.uid!==process.getuid?.())return"is not owned by this user";let mode=info.mode&4095;return privateKeys?mode===448?void 0:`must be mode 0700 (is 0${mode.toString(8)}); run: chmod 700 ${path2}`:(mode&18)===0?void 0:`is writable by group or others; run: chmod go-w ${path2}`}async function checkRpcKeyParents(root){await checkRpcKeyDirectory(root),await checkRpcKeyDirectory(join13(root,"rpc"))}async function readRpcKeyRecord(root,launchId){if(!RPC_LAUNCH_ID.test(launchId))throw new RpcEndpointAuthError("unsafe_key_record",`invalid launch id under ${root}`);let path2=join13(root,"rpc","keys",launchId);try{await checkRpcKeyParents(root),await checkRpcKeyDirectory(join13(root,"rpc","keys"),!0);let handle=await fs.open(path2,constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384||info.size>MAX_KEY_RECORD_BYTES)throw new RpcEndpointAuthError("unsafe_key_record",path2);let record3=authRecord(JSON.parse(await handle.readFile("utf8")));if(record3?.version!==1||record3.launch_id!==launchId||typeof record3.key!="string"||!RPC_AUTH_HEX.test(record3.key))throw new RpcEndpointAuthError("unsafe_key_record",path2);return record3}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause instanceof RpcEndpointAuthError?cause:new RpcEndpointAuthError("unsafe_key_record",path2,{cause})}}var MAX_KEY_RECORD_BYTES,RpcPublicEndpoint,init_rpc_public_key=__esm({"packages/coding-agent/dist/modes/rpc/rpc-public-key.js"(){init_process_identity();init_rpc_auth_proof();MAX_KEY_RECORD_BYTES=4096;RpcPublicEndpoint=class{constructor(agentDir,endpoint){this.key=randomBytes3(32),this.launchId=randomUUID3(),this.publication=Promise.withResolvers(),this.created=!1,this.exitCleanup=()=>{if(this.created)try{unlinkSync2(this.recordPath)}catch(cause){cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"||process.stderr.write(`senpi rpc host: could not remove own endpoint key record
@@ -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,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionRunner,FooterComponent,InteractiveMode,JOB_WIDGET_STATE_EVENT,KILL_GUARD_MODULE_URL,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ReservedCustodyKey,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TextTap,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,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,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,kernelToolsStorage,killGuardProtectedPids,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSkillBlock,prepareBranchEntries,readKillGuardSetting,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-X4XWAB3J.js";import"./chunks/chunk-TGW4R7SI.js";import{RELOCATION_TOOL_NAMES,SESSION_CONTROL_DELIVERY_TYPE,isSessionControlDeliveryDetails,sessionControlRemoteOriginOf,sessionControlSenderOf}from"./chunks/chunk-HI5JSLG5.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-ARUV3US4.js";import"./chunks/chunk-3IYEGHBI.js";import"./chunks/chunk-RYPM5BZQ.js";import"./chunks/chunk-NLYT7BND.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-FAFIGBUD.js";import"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-436DNN4Z.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-BELNOPAI.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-GTJJ73DE.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-VD7AKTGP.js";import{AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,UserMessageComponent,copyToClipboard}from"./chunks/chunk-7MN7YNO5.js";import"./chunks/chunk-H33A33M4.js";import"./chunks/chunk-TQHNFP77.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-ZUQCYIRY.js";import{SecretInputUnavailableError}from"./chunks/chunk-HKCFMDJN.js";import"./chunks/chunk-3Q5ZENSD.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-Y3TMJV3J.js";import"./chunks/chunk-O3FG6HML.js";import"./chunks/chunk-MOVB6H22.js";import{registerRpcRemoteSource}from"./chunks/chunk-NH7SYIGN.js";import"./chunks/chunk-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-SOMFLLPD.js";import{readOwnFootprint,readProcessFootprint}from"./chunks/chunk-MTQQ2VQH.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest}from"./chunks/chunk-L6NRDUWJ.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-THYEZBUG.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunks/chunk-Y7Z7XPUF.js";import{parseArgs}from"./chunks/chunk-IEY2SL46.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-I5ASHSLZ.js";import"./chunks/chunk-2CNSCMYC.js";import"./chunks/chunk-DX43FSQT.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-YPAQXRP3.js";import"./chunks/chunk-R2Z7CX77.js";import"./chunks/chunk-UCXBDE6R.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-YI6KRJDC.js";import"./chunks/chunk-DBQBJTMF.js";import"./chunks/chunk-SF4MQDKZ.js";import"./chunks/chunk-EJB5E2JK.js";import"./chunks/chunk-RCHIMH7N.js";import"./chunks/chunk-GILDYS3O.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-C4AHHZ6P.js";import"./chunks/chunk-J7FW7MED.js";import"./chunks/chunk-2EJ4BGBM.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-MSDBBOB2.js";import"./chunks/chunk-WHQ2QPP5.js";import"./chunks/chunk-J2NGJKXL.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-NJ43NBSP.js";import"./chunks/chunk-KDUJCDLM.js";import{decideKillGuardRequest}from"./chunks/chunk-6APXZK7W.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-2IKL4F24.js";import"./chunks/chunk-KJR3XXMI.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-AC72EWI5.js";import"./chunks/chunk-RQFD6LG2.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getJobWidgetState,registerJobWidgetSource,setJobWidgetAuthorResolver,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-2U6HXWXS.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-LPYBKMPT.js";import{activateKillGuardRuntime,activeKillGuardEnvironment,getPowerShellConfig,getShellConfig,releaseKillGuardRuntime,withBundledBunCommands}from"./chunks/chunk-33MZJTQ3.js";import"./chunks/chunk-V5FSENW6.js";import"./chunks/chunk-R7J5TEYK.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-WXYMAUFX.js";import{KILL_GUARD_TAG}from"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-XH2MWTXA.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-ZG3MNTNX.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-UAOOH2V7.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-OH5TKHW7.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-3IYWH6RO.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-E266ORGA.js";import"./chunks/chunk-T2SMQPRE.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-IHES3JES.js";import"./chunks/chunk-5XHOHZIR.js";import"./chunks/chunk-HW6AAS3R.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-SODMQEHO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-EYSV6A7S.js";import"./chunks/chunk-MIENF2YK.js";import"./chunks/chunk-OXNWERO4.js";import"./chunks/chunk-44BJPS5I.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.js";import"./chunks/chunk-RFFMEA4B.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,JOB_WIDGET_STATE_EVENT,KILL_GUARD_MODULE_URL,KILL_GUARD_TAG,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,RELOCATION_TOOL_NAMES,REQUIRED_COMPACTION_ERROR_MESSAGE,REQUIRED_HOST_CAPABILITIES,RequiredCompactionError,ReservedCustodyKey,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SecretInputUnavailableError,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,TextTap,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,activateKillGuardRuntime,activeKillGuardEnvironment,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,decideKillGuardRequest,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findReservedKeywordRuns,findReservedKeywordSpans,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getJobWidgetState,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,killGuardProtectedPids,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readKillGuardSetting,readOwnFootprint,readProcessFootprint,readStoredCredential,registerJobWidgetSource,registerReadClassifier,registerRpcRemoteSource,releaseKillGuardRuntime,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionControlRemoteOriginOf,sessionControlSenderOf,sessionEntryToContextMessages,setJobWidgetAuthorResolver,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{AgentSession,AgentSessionRuntime,ArminComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionRunner,FooterComponent,InteractiveMode,JOB_WIDGET_STATE_EVENT,KILL_GUARD_MODULE_URL,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ReservedCustodyKey,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TextTap,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageSelectorComponent,buildNoticeBox,calculateContextTokens,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,connectWebViewService,convertToPng,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,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,kernelToolsStorage,killGuardProtectedPids,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSkillBlock,prepareBranchEntries,readKillGuardSetting,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-YCPURLPU.js";import"./chunks/chunk-XH24X5B2.js";import{RELOCATION_TOOL_NAMES,SESSION_CONTROL_DELIVERY_TYPE,isSessionControlDeliveryDetails,sessionControlRemoteOriginOf,sessionControlSenderOf}from"./chunks/chunk-74IB3JPP.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-QATU6BBC.js";import"./chunks/chunk-3IYEGHBI.js";import"./chunks/chunk-RYPM5BZQ.js";import"./chunks/chunk-NLYT7BND.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-TUEZNIBK.js";import"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-XI6THO4F.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-UOZDDYBN.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-GTJJ73DE.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-VD7AKTGP.js";import{AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,UserMessageComponent,copyToClipboard}from"./chunks/chunk-7MN7YNO5.js";import"./chunks/chunk-M2VJVJMK.js";import"./chunks/chunk-TQHNFP77.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-ZUQCYIRY.js";import{SecretInputUnavailableError}from"./chunks/chunk-HKCFMDJN.js";import"./chunks/chunk-3Q5ZENSD.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-Y3TMJV3J.js";import"./chunks/chunk-O3FG6HML.js";import"./chunks/chunk-MOVB6H22.js";import{registerRpcRemoteSource}from"./chunks/chunk-DLPV4B3R.js";import"./chunks/chunk-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-SOMFLLPD.js";import{readOwnFootprint,readProcessFootprint}from"./chunks/chunk-MTQQ2VQH.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,classifyEndpointLiveness,endpointProbeTimeoutMs,ensureHost,handoffHost,loadHostLaunchSpec,parseHostLaunchSpec,readAllHostStatus,readHostStatus,runHostCommand,runHostRequest}from"./chunks/chunk-OF3XVGG4.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-Q4G5DECT.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunks/chunk-DZQA5LVN.js";import{parseArgs}from"./chunks/chunk-IEY2SL46.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-4JMGWVRH.js";import"./chunks/chunk-E5O4SP5I.js";import"./chunks/chunk-DX43FSQT.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-47T6YMI2.js";import"./chunks/chunk-R2Z7CX77.js";import"./chunks/chunk-UCXBDE6R.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-YI6KRJDC.js";import"./chunks/chunk-VUY4BZDI.js";import"./chunks/chunk-SF4MQDKZ.js";import"./chunks/chunk-EJB5E2JK.js";import"./chunks/chunk-RCHIMH7N.js";import"./chunks/chunk-GILDYS3O.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-C4AHHZ6P.js";import"./chunks/chunk-J7FW7MED.js";import"./chunks/chunk-2EJ4BGBM.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-MSDBBOB2.js";import"./chunks/chunk-WHQ2QPP5.js";import"./chunks/chunk-J2NGJKXL.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-NJ43NBSP.js";import"./chunks/chunk-KDUJCDLM.js";import{decideKillGuardRequest}from"./chunks/chunk-6APXZK7W.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-2IKL4F24.js";import"./chunks/chunk-KJR3XXMI.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-AC72EWI5.js";import"./chunks/chunk-RQFD6LG2.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getJobWidgetState,registerJobWidgetSource,setJobWidgetAuthorResolver,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-2U6HXWXS.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-LPYBKMPT.js";import{activateKillGuardRuntime,activeKillGuardEnvironment,getPowerShellConfig,getShellConfig,releaseKillGuardRuntime,withBundledBunCommands}from"./chunks/chunk-33MZJTQ3.js";import"./chunks/chunk-V5FSENW6.js";import"./chunks/chunk-R7J5TEYK.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-WXYMAUFX.js";import{KILL_GUARD_TAG}from"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-XH2MWTXA.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-ZG3MNTNX.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-UAOOH2V7.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-OH5TKHW7.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-IKJCA5SH.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-E266ORGA.js";import"./chunks/chunk-T2SMQPRE.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-IHES3JES.js";import"./chunks/chunk-5XHOHZIR.js";import"./chunks/chunk-HW6AAS3R.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-SODMQEHO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-EYSV6A7S.js";import"./chunks/chunk-MIENF2YK.js";import"./chunks/chunk-OXNWERO4.js";import"./chunks/chunk-44BJPS5I.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.js";import"./chunks/chunk-RFFMEA4B.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,JOB_WIDGET_STATE_EVENT,KILL_GUARD_MODULE_URL,KILL_GUARD_TAG,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,PINNED_HOST_CLIENT_CAPABILITIES,ProjectTrustStore,RELOCATION_TOOL_NAMES,REQUIRED_COMPACTION_ERROR_MESSAGE,REQUIRED_HOST_CAPABILITIES,RequiredCompactionError,ReservedCustodyKey,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SecretInputUnavailableError,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,TextTap,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,activateKillGuardRuntime,activeKillGuardEnvironment,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,decideKillGuardRequest,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findReservedKeywordRuns,findReservedKeywordSpans,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getJobWidgetState,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,killGuardProtectedPids,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readKillGuardSetting,readOwnFootprint,readProcessFootprint,readStoredCredential,registerJobWidgetSource,registerReadClassifier,registerRpcRemoteSource,releaseKillGuardRuntime,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionControlRemoteOriginOf,sessionControlSenderOf,sessionEntryToContextMessages,setJobWidgetAuthorResolver,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"./chunks/chunk-KU72IKV5.js";import{main}from"./chunks/chunk-X4XWAB3J.js";import"./chunks/chunk-TGW4R7SI.js";import"./chunks/chunk-HI5JSLG5.js";import"./chunks/chunk-ARUV3US4.js";import"./chunks/chunk-3IYEGHBI.js";import"./chunks/chunk-RYPM5BZQ.js";import"./chunks/chunk-NLYT7BND.js";import"./chunks/chunk-FAFIGBUD.js";import{configureHttpDispatcher}from"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-436DNN4Z.js";import"./chunks/chunk-BELNOPAI.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-GTJJ73DE.js";import"./chunks/chunk-VD7AKTGP.js";import"./chunks/chunk-7MN7YNO5.js";import"./chunks/chunk-H33A33M4.js";import"./chunks/chunk-TQHNFP77.js";import"./chunks/chunk-ZUQCYIRY.js";import"./chunks/chunk-HKCFMDJN.js";import"./chunks/chunk-3Q5ZENSD.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-Y3TMJV3J.js";import"./chunks/chunk-O3FG6HML.js";import"./chunks/chunk-MOVB6H22.js";import"./chunks/chunk-NH7SYIGN.js";import"./chunks/chunk-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-SOMFLLPD.js";import"./chunks/chunk-MTQQ2VQH.js";import"./chunks/chunk-L6NRDUWJ.js";import"./chunks/chunk-THYEZBUG.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-Y7Z7XPUF.js";import"./chunks/chunk-IEY2SL46.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-I5ASHSLZ.js";import"./chunks/chunk-2CNSCMYC.js";import"./chunks/chunk-DX43FSQT.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-YPAQXRP3.js";import"./chunks/chunk-R2Z7CX77.js";import"./chunks/chunk-UCXBDE6R.js";import"./chunks/chunk-YI6KRJDC.js";import"./chunks/chunk-DBQBJTMF.js";import"./chunks/chunk-SF4MQDKZ.js";import"./chunks/chunk-EJB5E2JK.js";import"./chunks/chunk-RCHIMH7N.js";import"./chunks/chunk-GILDYS3O.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-C4AHHZ6P.js";import"./chunks/chunk-J7FW7MED.js";import"./chunks/chunk-2EJ4BGBM.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-MSDBBOB2.js";import"./chunks/chunk-WHQ2QPP5.js";import"./chunks/chunk-J2NGJKXL.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-NJ43NBSP.js";import"./chunks/chunk-KDUJCDLM.js";import"./chunks/chunk-6APXZK7W.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-2IKL4F24.js";import"./chunks/chunk-KJR3XXMI.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-AC72EWI5.js";import"./chunks/chunk-RQFD6LG2.js";import"./chunks/chunk-2U6HXWXS.js";import"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-LPYBKMPT.js";import"./chunks/chunk-33MZJTQ3.js";import"./chunks/chunk-V5FSENW6.js";import"./chunks/chunk-R7J5TEYK.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-WXYMAUFX.js";import"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-XH2MWTXA.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-ZG3MNTNX.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-UAOOH2V7.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-OH5TKHW7.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-3IYWH6RO.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-E266ORGA.js";import"./chunks/chunk-T2SMQPRE.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-IHES3JES.js";import"./chunks/chunk-5XHOHZIR.js";import"./chunks/chunk-HW6AAS3R.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-SODMQEHO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-EYSV6A7S.js";import"./chunks/chunk-MIENF2YK.js";import"./chunks/chunk-FQXWKEVK.js";import"./chunks/chunk-OXNWERO4.js";import"./chunks/chunk-44BJPS5I.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.js";import"./chunks/chunk-RFFMEA4B.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"./chunks/chunk-KU72IKV5.js";import{main}from"./chunks/chunk-YCPURLPU.js";import"./chunks/chunk-XH24X5B2.js";import"./chunks/chunk-74IB3JPP.js";import"./chunks/chunk-QATU6BBC.js";import"./chunks/chunk-3IYEGHBI.js";import"./chunks/chunk-RYPM5BZQ.js";import"./chunks/chunk-NLYT7BND.js";import"./chunks/chunk-TUEZNIBK.js";import{configureHttpDispatcher}from"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-XI6THO4F.js";import"./chunks/chunk-UOZDDYBN.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-GTJJ73DE.js";import"./chunks/chunk-VD7AKTGP.js";import"./chunks/chunk-7MN7YNO5.js";import"./chunks/chunk-M2VJVJMK.js";import"./chunks/chunk-TQHNFP77.js";import"./chunks/chunk-ZUQCYIRY.js";import"./chunks/chunk-HKCFMDJN.js";import"./chunks/chunk-3Q5ZENSD.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-Y3TMJV3J.js";import"./chunks/chunk-O3FG6HML.js";import"./chunks/chunk-MOVB6H22.js";import"./chunks/chunk-DLPV4B3R.js";import"./chunks/chunk-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-SOMFLLPD.js";import"./chunks/chunk-MTQQ2VQH.js";import"./chunks/chunk-OF3XVGG4.js";import"./chunks/chunk-Q4G5DECT.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-DZQA5LVN.js";import"./chunks/chunk-IEY2SL46.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-4JMGWVRH.js";import"./chunks/chunk-E5O4SP5I.js";import"./chunks/chunk-DX43FSQT.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-47T6YMI2.js";import"./chunks/chunk-R2Z7CX77.js";import"./chunks/chunk-UCXBDE6R.js";import"./chunks/chunk-YI6KRJDC.js";import"./chunks/chunk-VUY4BZDI.js";import"./chunks/chunk-SF4MQDKZ.js";import"./chunks/chunk-EJB5E2JK.js";import"./chunks/chunk-RCHIMH7N.js";import"./chunks/chunk-GILDYS3O.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-C4AHHZ6P.js";import"./chunks/chunk-J7FW7MED.js";import"./chunks/chunk-2EJ4BGBM.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-MSDBBOB2.js";import"./chunks/chunk-WHQ2QPP5.js";import"./chunks/chunk-J2NGJKXL.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-NJ43NBSP.js";import"./chunks/chunk-KDUJCDLM.js";import"./chunks/chunk-6APXZK7W.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-2IKL4F24.js";import"./chunks/chunk-KJR3XXMI.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-7THM57HH.js";import"./chunks/chunk-AC72EWI5.js";import"./chunks/chunk-RQFD6LG2.js";import"./chunks/chunk-2U6HXWXS.js";import"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-LPYBKMPT.js";import"./chunks/chunk-33MZJTQ3.js";import"./chunks/chunk-V5FSENW6.js";import"./chunks/chunk-R7J5TEYK.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-WXYMAUFX.js";import"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-XH2MWTXA.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-ZG3MNTNX.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-UAOOH2V7.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-OH5TKHW7.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-IKJCA5SH.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-E266ORGA.js";import"./chunks/chunk-T2SMQPRE.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-IHES3JES.js";import"./chunks/chunk-5XHOHZIR.js";import"./chunks/chunk-HW6AAS3R.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-SODMQEHO.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-EYSV6A7S.js";import"./chunks/chunk-MIENF2YK.js";import"./chunks/chunk-FQXWKEVK.js";import"./chunks/chunk-OXNWERO4.js";import"./chunks/chunk-44BJPS5I.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.js";import"./chunks/chunk-RFFMEA4B.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":"8d89e7dd1a97acb7","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
1
+ {"buildId":"48fad659dbf98bcd","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
@@ -114,6 +114,8 @@ export declare class AgentSessionRuntime {
114
114
  constructor(_session: AgentSession, _services: AgentSessionServices, createRuntime: CreateAgentSessionRuntimeFactory, _diagnostics?: AgentSessionRuntimeDiagnostic[], _modelFallbackMessage?: string, launchProfile?: Readonly<AgentSessionLaunchProfile>);
115
115
  /** Stops advertising the open session to other processes; a runtime that replaces this one holds its own. */
116
116
  releaseSessionHold(): void;
117
+ /** A speculative host session becomes durable only when a caller claims its already-built runtime. */
118
+ persistSession(): Promise<void>;
117
119
  get services(): AgentSessionServices;
118
120
  get session(): AgentSession;
119
121
  get cwd(): string;
@@ -65,6 +65,11 @@ export class AgentSessionRuntime {
65
65
  this._sessionHold?.release();
66
66
  this._sessionHold = undefined;
67
67
  }
68
+ /** A speculative host session becomes durable only when a caller claims its already-built runtime. */
69
+ async persistSession() {
70
+ await this.session.sessionManager.enablePersistence();
71
+ this._sessionHold ??= holdActiveSession(this.session.sessionManager, false, this._launchProfile?.holderEndpoint);
72
+ }
68
73
  get services() {
69
74
  return this._services;
70
75
  }
@@ -1926,7 +1926,7 @@ export declare class AgentSession {
1926
1926
  */
1927
1927
  private _recordEngineTurnStart;
1928
1928
  /**
1929
- * A refused engine turn still records its message and settles a cross-session delivery it carries. A delivery
1929
+ * A refused engine turn still records its message and settles a cross-session delivery it carries. A message
1930
1930
  * whose entry the file refuses leaves the context too: its sender redelivers it, and it must not appear twice.
1931
1931
  */
1932
1932
  private _recordRefusedEngineTurnMessage;
@@ -6574,7 +6574,7 @@ export class AgentSession {
6574
6574
  }
6575
6575
  }
6576
6576
  /**
6577
- * A refused engine turn still records its message and settles a cross-session delivery it carries. A delivery
6577
+ * A refused engine turn still records its message and settles a cross-session delivery it carries. A message
6578
6578
  * whose entry the file refuses leaves the context too: its sender redelivers it, and it must not appear twice.
6579
6579
  */
6580
6580
  _recordRefusedEngineTurnMessage(appMessage) {
@@ -6583,12 +6583,17 @@ export class AgentSession {
6583
6583
  this.externalAdmission.observePersisted(appMessage);
6584
6584
  }
6585
6585
  catch (error) {
6586
- if (deliveryIdOf(appMessage) !== undefined) {
6587
- const index = this.agent.state.messages.lastIndexOf(appMessage);
6588
- if (index >= 0)
6589
- this.agent.state.messages.splice(index, 1);
6590
- }
6591
- this.externalAdmission.observeRefused(appMessage, error instanceof Error ? error.message : String(error));
6586
+ // The session file refused the entry: the message leaves the context too, so the context matches the
6587
+ // file, and the failure follows the same contract as the main persistence path — it is recorded,
6588
+ // logged, and emitted (senpi#2972). This holds for non-delivery messages as well as deliveries.
6589
+ const errorMessage = error instanceof Error ? error.message : String(error);
6590
+ const index = this.agent.state.messages.lastIndexOf(appMessage);
6591
+ if (index >= 0)
6592
+ this.agent.state.messages.splice(index, 1);
6593
+ this._transcriptWriteFailures.record(appMessage, error);
6594
+ this._sessionLogger.warn("transcript_write_failed", { role: appMessage.role, error: errorMessage });
6595
+ this._emit({ type: "transcript_write_failed", role: appMessage.role, errorMessage });
6596
+ this.externalAdmission.observeRefused(appMessage, errorMessage);
6592
6597
  this._takePersistWatcher(appMessage)?.failed(error);
6593
6598
  }
6594
6599
  }
@@ -6674,12 +6679,27 @@ export class AgentSession {
6674
6679
  const start = { type: "message_start", message: appMessage };
6675
6680
  this._recoveryIdentity?.observe(start);
6676
6681
  const entryId = this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details, { recoveryOwner: recoveryCarrier(start) });
6677
- this._emitEntryAppended(entryId);
6682
+ // The entry is written: only a failure of the write itself counts as refused. Bookkeeping (ticket,
6683
+ // watcher settlement, revision) runs before any notification, and each notification is guarded on its
6684
+ // own, so a throwing listener can neither leave a persisted delivery unsettled nor suppress a later
6685
+ // notification (senpi#2972).
6678
6686
  this._recordWrittenTicket(appMessage, entryId);
6679
6687
  this._takePersistWatcher(appMessage)?.persisted(entryId);
6680
6688
  this._incrementMessageRevision();
6681
- this._emit(start);
6682
- this._emit({ type: "message_end", message: appMessage });
6689
+ const notify = (emit) => {
6690
+ try {
6691
+ emit();
6692
+ }
6693
+ catch (error) {
6694
+ this._sessionLogger.warn("custom_message_listener_failed", {
6695
+ customType: appMessage.customType,
6696
+ error: error instanceof Error ? error.message : String(error),
6697
+ });
6698
+ }
6699
+ };
6700
+ notify(() => this._emitEntryAppended(entryId));
6701
+ notify(() => this._emit(start));
6702
+ notify(() => this._emit({ type: "message_end", message: appMessage }));
6683
6703
  }
6684
6704
  _flushPendingCustomMessages() {
6685
6705
  const pending = this._pendingCustomMessages;
@@ -7,8 +7,12 @@ export function groupChangedPaths(paths, targets, rearmedContainers) {
7
7
  if (!targetMatchesPath(activeTarget.target, path))
8
8
  continue;
9
9
  matched = true;
10
- // The project container only rearms discovery; newly discovered config files carry the change.
11
- if (activeTarget.target.id === "builtin-project-presence" && rearmedContainers.includes(resolve(path)))
10
+ // Discovery containers only rearm their watches; discovered files carry the change.
11
+ // An extensions directory may contain only runtime state (e.g. a park's goal/no-session).
12
+ if (rearmedContainers.includes(resolve(path)) &&
13
+ (activeTarget.target.id === "builtin-project-presence" ||
14
+ activeTarget.target.id === "builtin-global-extensions" ||
15
+ activeTarget.target.id === "builtin-project-extensions"))
12
16
  continue;
13
17
  const group = groups.get(activeTarget.registrationId) ?? [];
14
18
  if (!group.includes(path))
@@ -1,15 +1,22 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
+ import { Type } from "typebox";
4
+ import { Check } from "typebox/value";
3
5
  import { keyedIdentity } from "../config-identity-key.js";
4
6
  import { resolveAuthMode } from "./context.js";
7
+ import { oauthGrantIdentity } from "./oauth-grant.js";
5
8
  import { McpTokenStore } from "./token-store.js";
6
9
  /** Local snapshot only: never migrates credentials, acquires a lock, or refreshes authentication. */
7
10
  export function mcpCredentialIdentity(config, serverName, agentDir, env) {
8
11
  const material = credentialMaterial(config, serverName, agentDir, env);
9
- return material === undefined || material === "none" ? material : keyedIdentity(agentDir, material);
12
+ return material === undefined || material === "none" || resolveAuthMode(config) === "oauth"
13
+ ? material
14
+ : keyedIdentity(agentDir, material);
10
15
  }
11
16
  /** The unkeyed identity earlier builds persisted; read only to adopt a cache entry for the same credential. */
12
17
  export function legacyMcpCredentialIdentity(config, serverName, agentDir, env) {
18
+ if (resolveAuthMode(config) === "oauth")
19
+ return undefined;
13
20
  const material = credentialMaterial(config, serverName, agentDir, env);
14
21
  return material === undefined || material === "none"
15
22
  ? material
@@ -31,14 +38,15 @@ function credentialMaterial(config, serverName, agentDir, env) {
31
38
  try {
32
39
  const store = new McpTokenStore({ serverName, serverUrl: config.url ?? "", agentDir });
33
40
  const value = JSON.parse(readFileSync(store.tokensPath, "utf8"));
34
- if (typeof value !== "object" || value === null || !("accessToken" in value))
35
- return undefined;
36
- if (typeof value.accessToken !== "string" || value.accessToken.length === 0)
37
- return undefined;
38
- const refreshToken = "refreshToken" in value ? value.refreshToken : undefined;
39
- if (refreshToken !== undefined && typeof refreshToken !== "string")
41
+ if (!Check(storedGrantSchema, value))
40
42
  return undefined;
41
- return JSON.stringify(["mcp-catalog-oauth", value.accessToken, refreshToken]);
43
+ return oauthGrantIdentity(value, {
44
+ serverName,
45
+ serverUrl: store.serverUrl,
46
+ agentDir: store.agentDir,
47
+ clientId: config.oauth?.clientId,
48
+ clientMetadataUrl: config.oauth?.clientMetadataUrl,
49
+ });
42
50
  }
43
51
  catch (error) {
44
52
  if (error instanceof Error)
@@ -46,4 +54,20 @@ function credentialMaterial(config, serverName, agentDir, env) {
46
54
  throw error;
47
55
  }
48
56
  }
57
+ // Parse exactly the stored fields the identity reader consumes; authorization is parsed by its proof owner.
58
+ const storedGrantSchema = Type.Object({
59
+ accessToken: Type.String({ minLength: 1 }),
60
+ refreshToken: Type.Optional(Type.String()),
61
+ issuer: Type.Optional(Type.String()),
62
+ resource: Type.Optional(Type.String()),
63
+ scope: Type.Optional(Type.String()),
64
+ refreshScope: Type.Optional(Type.String()),
65
+ clientInfo: Type.Optional(Type.Object({
66
+ client_id: Type.String(),
67
+ client_secret: Type.Optional(Type.String()),
68
+ token_endpoint_auth_method: Type.Optional(Type.String()),
69
+ issuer: Type.Optional(Type.String()),
70
+ })),
71
+ discoveryState: Type.Optional(Type.Object({ authorizationServerUrl: Type.String() })),
72
+ });
49
73
  //# sourceMappingURL=catalog-identity.js.map