@code-yeongyu/senpi 2026.11.6-1 → 2026.11.6-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.
- package/CHANGELOG.md +35 -0
- package/dist/bundle/chunks/{chunk-5MWHZH2O.js → chunk-2FDW2LQL.js} +1 -1
- package/dist/bundle/chunks/{chunk-GG2JO3CL.js → chunk-4E7GDG4H.js} +1 -1
- package/dist/bundle/chunks/{chunk-K5JLYACP.js → chunk-4GKU755E.js} +1 -1
- package/dist/bundle/chunks/{chunk-437VLZQZ.js → chunk-7III44PV.js} +1 -1
- package/dist/bundle/chunks/chunk-7PSBD5KS.js +9 -0
- package/dist/bundle/chunks/{chunk-KFWHLVVH.js → chunk-C7OKUC7L.js} +1 -1
- package/dist/bundle/chunks/{chunk-CX32K5KD.js → chunk-CF5OGBC4.js} +7 -7
- package/dist/bundle/chunks/{chunk-7TGZJH6Z.js → chunk-D5MRJWUK.js} +40 -39
- package/dist/bundle/chunks/{chunk-E6L5VZSM.js → chunk-DSWDJ7HT.js} +1 -1
- package/dist/bundle/chunks/{chunk-6NMTFURP.js → chunk-ECW7VBMB.js} +1 -1
- package/dist/bundle/chunks/{chunk-2CSLJLM6.js → chunk-GKAYPJ4E.js} +2 -2
- package/dist/bundle/chunks/{chunk-KCGUUIUS.js → chunk-GNSMNSL7.js} +1 -1
- package/dist/bundle/chunks/{chunk-V3JSQ3PG.js → chunk-GSKCWXXG.js} +1 -1
- package/dist/bundle/chunks/{chunk-USKWGPA6.js → chunk-GTJJ73DE.js} +1 -1
- package/dist/bundle/chunks/{chunk-HHSYTDKO.js → chunk-HLM46XEB.js} +2 -2
- package/dist/bundle/chunks/{chunk-A4F4J2KH.js → chunk-I3PHVJAS.js} +2 -2
- package/dist/bundle/chunks/{chunk-LAMRXFHZ.js → chunk-LNPAT22L.js} +1 -1
- package/dist/bundle/chunks/chunk-NH7SYIGN.js +2 -0
- package/dist/bundle/chunks/{chunk-ZIIDIVTG.js → chunk-R2Z7CX77.js} +1 -1
- package/dist/bundle/chunks/{chunk-32I42CEY.js → chunk-RQ6CHXQ2.js} +1 -1
- package/dist/bundle/chunks/chunk-SJI6UB23.js +2 -0
- package/dist/bundle/chunks/{chunk-KUIEHAPR.js → chunk-T2SMQPRE.js} +1 -1
- package/dist/bundle/chunks/{chunk-IPG434JT.js → chunk-TIPKAMSS.js} +1 -1
- package/dist/bundle/chunks/{chunk-RI5ABX7A.js → chunk-TMXRR3N7.js} +2 -2
- package/dist/bundle/chunks/chunk-VD7AKTGP.js +3 -0
- package/dist/bundle/chunks/{chunk-22JICYKS.js → chunk-WAOGBBZR.js} +1 -1
- package/dist/bundle/chunks/{chunk-6MHCFJDB.js → chunk-WGRKM3N6.js} +2 -2
- package/dist/bundle/chunks/{chunk-WF5R2VSP.js → chunk-X5ZVYNOL.js} +1 -1
- package/dist/bundle/chunks/{chunk-H2FBGZNP.js → chunk-XCMII2VQ.js} +2 -2
- package/dist/bundle/chunks/{chunk-5JUCTKYS.js → chunk-YK3ZZCHI.js} +1 -1
- package/dist/bundle/chunks/{cli-main-ZQBSX5H5.js → cli-main-T74YJGIF.js} +1 -1
- package/dist/bundle/chunks/{hand-entry-7U7354GG.js → hand-entry-AYRUGE2A.js} +2 -2
- package/dist/bundle/chunks/{headless-host-7LKTG76U.js → headless-host-ES74ZB6M.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-NLSWH2CA.js → help-fast-path-TMTGLOBG.js} +1 -1
- package/dist/bundle/chunks/{host-command-3YRFN35E.js → host-command-YRXZE4TV.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-6XLVIECJ.js → host-lifecycle-6VCXMPDW.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/{host-session-command-F7USXUZV.js → host-session-command-N7IN7ZDV.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-4RF3PUQ2.js → interactive-mode-B5SQDLH7.js} +1 -1
- package/dist/bundle/chunks/{list-tips-H6VGDFTS.js → list-tips-DU57HHKA.js} +1 -1
- package/dist/bundle/chunks/{main-G2SRZYQN.js → main-UQFVFCNY.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-RPN54GUC.js → multi-session-host-XSUJDHFZ.js} +5 -5
- package/dist/bundle/chunks/{openai-codex-responses-MJZKUS6I.js → openai-codex-responses-7V6LTDRU.js} +2 -2
- package/dist/bundle/chunks/{package-manager-cli-D2VFD463.js → package-manager-cli-GLUNPQJU.js} +1 -1
- package/dist/bundle/chunks/{role-37WVG42T.js → role-RRFFHZF5.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-QELPMM4N.js → rotation-stream-BN2YK2MC.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-P4D3DVYD.js → rpc-mode-JYN3E7P7.js} +1 -1
- package/dist/bundle/chunks/rpc-monitor-source-C6VQ3BC4.js +3 -0
- package/dist/bundle/chunks/{run-attached-tui-CGA6O5FR.js → run-attached-tui-W236SEOR.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-XWSNOAGG.js → schedule-command-B2EJTBOE.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-YIMLHGLG.js +3 -0
- package/dist/bundle/chunks/{session-picker-OA2AUVZG.js → session-picker-E6ZONUJB.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +294 -292
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/cli/project-trust-headless.d.ts +13 -0
- package/dist/cli/project-trust-headless.js +35 -0
- package/dist/cli/project-trust.js +13 -50
- package/dist/cli/schedule-delivery.d.ts +4 -0
- package/dist/cli/schedule-delivery.js +6 -0
- package/dist/cli/schedule-runner.js +8 -0
- package/dist/cli/session-opening.d.ts +19 -0
- package/dist/cli/session-opening.js +47 -1
- package/dist/core/agent-session-runtime.d.ts +12 -0
- package/dist/core/agent-session-runtime.js +41 -0
- package/dist/core/agent-session.js +13 -22
- package/dist/core/egress/api-table.d.ts +121 -0
- package/dist/core/egress/api-table.js +41 -0
- package/dist/core/egress/classify.d.ts +19 -0
- package/dist/core/egress/classify.js +197 -0
- package/dist/core/egress/credential-fields.d.ts +18 -0
- package/dist/core/egress/credential-fields.js +83 -0
- package/dist/core/egress/custody-sidecar.d.ts +44 -0
- package/dist/core/egress/custody-sidecar.js +91 -0
- package/dist/core/egress/device-custody.d.ts +12 -0
- package/dist/core/egress/device-custody.js +82 -0
- package/dist/core/egress/endpoint.d.ts +33 -0
- package/dist/core/egress/endpoint.js +115 -0
- package/dist/core/execute-tool-on-host.d.ts +26 -0
- package/dist/core/execute-tool-on-host.js +96 -0
- package/dist/core/extensions/builtin/compaction/retained-message-safety.js +15 -0
- package/dist/core/extensions/builtin/goal/index.js +15 -3
- package/dist/core/extensions/builtin/goal/stop-pause.d.ts +2 -0
- package/dist/core/extensions/builtin/goal/stop-pause.js +5 -0
- package/dist/core/extensions/builtin/herdr/herdr-state.d.ts +10 -0
- package/dist/core/extensions/builtin/herdr/herdr-state.js +34 -6
- package/dist/core/extensions/builtin/herdr/index.js +6 -2
- package/dist/core/extensions/builtin/mcp/service.d.ts +9 -1
- package/dist/core/extensions/builtin/mcp/service.js +32 -1
- package/dist/core/extensions/builtin/terminal/rpc-monitor-remote.d.ts +43 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-remote.js +158 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-render.d.ts +2 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-render.js +4 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-source.d.ts +5 -2
- package/dist/core/extensions/builtin/terminal/rpc-monitor-source.js +19 -4
- package/dist/core/extensions/builtin/terminal/rpc-monitor-targets.d.ts +4 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-targets.js +15 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-watch.d.ts +10 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-watch.js +28 -2
- package/dist/core/extensions/builtin/terminal/rpc-remote-source.d.ts +59 -0
- package/dist/core/extensions/builtin/terminal/rpc-remote-source.js +15 -0
- package/dist/core/extensions/builtin/terminal/terminal-manifest-model.d.ts +5 -0
- package/dist/core/extensions/builtin/terminal/terminal-manifest-parse.js +14 -1
- package/dist/core/extensions/builtin/terminal/tools/monitor-rpc.js +8 -1
- package/dist/core/extensions/loader.js +8 -0
- package/dist/core/extensions/types.d.ts +6 -0
- package/dist/core/foreign-session-holders.d.ts +1 -1
- package/dist/core/foreign-session-holders.js +3 -3
- package/dist/core/session-import/jsonl-import.d.ts +8 -12
- package/dist/core/session-import/jsonl-import.js +99 -40
- package/dist/core/session-manager.d.ts +2 -0
- package/dist/core/session-manager.js +7 -2
- package/dist/core/session-store/durable-binding.d.ts +2 -0
- package/dist/core/session-store/durable-binding.js +26 -4
- package/dist/core/settings-manager.d.ts +20 -0
- package/dist/core/settings-manager.js +51 -0
- package/dist/core/trust-manager.d.ts +1 -18
- package/dist/core/trust-manager.js +3 -124
- package/dist/core/trust-requiring-resources.d.ts +21 -0
- package/dist/core/trust-requiring-resources.js +189 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/main.js +42 -12
- package/dist/modes/interactive/interactive-mode.js +2 -2
- package/dist/modes/interactive/session-control-commands.js +2 -0
- package/dist/modes/rpc/connection-handler.js +17 -0
- package/dist/modes/rpc/connection-question-bridge.js +7 -4
- package/dist/modes/rpc/effect-commands.d.ts +24 -0
- package/dist/modes/rpc/host-boot-extensions.d.ts +4 -0
- package/dist/modes/rpc/host-boot-extensions.js +17 -0
- package/dist/modes/rpc/host-lifecycle-shutdown.js +11 -2
- package/dist/modes/rpc/loopless-runtime-settings.js +5 -1
- package/dist/modes/rpc/method-classes-schema-session.d.ts +33 -0
- package/dist/modes/rpc/method-classes-schema-session.js +4 -0
- package/dist/modes/rpc/method-classes-schema.d.ts +33 -0
- package/dist/modes/rpc/method-classes.d.ts +4 -0
- package/dist/modes/rpc/method-classes.js +7 -0
- package/dist/modes/rpc/multi-session-host.d.ts +2 -0
- package/dist/modes/rpc/multi-session-host.js +7 -2
- package/dist/modes/rpc/project-workspace-commands.d.ts +60 -0
- package/dist/modes/rpc/project-workspace-commands.js +145 -0
- package/dist/modes/rpc/rpc-error-types.d.ts +11 -1
- package/dist/modes/rpc/rpc-error-types.js +10 -0
- package/dist/modes/rpc/rpc-input-validation.js +4 -0
- package/dist/modes/rpc/rpc-mutation-response-types.d.ts +13 -0
- package/dist/modes/rpc/rpc-read-response-types.d.ts +13 -0
- package/dist/modes/rpc/rpc-session-command-types.d.ts +15 -0
- package/dist/modes/rpc/session-attachment-gate.js +2 -0
- package/dist/modes/rpc/session-command-activity.js +2 -0
- package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
- package/docs/engine-socket/fixtures/rpc-inbound-samples.json +41 -2
- package/docs/extensions.md +17 -1
- package/docs/rpc.md +121 -4
- package/docs/terminal-tools.md +8 -0
- package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
- package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-FUQJK2TU.js +0 -2
- package/dist/bundle/chunks/chunk-POZMRM6V.js +0 -2
- package/dist/bundle/chunks/chunk-XBG63MJZ.js +0 -8
- package/dist/bundle/chunks/chunk-YP47G4YP.js +0 -3
- package/dist/bundle/chunks/rpc-monitor-source-KKN2UP4T.js +0 -3
- package/dist/bundle/chunks/session-control-endpoint-OST7WAKP.js +0 -3
package/dist/bundle/cli.js
CHANGED
|
@@ -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-437VLZQZ.js";import"./chunks/chunk-IPG434JT.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-GLTOBXZY.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-6NMTFURP.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import{preparePrivateFdSpawn,spawnWithPrivateFds}from"./chunks/chunk-5JUCTKYS.js";import{releaseInheritedStartupFillers}from"./chunks/chunk-KUIEHAPR.js";import{HOST_STARTUP_EVENTS_ENV}from"./chunks/chunk-RUGTHELO.js";import{isFifoMode}from"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.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"});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:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawnWithPrivateFds(spawn2,process.execPath,[...process.execArgv,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-NLSWH2CA.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-ZQBSX5H5.js")}
|
|
3
|
+
import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunks/chunk-7III44PV.js";import"./chunks/chunk-TIPKAMSS.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-GLTOBXZY.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-ECW7VBMB.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import{preparePrivateFdSpawn,spawnWithPrivateFds}from"./chunks/chunk-YK3ZZCHI.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-2SOVDETB.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"});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:process.execArgv.length>0||hasInheritedInspectorOption()}async function spawnFullCli(){let extension=import.meta.url.endsWith(".ts")?".ts":".js",fullCliPath=isBundledNode?fileURLToPath(import.meta.url):fileURLToPath(new URL(`./cli-main${extension}`,import.meta.url));releaseInheritedInspectorForChild();let childEnvironment=isBundledNode?{...process.env,[ISOLATED_CHILD_ENV]:"1"}:process.env;return await new Promise((resolve,reject)=>{let child=spawnWithPrivateFds(spawn2,process.execPath,[...process.execArgv,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-TMTGLOBG.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-T74YJGIF.js")}
|
|
@@ -51,4 +51,4 @@ renameSync(temporary, launcher);
|
|
|
51
51
|
`)}))}catch(cause){socket.destroy();let reason=cause instanceof Error?cause.message:"";return reason==="host_identity_unproven"||reason==="auth_failed"?{unproven:reason}:outcome(!1)}finally{clearTimeout(timer)}}return new Promise(resolve5=>{let socket=createConnection5(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=connected=>{socket.destroy(),resolve5(connected?"ready":"refused")};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}async function stampOf(socketPath){try{let entry=await lstat4(socketPath,{bigint:!0});return{dev:entry.dev,ino:entry.ino,ctimeNs:entry.ctimeNs,socket:entry.isSocket()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}}var sameStamp=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.ctimeNs===b.ctimeNs;async function prepareSocketPath(socketPath,hooks={}){if(process.platform==="win32"||socketPath.startsWith("\0"))return;if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir8(dirname11(socketPath),{recursive:!0,mode:448});let probed=await stampOf(socketPath);if(probed===void 0)return;let inUse=evidence=>new Error(`${socketPath}: address already in use by a live server (${evidence}).`);if(!probed.socket)throw new Error(`${socketPath}: address already in use, occupied by a non-socket entry (a symlink or other file; nothing listens there).`);let probe=hooks.listenerState??socketEntryListenerState,state3=await probe(socketPath);if(state3.verdict==="gone")return;if(state3.verdict==="live")throw inUse(state3.evidence);await hooks.afterStaleProbe?.();let unchanged=async()=>{let current=await stampOf(socketPath);if(current===void 0)return!1;if(!sameStamp(probed,current))throw inUse("the entry changed after it was probed");return!0};if(!await unchanged())return;let again=await probe(socketPath);if(again.verdict!=="gone"){if(again.verdict==="live")throw inUse(again.evidence);if(await unchanged())try{await unlink4(socketPath)}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}}}function listen2(server,socketPath,secret){return listen(server,socketPath,secret)}function closeServer(server){return new Promise(resolve5=>{server.close(()=>resolve5())})}var HOST_CHILD_LISTEN_MS=3e4,OBSERVER_RETRY_DELAY_MS=250;function declareHostChild(childCommand){childCommand&&reportStartupMilestone("host_opaque")}function hostChildReportsStartup(childCommand){return startupHandOff()!==void 0&&!childCommand}async function hostChildSpawned(child,generationDir,supervisorStartTime){let handOff=startupHandOff();if(!handOff)return;let stream=child.stdio[16];relayHostStartupEvents(stream instanceof Readable?stream:void 0),await writeJsonAtomic(join19(generationDir,STARTUP_ATTEMPT_FILE),{attempt:handOff.binding.attempt,pid:process.pid,processStartTime:supervisorStartTime??null}),reportStartupMilestone("supervisor_setup")}async function awaitInternalStartup(options){let handOff=startupHandOff(),deadline=performance.now()+(handOff?.budgetMs??0);for(await waitForListener(options.internalSocket,handOff?.budgetMs??HOST_CHILD_LISTEN_MS,options.internalSecret,options.internalKey,{retrySilent:handOff!==void 0}),reportStartupMilestone("internal_ready");;)try{await options.openObserver();break}catch(cause){let reason=cause instanceof Error?cause.message:"";if(!handOff||(reason==="host_identity_unproven"||reason==="auth_failed")||performance.now()+OBSERVER_RETRY_DELAY_MS>=deadline)throw cause;await new Promise(resolveDelay=>setTimeout(resolveDelay,OBSERVER_RETRY_DELAY_MS))}reportStartupMilestone("observer_ready")}function supervisorPublished(){reportStartupMilestone("public_published")}async function publishSupervisorEndpoint(options){let{launch,server,publicSecret}=options,generation=typeof options.settings=="object"&&options.settings!==null?Reflect.get(options.settings,"generation"):void 0,token=endpointOwnerToken(launch.socket,options.instanceId,typeof generation=="number"?generation:0),bindSocket=launch.bindSocket;if(bindSocket===void 0){await claimEndpoint(launch.socket,token,async()=>{await prepareSocketPath(launch.socket),await listen2(server,launch.socket,publicSecret)}),await options.publicEndpoint?.publish(),options.state.publicSocketOwned=!0;return}await prepareSocketPath(bindSocket);let bound=await listen2(server,bindSocket,publicSecret);try{let granted=await awaitPublicationGrant(options.generationDir);await options.publicEndpoint?.publish(),options.state.publicSocketOwned=!0,await adoptEndpoint({bindSocket,publicSocket:launch.socket,expected:launch.replaceIdentity,expectedOwner:launch.replaceOwner,token,...granted?{granted}:{}})}catch(cause){throw await unlinkOwnedSocket(bindSocket,bound,supervisorLog),cause}}async function awaitPublicationGrant(generationDir){let handOff=startupHandOff();if(handOff?.binding.launchKind!=="successor")return;let{attempt}=handOff.binding;return await readGrantLine(startupGrantLine(attempt).trimEnd(),handOff.budgetMs),async()=>{try{let grant=JSON.parse(await readFile10(join19(generationDir,ADOPTION_GRANT_FILE),"utf8"));return typeof grant=="object"&&grant!==null&&Reflect.get(grant,"attempt")===attempt}catch{return!1}}}var GRANT_READ_RETRY_MS=50;function readGrantLine(expected,budgetMs){return new Promise((resolveGrant,reject)=>{let buffer=Buffer.alloc(4096),pending="",settled=!1,settle=error=>{settled||(settled=!0,clearTimeout(timer),error?reject(error):resolveGrant())},timer=setTimeout(()=>settle(new Error(`no publication grant within ${budgetMs}ms`)),budgetMs),next=()=>{read(16,buffer,0,buffer.length,null,(error,bytes)=>{if(!settled){if(error?.code==="EAGAIN"){setTimeout(next,GRANT_READ_RETRY_MS);return}if(error||bytes===0)return settle(new Error("the startup pipe closed before the publication grant"));pending+=buffer.toString("utf8",0,bytes);for(let newline=pending.indexOf(`
|
|
52
52
|
`);newline>=0;newline=pending.indexOf(`
|
|
53
53
|
`)){if(pending.slice(0,newline)===expected)return settle();pending=pending.slice(newline+1)}if(pending.length>4096)return settle(new Error("oversized startup grant record"));next()}})};next()})}function hostChildStdio(bootstrap,reportsStartup){let base=[process.platform==="win32"?"ignore":"pipe","ignore","inherit","pipe",...bootstrap?["pipe"]:[]];return reportsStartup?withStartupPipe(base):{stdio:[...base],fillers:[]}}init_brand();init_host_identity_env();init_process_identity();var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PSTART_ENV="SENPI_RPC_HOST_WATCH_PSTART",HOST_WATCH_PSTART_TICKS_ENV="SENPI_RPC_HOST_WATCH_PSTART_TICKS",HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";init_socket_transport();var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,ownerFd,presenterBootstrapFd,bindSocket,replaceIdentity,replaceOwner;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--mcp-presenter-fd"&&argv[index+1]==="4"){presenterBootstrapFd=4,index++;continue}if(arg==="--owner-fd"&&index+1<argv.length){if(ownerFd=Number(argv[++index]),!Number.isSafeInteger(ownerFd)||ownerFd<3)return;continue}if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}if(arg==="--replace-owner"&&index+1<argv.length){replaceOwner=argv[++index];continue}hostArgs.push(arg)}return socket===void 0||ownerFd===presenterBootstrapFd&&ownerFd!==void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity,replaceOwner,presenterBootstrapFd}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...runtimeExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}var HOST_CHILD_WATCH_FD=3;function hostChildEnvironment(options,startupHandOff2,platform=process.platform){let{launch,internal,internalSecret}=options;return{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:options.daemonDir,[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_WATCH_FD_ENV]:String(HOST_CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),[HOST_WATCH_PSTART_ENV]:options.supervisorStart?.time,[HOST_WATCH_PSTART_TICKS_ENV]:options.supervisorStart?.ticks,[HOST_WATCH_LIFETIME_FIFO_ENV]:options.lifetimeFifo,...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},[SOCKET_SECRET_FILE_ENV]:platform==="win32"&&internalSecret?internal.secretPath:void 0,[INTERNAL_KEY_STDIN_ENV]:options.internalKey?"1":void 0,[HOST_CLEANUP_PATHS_ENV]:options.cleanupPaths.join(`
|
|
54
|
-
`),[HOST_PUBLIC_SOCKET_ENV]:options.publicSocket,[HOST_STARTUP_EVENTS_ENV]:startupHandOff2}}function spawnHostChild(options){let{launch,internalSocket}=options,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),bootstrap=launch.presenterBootstrapFd!==void 0&&!childLaunch.shell;bootstrap&&childLaunch.args.push("--mcp-presenter-fd","4");let startupStdio=hostChildStdio(bootstrap,options.reportsStartup===!0),child=spawnWithPrivateFds((command,args,options2)=>childProcess.spawn(command,args,options2),childLaunch.command,childLaunch.args,{env:hostChildEnvironment(options,options.reportsStartup?hostChildStartupHandOff(startupStdio.fillers):void 0),shell:childLaunch.shell,stdio:startupStdio.stdio,windowsHide:!0},{final:!0});if(releaseStartupFillers(child,startupStdio.fillers),launch.presenterBootstrapFd!==void 0){let fd=launch.presenterBootstrapFd;Promise.resolve().then(()=>(init_mcp_presenter_bootstrap(),mcp_presenter_bootstrap_exports)).then(({presenterBootstrapStream:presenterBootstrapStream2,relayPresenterBootstrap:relayPresenterBootstrap2})=>{let upstream=presenterBootstrapStream2(fd);if(upstream&&bootstrap)return relayPresenterBootstrap2(upstream,child);upstream?.destroy(),child.stdio[4]?.destroy()}).catch(()=>child.stdio[4]?.destroy())}return options.internalKey&&(child.stdin?.on("error",()=>{}),child.stdin?.write(options.internalKey)),child}import{rm as rm6}from"node:fs/promises";init_process_identity();import{rename as rename5,rm as rm5}from"node:fs/promises";init_process_identity();var TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;var BYTES_PER_MEGABYTE=1024*1024;init_process_identity();async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId);if(await hostChildAlive(generation))return;let record2=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record2!==void 0&&record2.pid!==owner.pid)return;if(owner.superseded===!0){await rm5(generation.dir,{recursive:!0,force:!0});return}let ownsPointer=parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId;ownsPointer&&await rm5(paths.settingsFile,{force:!0}),await rm5(generation.dir,{recursive:!0,force:!0}),ownsPointer&&await rm5(paths.pointerFile,{force:!0})}var LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_ERROR_MS=5e3;function loopLagErrorMs(env=process.env){return parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}var STALL_WAIT_SLICE_MS=5e3;async function waitOutStalledChild(options){let{child,generation,signalledAt}=options,maxMs=childStalledStopMaxMs(),untilAt=signalledAt+maxMs,stalled=()=>hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:STOP_STALL_EVIDENCE_MAX_AGE_MS}).catch(()=>!1),waited=0;try{for(;Date.now()<untilAt&&await stalled();){waited===0&&supervisorLog(`host child is stalled; waiting up to ${maxMs}ms (${CHILD_STALLED_STOP_MAX_MS_ENV})`),await writeStopProgress(generation,{at:new Date().toISOString(),phase:"waiting_stalled_child",untilAt:new Date(untilAt).toISOString()}).catch(()=>{});let slice=Math.min(STALL_WAIT_SLICE_MS,untilAt-Date.now()),exited=await options.waitForExit(child,slice);if(waited+=slice,exited)break}}finally{await clearStopProgress(generation)}return waited}var WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3;function supervisorSender(instanceId){return{pid:process.pid,kind:"supervisor",generation:instanceId}}function childExited(child){return child.exitCode!==null||child.signalCode!==null}async function performShutdown(context,reason,exitCode){let{state:state3,child}=context;state3.shuttingDown=!0,state3.shutdownReason=reason,context.admission.stop();let childStopStarted=!1,hardExit;try{context.drain.stop(),writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`),childStopStarted=!0,await stopChild(context,reason),await state3.childExitRecorded,await state3.startupComplete.then(void 0,()=>{}),context.stopWatchers(),await context.admission.flush(),context.activity.clients.destroyAll(),process.platform==="win32"&&(hardExit=setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS)),context.drain.active||await closeShieldedEndpoint(context.publicSocket,()=>closeServer(context.server)),context.internalDir&&await rm6(context.internalDir,{recursive:!0,force:!0}),context.activity.stopObserver(),state3.publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedEndpoint(context.publicSocket,state3.publicSocketIdentity,context.instanceId,supervisorLog),await releaseGeneration(context.paths,{instanceId:context.instanceId,pid:process.pid,superseded:state3.endpointReplaced})}catch(cause){supervisorLog(`shutdown failed for host child pid ${child.pid??"unknown"}: ${errorMessage(cause)}`),exitCode=1;try{childStopStarted||await reapChildAfterFailure(child),await state3.childExitRecorded}catch(reapCause){supervisorLog(`shutdown recovery failed for host child pid ${child.pid??"unknown"}: ${errorMessage(reapCause)}`)}}finally{await context.publicEndpoint?.dispose().catch(cause=>{supervisorLog(`endpoint key cleanup failed: ${errorMessage(cause)}`)}),hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}async function stopChild(context,reason){let{child,generation}=context,pid=child.pid;if(childExited(child)||pid===void 0)return;let termAttempted=!1,killAttempted=!1;try{let outer=await readStopIntent(generation).catch(cause=>{supervisorLog(`cannot read child stop intent: ${errorMessage(cause)}`)}),at=new Date().toISOString(),intent=layeredSupervisorIntent(outer,supervisorSender(context.instanceId),{targetPid:pid,reason,at});await writeStopIntent(generation,intent,supervisorLog);let signalledAt=Date.now();if(termAttempted=!0,signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS))return;let stallWaitMs=await waitOutStalledChild({child,generation,signalledAt,waitForExit:waitForChildExit});if(childExited(child))return;if(stallWaitMs>0){let escalated={...intent,reason:`${intent.reason}; escalated_after_stall_wait=${stallWaitMs}`};await writeStopIntent(generation,escalated,supervisorLog)}if(killAttempted=!0,signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after SIGKILL`)}catch(cause){throw killAttempted||await reapChildAfterFailure(child,termAttempted),cause}}async function reapChildAfterFailure(child,termAttempted=!1){let pid=child.pid;if(!(childExited(child)||pid===void 0)&&!(!termAttempted&&(signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)))&&(signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS)))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after recovery SIGKILL`)}function signalChild(pid,signal){try{return process.kill(pid,signal),!0}catch{return!1}}function waitForChildExit(child,timeoutMs){return childExited(child)?Promise.resolve(!0):new Promise(resolve5=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve5(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve5(!0)};child.once("exit",onExit2)})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}function startSupervisorTicker(options){let{activity,owner,draining,shuttingDown,shutdown}=options,tickIntervalMs=Math.max(20,Math.min(1e3,options.idleExitMs/4)),ownerCheck=!1,ticker=setInterval(()=>{!draining()&&activity.refresh()==="exit"&&activity.clients.unclassifiedCount===0&&shutdown("idle",0),!ownerCheck&&!shuttingDown()&&!draining()&&(ownerCheck=!0,owner.shouldExit(activity).then(exit=>{exit&&!shuttingDown()&&!draining()&&shutdown("owner_gone",0)}).finally(()=>{ownerCheck=!1}))},tickIntervalMs);return()=>{clearInterval(ticker),owner.stop()}}init_rpc_public_key();var __addDisposableResource=function(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value},__disposeResources=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e,env.hasError=!0}var r,s=0;function next(){for(;r=env.stack.pop();)try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){return fail(e),next()})}else s|=1}catch(e){fail(e)}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError=="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e});async function runHostSupervisor(launch){let env_1={stack:[],error:void 0,hasError:!1};try{let shutdown=function(reason,exitCode){return shutdownPromise??=performShutdown(teardown,reason,exitCode),shutdownPromise},paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID6(),generation=generationPaths(paths,instanceId),created=await mkdir9(generation.dir,{recursive:!0,mode:448}).catch(cause=>{throw new HostDaemonStateError(generation.dir,cause)}),startupRegistered=!1,_generationStartup=__addDisposableResource(env_1,{async[Symbol.asyncDispose](){created!==void 0&&!startupRegistered&&await rm7(generation.dir,{recursive:!0,force:!0})}},!0);await createGenerationDirectory(generation);let settings=await readSettingsFile(paths.settingsFile),policy=resolveHostPolicy(settings,process.env),publicSocket=launch.socket,publicEndpoint=process.platform==="win32"?void 0:new RpcPublicEndpoint(launch.agentDir??getAgentDir(),publicSocket),publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,hop=await prepareInternalHop(paths.dir),{internal,internalSocket,internalSecret,internalKey}=hop,state3={shuttingDown:!1,shutdownReason:void 0,childExitRecorded:Promise.resolve(),startupComplete:Promise.resolve(),publicSocketOwned:!1,publicSocketIdentity:void 0,endpointReplaced:!1},owner=new SupervisorOwner(generation.dir),activity=new SupervisorActivity({idleExitMs:policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs,internalSocket,...hop.transport,instanceId,settled:()=>state3.shuttingDown,onActivity:()=>owner.activity()}),watchers=[];declareHostChild(launch.childCommand);let child=spawnHostChild({launch,reportsStartup:hostChildReportsStartup(launch.childCommand),internalSocket,internal,...hop.transport,supervisorStart:hop.supervisorStart,lifetimeFifo:hop.lifetimeFifo,daemonDir:paths.dir,instanceId,cleanupPaths:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:launch.bindSocket!==void 0,platform:process.platform}),publicSocket}),childStartedAt=Date.now();await hostChildSpawned(child,generation.dir,hop.supervisorStart?.time),child.stdio[HOST_CHILD_WATCH_FD]?.on("error",()=>{}),child.pid!==void 0&&recordChildPid(generation.childPidFile,child.pid,()=>child.exitCode===null&&child.signalCode===null),child.once("exit",(code,signal)=>{let reason=state3.shutdownReason;if(state3.childExitRecorded=noteChildExit({daemonDir:paths.dir,generation,instanceId,code,signal,childStartedAt,...state3.shuttingDown&&reason!==void 0?{shutdown:{reason,supervisor:supervisorSender(instanceId)}}:{}}),state3.shuttingDown)return;let verdict=classifyChildExit(code,signal);state3.childExitRecorded.then(()=>shutdown(verdict.reason,verdict.exitCode))});let admission=new HostAdmission({protocolVersion:1,serverVersion:VERSION,capabilities:[],instanceId}),drain=new SupervisorDrain(child,()=>state3.shuttingDown,()=>admission.stop(),{file:generation.childDrainRequestFile,sender:supervisorSender(instanceId)}),server=createPublicProxy({internalSocket,...hop.transport,...publicSecret?{publicSecret}:{},...publicEndpoint?{publicEndpoint}:{},clients:activity.clients,admission,onDetach:()=>activity.refresh(),onAdmit:()=>owner.activity()});server.once("error",cause=>{state3.shuttingDown||shutdown(`public socket listener failed: ${errorMessage(cause)}`,1)}),watchers.push(startSupervisorTicker({idleExitMs:policy.idleExitMs,activity,owner,draining:()=>drain.active,shuttingDown:()=>state3.shuttingDown,shutdown}));let teardown={paths,generation,instanceId,publicSocket,server,internalDir:internal.dir,child,activity,drain,admission,state:state3,...publicEndpoint?{publicEndpoint}:{},stopWatchers:()=>{for(let stop of watchers.splice(0))stop()}},shutdownPromise;registerSupervisorSignals(shutdown,()=>drain.drain()),startupRegistered=!0;try{if((launch.ownerFd!==void 0||await readSettingsFile(generation.settingsFile))&&await owner.start(launch.ownerFd),await awaitInternalStartup({internalSocket,internalSecret,internalKey,openObserver:()=>activity.openObserver()}),state3.shuttingDown)return;state3.startupComplete=(async()=>{await publishSupervisorEndpoint({launch,server,publicSecret,publicEndpoint,generationDir:generation.dir,instanceId,settings,state:state3}),state3.publicSocketIdentity=await statSocketIdentity(publicSocket),state3.publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join20(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),state3.publicSocketIdentity),watchers.push(drainOnPublicSocketLoss(publicSocket,state3.publicSocketIdentity,()=>state3.shuttingDown||drain.active,drain,()=>{state3.endpointReplaced=!0},{file:paths.pointerFile,instanceId})),watchers.push(await drain.acceptRequests(generation))})(),await state3.startupComplete,supervisorPublished()}catch(cause){await shutdown(`startup failed: ${errorMessage(cause)}`,1)}if(state3.shuttingDown)return;process.platform==="win32"&&watchers.push(await watchWin32ChildIdentity(child,()=>state3.shuttingDown,()=>{shutdown("rpc host child exit observed by identity watchdog",0)})),writeHostReady(publicSocket,policy.coldStart,policy.idleExitMs),await new Promise(()=>{})}catch(e_1){env_1.error=e_1,env_1.hasError=!0}finally{let result_1=__disposeResources(env_1);result_1&&await result_1}}if(!isBundledNode&&isCliModuleEntry(import.meta.url)){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath4(import.meta.url)===realpathSync5(entry)}catch{return!1}}function claimOwnRuntimeSnapshot(){try{let packageDir=resolve4(dirname12(fileURLToPath4(import.meta.url)),"..","..");if(!readRuntimeSnapshotMarker(packageDir))return;withRuntimeLock(dirname12(packageDir),()=>claimRuntimeSnapshot(packageDir,process.pid))}catch{}}if(isEntryScript()){claimOwnRuntimeSnapshot(),process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT=APP_NAME,process.emitWarning=(()=>{}),brandProfile(),scrubBrandFromEnvironment();let supervisorArgs=findInternalSupervisorArgs(process.argv.slice(2)),launch=supervisorArgs?parseSupervisorArgs(supervisorArgs):void 0;launch||(writeStderrLine("invalid internal RPC host supervisor arguments"),process.exit(2)),await runHostSupervisor(launch)}
|
|
54
|
+
`),[HOST_PUBLIC_SOCKET_ENV]:options.publicSocket,[HOST_STARTUP_EVENTS_ENV]:startupHandOff2}}function spawnHostChild(options){let{launch,internalSocket}=options,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),bootstrap=launch.presenterBootstrapFd!==void 0&&!childLaunch.shell;bootstrap&&childLaunch.args.push("--mcp-presenter-fd","4");let startupStdio=hostChildStdio(bootstrap,options.reportsStartup===!0),child=spawnWithPrivateFds((command,args,options2)=>childProcess.spawn(command,args,options2),childLaunch.command,childLaunch.args,{env:hostChildEnvironment(options,options.reportsStartup?hostChildStartupHandOff(startupStdio.fillers):void 0),shell:childLaunch.shell,stdio:startupStdio.stdio,windowsHide:!0},{final:!0});if(releaseStartupFillers(child,startupStdio.fillers),launch.presenterBootstrapFd!==void 0){let fd=launch.presenterBootstrapFd;Promise.resolve().then(()=>(init_mcp_presenter_bootstrap(),mcp_presenter_bootstrap_exports)).then(({presenterBootstrapStream:presenterBootstrapStream2,relayPresenterBootstrap:relayPresenterBootstrap2})=>{let upstream=presenterBootstrapStream2(fd);if(upstream&&bootstrap)return relayPresenterBootstrap2(upstream,child);upstream?.destroy(),child.stdio[4]?.destroy()}).catch(()=>child.stdio[4]?.destroy())}return options.internalKey&&(child.stdin?.on("error",()=>{}),child.stdin?.write(options.internalKey)),child}import{rm as rm6}from"node:fs/promises";init_process_identity();import{rename as rename5,rm as rm5}from"node:fs/promises";init_process_identity();var TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;var BYTES_PER_MEGABYTE=1024*1024;init_process_identity();async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId);if(await hostChildAlive(generation))return;let record2=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record2!==void 0&&record2.pid!==owner.pid)return;if(owner.superseded===!0){await rm5(generation.dir,{recursive:!0,force:!0});return}let ownsPointer=parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId;ownsPointer&&await rm5(paths.settingsFile,{force:!0}),await rm5(generation.dir,{recursive:!0,force:!0}),ownsPointer&&await rm5(paths.pointerFile,{force:!0})}var LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_ERROR_MS=5e3;function loopLagErrorMs(env=process.env){return parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}var STALL_WAIT_SLICE_MS=5e3;async function waitOutStalledChild(options){let{child,generation,signalledAt}=options,maxMs=childStalledStopMaxMs(),untilAt=signalledAt+maxMs,stalled=()=>hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:STOP_STALL_EVIDENCE_MAX_AGE_MS}).catch(()=>!1),waited=0;try{for(;Date.now()<untilAt&&await stalled();){waited===0&&supervisorLog(`host child is stalled; waiting up to ${maxMs}ms (${CHILD_STALLED_STOP_MAX_MS_ENV})`),await writeStopProgress(generation,{at:new Date().toISOString(),phase:"waiting_stalled_child",untilAt:new Date(untilAt).toISOString()}).catch(()=>{});let slice=Math.min(STALL_WAIT_SLICE_MS,untilAt-Date.now()),exited=await options.waitForExit(child,slice);if(waited+=slice,exited)break}}finally{await clearStopProgress(generation)}return waited}var WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3;function supervisorSender(instanceId){return{pid:process.pid,kind:"supervisor",generation:instanceId}}function childExited(child){return child.exitCode!==null||child.signalCode!==null}async function performShutdown(context,reason,exitCode){let{state:state3,child}=context;state3.shuttingDown=!0,state3.shutdownReason=reason,context.admission.stop();let childStopStarted=!1,hardExit;try{context.drain.stop(),writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`),childStopStarted=!0,await stopChild(context,reason),await state3.childExitRecorded,await state3.startupComplete.then(void 0,()=>{}),context.stopWatchers(),await context.admission.flush(),context.activity.clients.destroyAll(),process.platform==="win32"&&(hardExit=setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS)),context.drain.active||await closeShieldedEndpoint(context.publicSocket,()=>closeServer(context.server)),context.internalDir&&await rm6(context.internalDir,{recursive:!0,force:!0}),context.activity.stopObserver(),state3.publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedEndpoint(context.publicSocket,state3.publicSocketIdentity,context.instanceId,supervisorLog),await releaseGeneration(context.paths,{instanceId:context.instanceId,pid:process.pid,superseded:state3.endpointReplaced})}catch(cause){supervisorLog(`shutdown failed for host child pid ${child.pid??"unknown"}: ${errorMessage(cause)}`),exitCode=1;try{childStopStarted||await reapChildAfterFailure(child),await state3.childExitRecorded}catch(reapCause){supervisorLog(`shutdown recovery failed for host child pid ${child.pid??"unknown"}: ${errorMessage(reapCause)}`)}}finally{await context.publicEndpoint?.dispose().catch(cause=>{supervisorLog(`endpoint key cleanup failed: ${errorMessage(cause)}`)}),hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}async function stopChild(context,reason){let{child,generation}=context,pid=child.pid;if(childExited(child)||pid===void 0)return;let termAttempted=!1,killAttempted=!1;try{let outer=await readStopIntent(generation).catch(cause=>{supervisorLog(`cannot read child stop intent: ${errorMessage(cause)}`)}),at=new Date().toISOString(),intent=layeredSupervisorIntent(outer,supervisorSender(context.instanceId),{targetPid:pid,reason,at});await writeStopIntent(generation,intent,supervisorLog);let signalledAt=Date.now();if(termAttempted=!0,signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS))return;let stallWaitMs=await waitOutStalledChild({child,generation,signalledAt,waitForExit:waitForChildExit});if(childExited(child))return;if(stallWaitMs>0){let escalated={...intent,reason:`${intent.reason}; escalated_after_stall_wait=${stallWaitMs}`};await writeStopIntent(generation,escalated,supervisorLog)}if(killAttempted=!0,signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after SIGKILL`)}catch(cause){if(!killAttempted)try{await reapChildAfterFailure(child,termAttempted)}catch(reapCause){supervisorLog(`shutdown recovery failed for host child pid ${pid??"unknown"}: ${errorMessage(reapCause)}`)}throw cause}}async function reapChildAfterFailure(child,termAttempted=!1){let pid=child.pid;if(!(childExited(child)||pid===void 0)&&!(!termAttempted&&(signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)))&&(signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS)))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after recovery SIGKILL`)}function signalChild(pid,signal){try{return process.kill(pid,signal),!0}catch{return!1}}function waitForChildExit(child,timeoutMs){return childExited(child)?Promise.resolve(!0):new Promise(resolve5=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve5(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve5(!0)};child.once("exit",onExit2)})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}function startSupervisorTicker(options){let{activity,owner,draining,shuttingDown,shutdown}=options,tickIntervalMs=Math.max(20,Math.min(1e3,options.idleExitMs/4)),ownerCheck=!1,ticker=setInterval(()=>{!draining()&&activity.refresh()==="exit"&&activity.clients.unclassifiedCount===0&&shutdown("idle",0),!ownerCheck&&!shuttingDown()&&!draining()&&(ownerCheck=!0,owner.shouldExit(activity).then(exit=>{exit&&!shuttingDown()&&!draining()&&shutdown("owner_gone",0)}).finally(()=>{ownerCheck=!1}))},tickIntervalMs);return()=>{clearInterval(ticker),owner.stop()}}init_rpc_public_key();var __addDisposableResource=function(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value},__disposeResources=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e,env.hasError=!0}var r,s=0;function next(){for(;r=env.stack.pop();)try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){return fail(e),next()})}else s|=1}catch(e){fail(e)}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError=="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e});async function runHostSupervisor(launch){let env_1={stack:[],error:void 0,hasError:!1};try{let shutdown=function(reason,exitCode){return shutdownPromise??=performShutdown(teardown,reason,exitCode),shutdownPromise},paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID6(),generation=generationPaths(paths,instanceId),created=await mkdir9(generation.dir,{recursive:!0,mode:448}).catch(cause=>{throw new HostDaemonStateError(generation.dir,cause)}),startupRegistered=!1,_generationStartup=__addDisposableResource(env_1,{async[Symbol.asyncDispose](){created!==void 0&&!startupRegistered&&await rm7(generation.dir,{recursive:!0,force:!0})}},!0);await createGenerationDirectory(generation);let settings=await readSettingsFile(paths.settingsFile),policy=resolveHostPolicy(settings,process.env),publicSocket=launch.socket,publicEndpoint=process.platform==="win32"?void 0:new RpcPublicEndpoint(launch.agentDir??getAgentDir(),publicSocket),publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,hop=await prepareInternalHop(paths.dir),{internal,internalSocket,internalSecret,internalKey}=hop,state3={shuttingDown:!1,shutdownReason:void 0,childExitRecorded:Promise.resolve(),startupComplete:Promise.resolve(),publicSocketOwned:!1,publicSocketIdentity:void 0,endpointReplaced:!1},owner=new SupervisorOwner(generation.dir),activity=new SupervisorActivity({idleExitMs:policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs,internalSocket,...hop.transport,instanceId,settled:()=>state3.shuttingDown,onActivity:()=>owner.activity()}),watchers=[];declareHostChild(launch.childCommand);let child=spawnHostChild({launch,reportsStartup:hostChildReportsStartup(launch.childCommand),internalSocket,internal,...hop.transport,supervisorStart:hop.supervisorStart,lifetimeFifo:hop.lifetimeFifo,daemonDir:paths.dir,instanceId,cleanupPaths:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:launch.bindSocket!==void 0,platform:process.platform}),publicSocket}),childStartedAt=Date.now();await hostChildSpawned(child,generation.dir,hop.supervisorStart?.time),child.stdio[HOST_CHILD_WATCH_FD]?.on("error",()=>{}),child.pid!==void 0&&recordChildPid(generation.childPidFile,child.pid,()=>child.exitCode===null&&child.signalCode===null),child.once("exit",(code,signal)=>{let reason=state3.shutdownReason;if(state3.childExitRecorded=noteChildExit({daemonDir:paths.dir,generation,instanceId,code,signal,childStartedAt,...state3.shuttingDown&&reason!==void 0?{shutdown:{reason,supervisor:supervisorSender(instanceId)}}:{}}),state3.shuttingDown)return;let verdict=classifyChildExit(code,signal);state3.childExitRecorded.then(()=>shutdown(verdict.reason,verdict.exitCode))});let admission=new HostAdmission({protocolVersion:1,serverVersion:VERSION,capabilities:[],instanceId}),drain=new SupervisorDrain(child,()=>state3.shuttingDown,()=>admission.stop(),{file:generation.childDrainRequestFile,sender:supervisorSender(instanceId)}),server=createPublicProxy({internalSocket,...hop.transport,...publicSecret?{publicSecret}:{},...publicEndpoint?{publicEndpoint}:{},clients:activity.clients,admission,onDetach:()=>activity.refresh(),onAdmit:()=>owner.activity()});server.once("error",cause=>{state3.shuttingDown||shutdown(`public socket listener failed: ${errorMessage(cause)}`,1)}),watchers.push(startSupervisorTicker({idleExitMs:policy.idleExitMs,activity,owner,draining:()=>drain.active,shuttingDown:()=>state3.shuttingDown,shutdown}));let teardown={paths,generation,instanceId,publicSocket,server,internalDir:internal.dir,child,activity,drain,admission,state:state3,...publicEndpoint?{publicEndpoint}:{},stopWatchers:()=>{for(let stop of watchers.splice(0))stop()}},shutdownPromise;registerSupervisorSignals(shutdown,()=>drain.drain()),startupRegistered=!0;try{if((launch.ownerFd!==void 0||await readSettingsFile(generation.settingsFile))&&await owner.start(launch.ownerFd),await awaitInternalStartup({internalSocket,internalSecret,internalKey,openObserver:()=>activity.openObserver()}),state3.shuttingDown)return;state3.startupComplete=(async()=>{await publishSupervisorEndpoint({launch,server,publicSecret,publicEndpoint,generationDir:generation.dir,instanceId,settings,state:state3}),state3.publicSocketIdentity=await statSocketIdentity(publicSocket),state3.publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join20(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),state3.publicSocketIdentity),watchers.push(drainOnPublicSocketLoss(publicSocket,state3.publicSocketIdentity,()=>state3.shuttingDown||drain.active,drain,()=>{state3.endpointReplaced=!0},{file:paths.pointerFile,instanceId})),watchers.push(await drain.acceptRequests(generation))})(),await state3.startupComplete,supervisorPublished()}catch(cause){await shutdown(`startup failed: ${errorMessage(cause)}`,1)}if(state3.shuttingDown)return;process.platform==="win32"&&watchers.push(await watchWin32ChildIdentity(child,()=>state3.shuttingDown,()=>{shutdown("rpc host child exit observed by identity watchdog",0)})),writeHostReady(publicSocket,policy.coldStart,policy.idleExitMs),await new Promise(()=>{})}catch(e_1){env_1.error=e_1,env_1.hasError=!0}finally{let result_1=__disposeResources(env_1);result_1&&await result_1}}if(!isBundledNode&&isCliModuleEntry(import.meta.url)){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath4(import.meta.url)===realpathSync5(entry)}catch{return!1}}function claimOwnRuntimeSnapshot(){try{let packageDir=resolve4(dirname12(fileURLToPath4(import.meta.url)),"..","..");if(!readRuntimeSnapshotMarker(packageDir))return;withRuntimeLock(dirname12(packageDir),()=>claimRuntimeSnapshot(packageDir,process.pid))}catch{}}if(isEntryScript()){claimOwnRuntimeSnapshot(),process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT=APP_NAME,process.emitWarning=(()=>{}),brandProfile(),scrubBrandFromEnvironment();let supervisorArgs=findInternalSupervisorArgs(process.argv.slice(2)),launch=supervisorArgs?parseSupervisorArgs(supervisorArgs):void 0;launch||(writeStderrLine("invalid internal RPC host supervisor arguments"),process.exit(2)),await runHostSupervisor(launch)}
|
package/dist/bundle/index.js
CHANGED
|
@@ -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,RELOCATION_TOOL_NAMES,ReservedCustodyKey,SESSION_CONTROL_DELIVERY_TYPE,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,isSessionControlDeliveryDetails,isToolCallEventType,isWriteToolResult,kernelToolsStorage,killGuardProtectedPids,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSkillBlock,prepareBranchEntries,readKillGuardSetting,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-7TGZJH6Z.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-WF5R2VSP.js";import"./chunks/chunk-XBG63MJZ.js";import"./chunks/chunk-V3JSQ3PG.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-6MHCFJDB.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-CX32K5KD.js";import"./chunks/chunk-USKWGPA6.js";import"./chunks/chunk-FEQDJBDL.js";import{AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,UserMessageComponent,copyToClipboard}from"./chunks/chunk-KFWHLVVH.js";import"./chunks/chunk-H33A33M4.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-32I42CEY.js";import"./chunks/chunk-22YXCY7K.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-K5JLYACP.js";import"./chunks/chunk-H2FBGZNP.js";import"./chunks/chunk-FUQJK2TU.js";import"./chunks/chunk-436DNN4Z.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-TQHNFP77.js";import{SecretInputUnavailableError}from"./chunks/chunk-C7HEEBFH.js";import"./chunks/chunk-47PPZKPO.js";import"./chunks/chunk-MOVB6H22.js";import"./chunks/chunk-POZMRM6V.js";import"./chunks/chunk-22JICYKS.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-YP47G4YP.js";import"./chunks/chunk-Y3TMJV3J.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-5MWHZH2O.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-HHSYTDKO.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunks/chunk-Y7Z7XPUF.js";import{parseArgs}from"./chunks/chunk-54YTJCYZ.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-I5ASHSLZ.js";import"./chunks/chunk-2CNSCMYC.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-A4F4J2KH.js";import"./chunks/chunk-ZIIDIVTG.js";import"./chunks/chunk-EAEEM2KN.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-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-PPQPV52D.js";import"./chunks/chunk-GG2JO3CL.js";import"./chunks/chunk-UBNUGVW6.js";import"./chunks/chunk-ADT36P7E.js";import"./chunks/chunk-KLAX467B.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-YUTUD26F.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-6VWIMHMH.js";import"./chunks/chunk-SOMFLLPD.js";import"./chunks/chunk-KDUJCDLM.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-ADOOQW3O.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-LAMRXFHZ.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-RI5ABX7A.js";import{activateKillGuardRuntime,activeKillGuardEnvironment,getPowerShellConfig,getShellConfig,releaseKillGuardRuntime,withBundledBunCommands}from"./chunks/chunk-E6L5VZSM.js";import"./chunks/chunk-2CSLJLM6.js";import"./chunks/chunk-EVTTLPIY.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-YUVC7SJB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-ZDHAJROE.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-HJDTYAPV.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-WIOV3AXZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-OKMHSVCA.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import{decideKillGuardRequest}from"./chunks/chunk-6APXZK7W.js";import{KILL_GUARD_TAG}from"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-6NMTFURP.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-5JUCTKYS.js";import"./chunks/chunk-KUIEHAPR.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.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-QN2BHP3M.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.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,releaseKillGuardRuntime,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,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,RELOCATION_TOOL_NAMES,ReservedCustodyKey,SESSION_CONTROL_DELIVERY_TYPE,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,isSessionControlDeliveryDetails,isToolCallEventType,isWriteToolResult,kernelToolsStorage,killGuardProtectedPids,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSkillBlock,prepareBranchEntries,readKillGuardSetting,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionControlSenderOf,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-D5MRJWUK.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-X5ZVYNOL.js";import"./chunks/chunk-7PSBD5KS.js";import"./chunks/chunk-GSKCWXXG.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-WGRKM3N6.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-CF5OGBC4.js";import"./chunks/chunk-GTJJ73DE.js";import"./chunks/chunk-FEQDJBDL.js";import{AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,UserMessageComponent,copyToClipboard}from"./chunks/chunk-C7OKUC7L.js";import"./chunks/chunk-H33A33M4.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-RQ6CHXQ2.js";import"./chunks/chunk-22YXCY7K.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-XCMII2VQ.js";import"./chunks/chunk-SJI6UB23.js";import"./chunks/chunk-436DNN4Z.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-TQHNFP77.js";import{SecretInputUnavailableError}from"./chunks/chunk-C7HEEBFH.js";import"./chunks/chunk-47PPZKPO.js";import"./chunks/chunk-MOVB6H22.js";import{registerRpcRemoteSource}from"./chunks/chunk-NH7SYIGN.js";import"./chunks/chunk-WAOGBBZR.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-VD7AKTGP.js";import"./chunks/chunk-Y3TMJV3J.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-2FDW2LQL.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-HLM46XEB.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunks/chunk-Y7Z7XPUF.js";import{parseArgs}from"./chunks/chunk-54YTJCYZ.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-I5ASHSLZ.js";import"./chunks/chunk-2CNSCMYC.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-I3PHVJAS.js";import"./chunks/chunk-R2Z7CX77.js";import"./chunks/chunk-EAEEM2KN.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-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-PPQPV52D.js";import"./chunks/chunk-4E7GDG4H.js";import"./chunks/chunk-UBNUGVW6.js";import"./chunks/chunk-ADT36P7E.js";import"./chunks/chunk-KLAX467B.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-YUTUD26F.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-6VWIMHMH.js";import"./chunks/chunk-SOMFLLPD.js";import"./chunks/chunk-KDUJCDLM.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-ADOOQW3O.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-LNPAT22L.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-TMXRR3N7.js";import{activateKillGuardRuntime,activeKillGuardEnvironment,getPowerShellConfig,getShellConfig,releaseKillGuardRuntime,withBundledBunCommands}from"./chunks/chunk-DSWDJ7HT.js";import"./chunks/chunk-GKAYPJ4E.js";import"./chunks/chunk-EVTTLPIY.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-YUVC7SJB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-ZDHAJROE.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-HJDTYAPV.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-WIOV3AXZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-OKMHSVCA.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import{decideKillGuardRequest}from"./chunks/chunk-6APXZK7W.js";import{KILL_GUARD_TAG}from"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-ECW7VBMB.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-YK3ZZCHI.js";import"./chunks/chunk-T2SMQPRE.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.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-QN2BHP3M.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.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,sessionControlSenderOf,sessionEntryToContextMessages,setJobWidgetAuthorResolver,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -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-
|
|
3
|
+
import"./chunks/chunk-TIPKAMSS.js";import{main}from"./chunks/chunk-D5MRJWUK.js";import"./chunks/chunk-X5ZVYNOL.js";import"./chunks/chunk-7PSBD5KS.js";import"./chunks/chunk-GSKCWXXG.js";import"./chunks/chunk-WGRKM3N6.js";import"./chunks/chunk-CF5OGBC4.js";import"./chunks/chunk-GTJJ73DE.js";import{configureHttpDispatcher}from"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-C7OKUC7L.js";import"./chunks/chunk-H33A33M4.js";import"./chunks/chunk-RQ6CHXQ2.js";import"./chunks/chunk-22YXCY7K.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-XCMII2VQ.js";import"./chunks/chunk-SJI6UB23.js";import"./chunks/chunk-436DNN4Z.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-TQHNFP77.js";import"./chunks/chunk-C7HEEBFH.js";import"./chunks/chunk-47PPZKPO.js";import"./chunks/chunk-MOVB6H22.js";import"./chunks/chunk-NH7SYIGN.js";import"./chunks/chunk-WAOGBBZR.js";import"./chunks/chunk-VD7AKTGP.js";import"./chunks/chunk-Y3TMJV3J.js";import"./chunks/chunk-MTQQ2VQH.js";import"./chunks/chunk-2FDW2LQL.js";import"./chunks/chunk-HLM46XEB.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-Y7Z7XPUF.js";import"./chunks/chunk-54YTJCYZ.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-I5ASHSLZ.js";import"./chunks/chunk-2CNSCMYC.js";import"./chunks/chunk-7WYJAYHH.js";import"./chunks/chunk-I3PHVJAS.js";import"./chunks/chunk-R2Z7CX77.js";import"./chunks/chunk-EAEEM2KN.js";import"./chunks/chunk-YI6KRJDC.js";import"./chunks/chunk-DBQBJTMF.js";import"./chunks/chunk-SF4MQDKZ.js";import"./chunks/chunk-VPVD5G32.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-PPQPV52D.js";import"./chunks/chunk-4E7GDG4H.js";import"./chunks/chunk-UBNUGVW6.js";import"./chunks/chunk-ADT36P7E.js";import"./chunks/chunk-KLAX467B.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-YUTUD26F.js";import"./chunks/chunk-WB4BUHOH.js";import"./chunks/chunk-6VWIMHMH.js";import"./chunks/chunk-SOMFLLPD.js";import"./chunks/chunk-KDUJCDLM.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-ADOOQW3O.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-LNPAT22L.js";import"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-DSWDJ7HT.js";import"./chunks/chunk-GKAYPJ4E.js";import"./chunks/chunk-EVTTLPIY.js";import"./chunks/chunk-BPNSOZ2C.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-YUVC7SJB.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-ZDHAJROE.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-Z6TEQEZO.js";import"./chunks/chunk-HJDTYAPV.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-WIOV3AXZ.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-OKMHSVCA.js";import"./chunks/chunk-JGKH3D6W.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-NDNQ23SK.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-6APXZK7W.js";import"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-GLTOBXZY.js";import"./chunks/chunk-ECW7VBMB.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-YK3ZZCHI.js";import"./chunks/chunk-T2SMQPRE.js";import"./chunks/chunk-RUGTHELO.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.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-QN2BHP3M.js";import"./chunks/chunk-AOTHPTMU.js";import"./chunks/chunk-O5RYI3IW.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":"
|
|
1
|
+
{"buildId":"b6fa378403bc3ebb","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ProjectTrustContext } from "../core/extensions/types.ts";
|
|
2
|
+
import type { AppMode } from "../core/project-trust.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The `project_trust` handler context of a run that cannot ask: every question answers "no answer", and notices go to
|
|
5
|
+
* stderr outside the TUI. It imports no startup UI, so the RPC session path can build it without reaching the
|
|
6
|
+
* terminal's synchronous config and package probes (senpi#6185).
|
|
7
|
+
*/
|
|
8
|
+
export declare function createHeadlessProjectTrustContext(options: {
|
|
9
|
+
cwd: string;
|
|
10
|
+
mode: AppMode;
|
|
11
|
+
hasUI: boolean;
|
|
12
|
+
}): ProjectTrustContext;
|
|
13
|
+
//# sourceMappingURL=project-trust-headless.d.ts.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
function toExtensionMode(mode) {
|
|
3
|
+
switch (mode) {
|
|
4
|
+
case "interactive":
|
|
5
|
+
return "tui";
|
|
6
|
+
case "print":
|
|
7
|
+
case "json":
|
|
8
|
+
case "rpc":
|
|
9
|
+
return mode;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The `project_trust` handler context of a run that cannot ask: every question answers "no answer", and notices go to
|
|
14
|
+
* stderr outside the TUI. It imports no startup UI, so the RPC session path can build it without reaching the
|
|
15
|
+
* terminal's synchronous config and package probes (senpi#6185).
|
|
16
|
+
*/
|
|
17
|
+
export function createHeadlessProjectTrustContext(options) {
|
|
18
|
+
return {
|
|
19
|
+
cwd: options.cwd,
|
|
20
|
+
mode: toExtensionMode(options.mode),
|
|
21
|
+
hasUI: options.hasUI,
|
|
22
|
+
ui: {
|
|
23
|
+
select: async () => undefined,
|
|
24
|
+
confirm: async () => false,
|
|
25
|
+
input: async () => undefined,
|
|
26
|
+
notify: (message, type = "info") => {
|
|
27
|
+
if (options.mode !== "interactive") {
|
|
28
|
+
const color = type === "error" ? chalk.red : type === "warning" ? chalk.yellow : chalk.cyan;
|
|
29
|
+
console.error(color(message));
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=project-trust-headless.js.map
|
|
@@ -1,57 +1,20 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { createHeadlessProjectTrustContext } from "./project-trust-headless.js";
|
|
2
2
|
import { showStartupInput, showStartupSelector } from "./startup-ui.js";
|
|
3
|
-
function toExtensionMode(mode) {
|
|
4
|
-
switch (mode) {
|
|
5
|
-
case "interactive":
|
|
6
|
-
return "tui";
|
|
7
|
-
case "print":
|
|
8
|
-
case "json":
|
|
9
|
-
case "rpc":
|
|
10
|
-
return mode;
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
3
|
export function createProjectTrustContext(options) {
|
|
4
|
+
const headless = createHeadlessProjectTrustContext(options);
|
|
5
|
+
if (!options.hasUI || options.mode !== "interactive") {
|
|
6
|
+
return headless;
|
|
7
|
+
}
|
|
14
8
|
return {
|
|
15
|
-
|
|
16
|
-
mode: toExtensionMode(options.mode),
|
|
17
|
-
hasUI: options.hasUI,
|
|
9
|
+
...headless,
|
|
18
10
|
ui: {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return showStartupSelector(options.settingsManager, title, selectOptions.map((option) => ({ label: option, value: option })));
|
|
27
|
-
},
|
|
28
|
-
confirm: async (title, message) => {
|
|
29
|
-
if (!options.hasUI) {
|
|
30
|
-
return false;
|
|
31
|
-
}
|
|
32
|
-
if (options.mode !== "interactive") {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
return ((await showStartupSelector(options.settingsManager, `${title}\n${message}`, [
|
|
36
|
-
{ label: "Yes", value: true },
|
|
37
|
-
{ label: "No", value: false },
|
|
38
|
-
])) ?? false);
|
|
39
|
-
},
|
|
40
|
-
input: async (title, placeholder) => {
|
|
41
|
-
if (!options.hasUI) {
|
|
42
|
-
return undefined;
|
|
43
|
-
}
|
|
44
|
-
if (options.mode !== "interactive") {
|
|
45
|
-
return undefined;
|
|
46
|
-
}
|
|
47
|
-
return showStartupInput(options.settingsManager, title, placeholder);
|
|
48
|
-
},
|
|
49
|
-
notify: (message, type = "info") => {
|
|
50
|
-
if (options.mode !== "interactive") {
|
|
51
|
-
const color = type === "error" ? chalk.red : type === "warning" ? chalk.yellow : chalk.cyan;
|
|
52
|
-
console.error(color(message));
|
|
53
|
-
}
|
|
54
|
-
},
|
|
11
|
+
...headless.ui,
|
|
12
|
+
select: async (title, selectOptions) => showStartupSelector(options.settingsManager, title, selectOptions.map((option) => ({ label: option, value: option }))),
|
|
13
|
+
confirm: async (title, message) => (await showStartupSelector(options.settingsManager, `${title}\n${message}`, [
|
|
14
|
+
{ label: "Yes", value: true },
|
|
15
|
+
{ label: "No", value: false },
|
|
16
|
+
])) ?? false,
|
|
17
|
+
input: async (title, placeholder) => showStartupInput(options.settingsManager, title, placeholder),
|
|
55
18
|
},
|
|
56
19
|
};
|
|
57
20
|
}
|
|
@@ -25,6 +25,8 @@ export type DeliveryResult = {
|
|
|
25
25
|
} | {
|
|
26
26
|
readonly ok: false;
|
|
27
27
|
readonly error: string;
|
|
28
|
+
/** Nothing was delivered because another live process holds the session: retry later, not a failure. */
|
|
29
|
+
readonly sessionHeld?: true;
|
|
28
30
|
};
|
|
29
31
|
/** Called with the delivery process pid as soon as it exists, so the session lock can record it. */
|
|
30
32
|
export interface DeliveryContext {
|
|
@@ -44,6 +46,8 @@ export interface ProcessLaunch {
|
|
|
44
46
|
readonly stdin?: string;
|
|
45
47
|
/** win32: pass `args` to the process unquoted (a `cmd.exe /s /c "..."` command line). */
|
|
46
48
|
readonly windowsVerbatimArguments?: boolean;
|
|
49
|
+
/** An exit code meaning the session was held and nothing ran; only the senpi resume delivery sets it. */
|
|
50
|
+
readonly sessionHeldExitCode?: number;
|
|
47
51
|
}
|
|
48
52
|
/**
|
|
49
53
|
* POSIX gate: the delivery command only starts once the runner writes a line on fd 3, which it does
|
|
@@ -6,6 +6,7 @@ import { spawn } from "node:child_process";
|
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
7
7
|
import { resolveMovedPath } from "../core/extensions/builtin/moved-path-guard/resolve.js";
|
|
8
8
|
import { liveSessionHolders } from "../core/session-holders.js";
|
|
9
|
+
import { SESSION_HELD_EXIT_CODE } from "./session-opening.js";
|
|
9
10
|
import { killWindowsProcessTree } from "../utils/shell.js";
|
|
10
11
|
// A job written before the desktop moved its data home fires against the moved files; its own file keeps the old paths (senpi#2898).
|
|
11
12
|
export function movedJobPaths(job) {
|
|
@@ -87,6 +88,10 @@ export function runDeliveryProcess(launch, timeoutMs, context = {}) {
|
|
|
87
88
|
resolve({ ok: false, error: failure });
|
|
88
89
|
else if (code === 0)
|
|
89
90
|
resolve({ ok: true });
|
|
91
|
+
else if (launch.sessionHeldExitCode !== undefined && code === launch.sessionHeldExitCode) {
|
|
92
|
+
const reason = stderr.trim() || "the session is open in another process";
|
|
93
|
+
resolve({ ok: false, error: reason, sessionHeld: true });
|
|
94
|
+
}
|
|
90
95
|
else {
|
|
91
96
|
const status = code === null ? `signal ${signal}` : `exit code ${code}`;
|
|
92
97
|
resolve({ ok: false, error: stderr.trim() ? `${status}: ${stderr.trim()}` : status });
|
|
@@ -146,6 +151,7 @@ export function sessionResumeDelivery(senpi, timeoutMs) {
|
|
|
146
151
|
args: [...senpi.args, "-p", "--session", event.sessionFile ?? event.sessionId, event.message],
|
|
147
152
|
cwd: event.cwd,
|
|
148
153
|
env: eventEnv(event),
|
|
154
|
+
sessionHeldExitCode: SESSION_HELD_EXIT_CODE,
|
|
149
155
|
}, timeoutMs, context);
|
|
150
156
|
};
|
|
151
157
|
}
|
|
@@ -125,6 +125,14 @@ async function deliverClaimed(options, job, onSpawn) {
|
|
|
125
125
|
catch (error) {
|
|
126
126
|
result = { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
127
127
|
}
|
|
128
|
+
if (!result.ok && result.sessionHeld === true) {
|
|
129
|
+
// Opened elsewhere after the shouldDefer check: nothing ran, so this is a deferral, not a failed occurrence.
|
|
130
|
+
// Put the claimed generation back (a recurring job's re-arm is undone first) and retry like any deferral.
|
|
131
|
+
if (job.everyMs !== null)
|
|
132
|
+
await rearmRecurringJob(options.dir, job);
|
|
133
|
+
await restorePending(options.dir, record, job.id);
|
|
134
|
+
return { event: "deferred", id: job.id, sessionId: job.sessionId, reason: result.error };
|
|
135
|
+
}
|
|
128
136
|
await settleOccurrence(options.dir, record, { ...job, fireCount: occurrence, lastFiredAt: firedAt }, occurrence, result);
|
|
129
137
|
return {
|
|
130
138
|
event: "fired",
|
|
@@ -1,5 +1,24 @@
|
|
|
1
|
+
import { checkSessionHolders } from "../core/foreign-session-holders.ts";
|
|
1
2
|
import type { AppMode } from "../core/project-trust.ts";
|
|
2
3
|
import type { SessionManager } from "../core/session-manager.ts";
|
|
3
4
|
/** Warn after the runtime publishes its holder; an advisory lookup must not abort startup. */
|
|
4
5
|
export declare function prepareSessionOpening(manager: SessionManager, mode: AppMode): Promise<void>;
|
|
6
|
+
export type StartupAdmission = "open" | "cancelled" | "refused";
|
|
7
|
+
/**
|
|
8
|
+
* Exit code of a startup refused because another live process holds the session. The schedule runner reads it to
|
|
9
|
+
* leave the occurrence pending instead of failing it (senpi#5756).
|
|
10
|
+
*/
|
|
11
|
+
export declare const SESSION_HELD_EXIT_CODE = 76;
|
|
12
|
+
export interface StartupAdmissionIo {
|
|
13
|
+
readonly canAsk: boolean;
|
|
14
|
+
readonly confirm: (question: string) => Promise<boolean>;
|
|
15
|
+
readonly err: (line: string) => void;
|
|
16
|
+
readonly lookup?: typeof checkSessionHolders;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Startup admission for a session another live process holds (senpi#5756, the startup path of #5744): opening it
|
|
20
|
+
* would start a second run of the same session. Without a person to ask it is refused with the holder named; on a
|
|
21
|
+
* terminal the person chooses to cancel or to take over (the holder is asked to exit first, as /resume does).
|
|
22
|
+
*/
|
|
23
|
+
export declare function admitStartupSession(sessionFile: string | undefined, io: StartupAdmissionIo): Promise<StartupAdmission>;
|
|
5
24
|
//# sourceMappingURL=session-opening.d.ts.map
|