@code-yeongyu/senpi 2026.11.6-2 → 2026.11.6-3
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 +30 -0
- package/dist/bundle/chunks/{bun-extension-importer-RCGPQTI2.js → bun-extension-importer-GQ6IKEXD.js} +2 -2
- package/dist/bundle/chunks/{chunk-QN2BHP3M.js → chunk-44BJPS5I.js} +1 -1
- package/dist/bundle/chunks/{chunk-C7OKUC7L.js → chunk-4BATXPB7.js} +1 -1
- package/dist/bundle/chunks/{chunk-RQ6CHXQ2.js → chunk-5LKB732P.js} +1 -1
- package/dist/bundle/chunks/{chunk-X5ZVYNOL.js → chunk-6CEDL5S2.js} +1 -1
- package/dist/bundle/chunks/{chunk-HLM46XEB.js → chunk-7DRWPZ3N.js} +1 -1
- package/dist/bundle/chunks/{chunk-7PSBD5KS.js → chunk-BASS47UD.js} +1 -1
- package/dist/bundle/chunks/{chunk-ECW7VBMB.js → chunk-CFEHJ4VU.js} +1 -1
- package/dist/bundle/chunks/{chunk-TIPKAMSS.js → chunk-EO2VPZ2K.js} +1 -1
- package/dist/bundle/chunks/{chunk-LNPAT22L.js → chunk-F5JLDCYD.js} +8 -7
- package/dist/bundle/chunks/{chunk-GSKCWXXG.js → chunk-JMQOLOC2.js} +1 -1
- package/dist/bundle/chunks/chunk-L7ZIS3MC.js +106 -0
- package/dist/bundle/chunks/{chunk-47PPZKPO.js → chunk-LM6DOWQH.js} +4 -4
- package/dist/bundle/chunks/chunk-LPYBKMPT.js +2 -0
- package/dist/bundle/chunks/{chunk-GNSMNSL7.js → chunk-LUZVGPQ7.js} +2 -2
- package/dist/bundle/chunks/{chunk-7III44PV.js → chunk-MJTCZUXS.js} +1 -1
- package/dist/bundle/chunks/{chunk-2FDW2LQL.js → chunk-SB6MXNO5.js} +1 -1
- package/dist/bundle/chunks/chunk-UODSYQ2D.js +2 -0
- package/dist/bundle/chunks/{chunk-D5MRJWUK.js → chunk-V2QAYGOK.js} +216 -224
- package/dist/bundle/chunks/{chunk-WGRKM3N6.js → chunk-X53PD4ZC.js} +1 -1
- package/dist/bundle/chunks/{cli-main-T74YJGIF.js → cli-main-RWHDZKTQ.js} +1 -1
- package/dist/bundle/chunks/{dispatch-BAK2YZKD.js → dispatch-VDIYSXQN.js} +1 -1
- package/dist/bundle/chunks/{hand-entry-AYRUGE2A.js → hand-entry-G5LYF62Q.js} +1 -1
- package/dist/bundle/chunks/{host-command-YRXZE4TV.js → host-command-I2JZ5JM7.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-N7IN7ZDV.js → host-session-command-Y52NFPP2.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-PA7DGVS6.js +2 -0
- package/dist/bundle/chunks/main-OBL6375C.js +2 -0
- package/dist/bundle/chunks/{multi-session-host-XSUJDHFZ.js → multi-session-host-NM6I5BWZ.js} +20 -17
- package/dist/bundle/chunks/{package-manager-cli-GLUNPQJU.js → package-manager-cli-GNRQ5MVR.js} +1 -1
- package/dist/bundle/chunks/{role-RRFFHZF5.js → role-F56BS2ZQ.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-G4KIP7XS.js +2 -0
- package/dist/bundle/chunks/{run-attached-tui-W236SEOR.js → run-attached-tui-XTGPAGYM.js} +1 -1
- package/dist/bundle/chunks/{runtime-session-OBXYK4PI.js → runtime-session-VO3X4OE3.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-B2EJTBOE.js → schedule-command-L4M3TSQ3.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-YIMLHGLG.js → session-control-endpoint-V46WMCDF.js} +1 -1
- package/dist/bundle/chunks/{session-picker-E6ZONUJB.js → session-picker-AG6KSR5A.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +87 -83
- package/dist/bundle/cli.js +2 -2
- 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/core/agent-session-runtime.d.ts +2 -0
- package/dist/core/agent-session-runtime.js +9 -2
- package/dist/core/agent-session.d.ts +24 -3
- package/dist/core/agent-session.js +94 -28
- package/dist/core/credential-pool/rotation-slots.d.ts +3 -3
- package/dist/core/credential-pool/state-store.d.ts +1 -1
- package/dist/core/egress/hpke.d.ts +63 -0
- package/dist/core/egress/hpke.js +188 -0
- package/dist/core/egress/placement-claim.d.ts +69 -0
- package/dist/core/egress/placement-claim.js +115 -0
- package/dist/core/egress/pool-state.d.ts +18 -0
- package/dist/core/egress/pool-state.js +5 -0
- package/dist/core/egress/sealed-format.d.ts +101 -0
- package/dist/core/egress/sealed-format.js +174 -0
- package/dist/core/egress/wire.d.ts +226 -0
- package/dist/core/egress/wire.js +47 -0
- package/dist/core/extensions/builtin/ask-user/escape-residue.d.ts +50 -0
- package/dist/core/extensions/builtin/ask-user/escape-residue.js +113 -0
- package/dist/core/extensions/builtin/ask-user/extension.js +7 -1
- package/dist/core/extensions/builtin/ask-user/resume.js +2 -1
- package/dist/core/extensions/builtin/ask-user/tool.d.ts +3 -0
- package/dist/core/extensions/builtin/ask-user/tool.js +8 -0
- package/dist/core/extensions/builtin/goal/index.js +46 -0
- package/dist/core/extensions/builtin/goal/stop-pause.d.ts +1 -0
- package/dist/core/extensions/builtin/goal/stop-pause.js +4 -2
- package/dist/core/extensions/builtin/permission-system/index.js +10 -4
- package/dist/core/extensions/builtin/permission-system/preset-registry.d.ts +2 -0
- package/dist/core/extensions/builtin/permission-system/preset-registry.js +11 -0
- package/dist/core/extensions/builtin/permission-system/settings.d.ts +2 -0
- package/dist/core/extensions/builtin/permission-system/settings.js +10 -1
- package/dist/core/extensions/builtin/terminal/tools/bash.d.ts +1 -1
- package/dist/core/extensions/builtin/terminal/tools/bash.js +38 -9
- package/dist/core/extensions/builtin/terminal/tools/context.d.ts +3 -0
- package/dist/core/extensions/bun-extension-importer.js +4 -3
- package/dist/core/extensions/bun-extension-load-turns.d.ts +4 -0
- package/dist/core/extensions/bun-extension-load-turns.js +45 -0
- package/dist/core/extensions/bun-extension-registry.d.ts +1 -0
- package/dist/core/extensions/bun-extension-registry.js +19 -1
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/session-dialog-api.d.ts +5 -0
- package/dist/core/extensions/session-dialog-api.js +13 -0
- package/dist/core/extensions/types.d.ts +14 -1
- package/dist/core/permission-decision.d.ts +22 -0
- package/dist/core/permission-decision.js +53 -0
- package/dist/core/permission-mode.d.ts +56 -0
- package/dist/core/permission-mode.js +133 -0
- package/dist/core/retry-fallback/controller-types.d.ts +6 -0
- package/dist/core/retry-fallback/controller.d.ts +8 -0
- package/dist/core/retry-fallback/controller.js +31 -3
- package/dist/core/retry-fallback/unusable.d.ts +23 -1
- package/dist/core/retry-fallback/unusable.js +80 -1
- package/dist/core/retry-fallback/usage-limit.d.ts +1 -1
- package/dist/core/retry-fallback/usage-limit.js +6 -3
- package/dist/core/sdk.js +2 -0
- package/dist/core/session-log.js +1 -1
- package/dist/core/stall-warning.d.ts +41 -0
- package/dist/core/stall-warning.js +72 -0
- package/dist/core/turn-origin.d.ts +27 -0
- package/dist/core/turn-origin.js +54 -0
- package/dist/modes/rpc/client-input-handler.d.ts +2 -0
- package/dist/modes/rpc/client-input-handler.js +2 -0
- package/dist/modes/rpc/connection-handler.js +16 -5
- package/dist/modes/rpc/connection-roles.d.ts +6 -0
- package/dist/modes/rpc/connection-roles.js +13 -0
- package/dist/modes/rpc/delegated-drive-origin.d.ts +9 -0
- package/dist/modes/rpc/delegated-drive-origin.js +16 -0
- package/dist/modes/rpc/effect-commands.d.ts +6 -0
- package/dist/modes/rpc/host-bare-endpoint-registration.d.ts +7 -0
- package/dist/modes/rpc/host-bare-endpoint-registration.js +35 -0
- package/dist/modes/rpc/host-capabilities.d.ts +2 -0
- package/dist/modes/rpc/host-capabilities.js +3 -0
- package/dist/modes/rpc/host-handover-parked.d.ts +11 -0
- package/dist/modes/rpc/host-handover-parked.js +17 -0
- package/dist/modes/rpc/host-handover-reopen.js +18 -6
- package/dist/modes/rpc/host-handover-resident-writer.d.ts +16 -0
- package/dist/modes/rpc/host-handover-resident-writer.js +57 -0
- package/dist/modes/rpc/host-warm.d.ts +16 -1
- package/dist/modes/rpc/host-warm.js +33 -6
- package/dist/modes/rpc/method-classes-schema-session.d.ts +9 -0
- package/dist/modes/rpc/method-classes-schema-session.js +1 -0
- package/dist/modes/rpc/method-classes-schema.d.ts +9 -0
- package/dist/modes/rpc/method-classes.d.ts +1 -0
- package/dist/modes/rpc/method-classes.js +2 -0
- package/dist/modes/rpc/multi-session-host.js +6 -1
- package/dist/modes/rpc/permission-preset-command.d.ts +6 -0
- package/dist/modes/rpc/permission-preset-command.js +27 -0
- package/dist/modes/rpc/rpc-mutation-response-types.d.ts +7 -0
- package/dist/modes/rpc/rpc-session-command-types.d.ts +4 -0
- package/dist/modes/rpc/rpc-session-event-types.d.ts +5 -2
- package/dist/modes/rpc/rpc-session-state-types.d.ts +2 -1
- package/dist/modes/rpc/rpc-session-state.js +2 -0
- package/dist/modes/rpc/session-attachment-commands.js +3 -3
- package/dist/modes/rpc/session-event-writer-connections.js +1 -0
- package/dist/modes/rpc/session-event-writer.d.ts +1 -1
- package/dist/modes/rpc/session-registry-attach.d.ts +0 -9
- package/dist/modes/rpc/session-registry-attach.js +16 -3
- package/dist/modes/rpc/session-registry-types.d.ts +2 -0
- package/dist/modes/rpc/session-registry.d.ts +2 -0
- package/dist/modes/rpc/session-registry.js +16 -3
- package/dist/modes/rpc/session-router-close.js +43 -6
- package/dist/modes/rpc/session-router-context.js +2 -0
- package/dist/modes/rpc/session-router-occupancy.js +2 -11
- package/dist/modes/rpc/session-router-open-profile.js +4 -0
- package/dist/modes/rpc/session-router-open.d.ts +1 -1
- package/dist/modes/rpc/session-router-open.js +6 -17
- package/dist/modes/rpc/session-router-residency.d.ts +24 -0
- package/dist/modes/rpc/session-router-residency.js +90 -0
- package/dist/modes/rpc/session-router-routing.js +7 -1
- package/dist/modes/rpc/session-status.js +4 -1
- package/dist/modes/rpc/session-worker.js +4 -0
- package/dist/modes/rpc/worker-session-registry.js +5 -2
- package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
- package/docs/engine-socket/fixtures/rpc-inbound-samples.json +12 -2
- package/docs/extensions.md +12 -0
- package/docs/rpc.md +72 -12
- 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-C7HEEBFH.js +0 -2
- package/dist/bundle/chunks/chunk-XCMII2VQ.js +0 -98
- package/dist/bundle/chunks/interactive-mode-B5SQDLH7.js +0 -2
- package/dist/bundle/chunks/main-UQFVFCNY.js +0 -2
- package/dist/bundle/chunks/rpc-mode-JYN3E7P7.js +0 -2
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-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")}
|
|
3
|
+
import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunks/chunk-MJTCZUXS.js";import"./chunks/chunk-EO2VPZ2K.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-GLTOBXZY.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-CFEHJ4VU.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-RWHDZKTQ.js")}
|
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-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};
|
|
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-V2QAYGOK.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-6CEDL5S2.js";import"./chunks/chunk-BASS47UD.js";import"./chunks/chunk-JMQOLOC2.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-X53PD4ZC.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-4BATXPB7.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-5LKB732P.js";import"./chunks/chunk-22YXCY7K.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-L7ZIS3MC.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-UODSYQ2D.js";import"./chunks/chunk-LM6DOWQH.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-SB6MXNO5.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-7DRWPZ3N.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-F5JLDCYD.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-LPYBKMPT.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-CFEHJ4VU.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-44BJPS5I.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-EO2VPZ2K.js";import{main}from"./chunks/chunk-V2QAYGOK.js";import"./chunks/chunk-6CEDL5S2.js";import"./chunks/chunk-BASS47UD.js";import"./chunks/chunk-JMQOLOC2.js";import"./chunks/chunk-X53PD4ZC.js";import"./chunks/chunk-CF5OGBC4.js";import"./chunks/chunk-GTJJ73DE.js";import{configureHttpDispatcher}from"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-4BATXPB7.js";import"./chunks/chunk-H33A33M4.js";import"./chunks/chunk-5LKB732P.js";import"./chunks/chunk-22YXCY7K.js";import"./chunks/chunk-3QPE75AR.js";import"./chunks/chunk-4GKU755E.js";import"./chunks/chunk-L7ZIS3MC.js";import"./chunks/chunk-SJI6UB23.js";import"./chunks/chunk-436DNN4Z.js";import"./chunks/chunk-J2I56WLK.js";import"./chunks/chunk-TQHNFP77.js";import"./chunks/chunk-UODSYQ2D.js";import"./chunks/chunk-LM6DOWQH.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-SB6MXNO5.js";import"./chunks/chunk-7DRWPZ3N.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-F5JLDCYD.js";import"./chunks/chunk-TMXRR3N7.js";import"./chunks/chunk-LPYBKMPT.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-CFEHJ4VU.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-44BJPS5I.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":"da02d749ca61757c","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
|
|
@@ -25,6 +25,8 @@ export interface AgentSessionLaunchProfile {
|
|
|
25
25
|
/** Host-owned public endpoint evidence; never sourced from client session context. */
|
|
26
26
|
holderEndpoint?: SessionHolderEndpoint;
|
|
27
27
|
permissionPreset?: string;
|
|
28
|
+
/** `host_default`: `permissionPreset` is the host's own default (an embedder's host option), not a client's choice. */
|
|
29
|
+
permissionPresetSource?: "host_default";
|
|
28
30
|
creationModel?: {
|
|
29
31
|
provider: string;
|
|
30
32
|
modelId: string;
|
|
@@ -2,6 +2,7 @@ import { constants, copyFileSync, existsSync, mkdirSync } from "node:fs";
|
|
|
2
2
|
import { basename, join, parse, resolve } from "node:path";
|
|
3
3
|
import { resolvePath } from "../utils/paths.js";
|
|
4
4
|
import { emitSessionShutdownEvent } from "./extensions/runner.js";
|
|
5
|
+
import { applyClientPermissionMode, clientNamedPreset, markHostDefaultPresetFlag, withClientPreset, } from "./permission-mode.js";
|
|
5
6
|
import { assertSessionCwdExists } from "./session-cwd.js";
|
|
6
7
|
import { holdSessionFile } from "./session-holders.js";
|
|
7
8
|
import { SessionManager } from "./session-manager.js";
|
|
@@ -55,6 +56,8 @@ export class AgentSessionRuntime {
|
|
|
55
56
|
this._diagnostics = _diagnostics;
|
|
56
57
|
this._modelFallbackMessage = _modelFallbackMessage;
|
|
57
58
|
this._launchProfile = launchProfile;
|
|
59
|
+
markHostDefaultPresetFlag(_session, launchProfile);
|
|
60
|
+
applyClientPermissionMode(_session, clientNamedPreset(launchProfile), { announce: false });
|
|
58
61
|
this._sessionHold = holdActiveSession(_session.sessionManager, wasFlushed(_session.sessionManager), launchProfile?.holderEndpoint);
|
|
59
62
|
}
|
|
60
63
|
/** Stops advertising the open session to other processes; a runtime that replaces this one holds its own. */
|
|
@@ -98,13 +101,15 @@ export class AgentSessionRuntime {
|
|
|
98
101
|
* fork) keep it.
|
|
99
102
|
*/
|
|
100
103
|
setPermissionPreset(preset) {
|
|
101
|
-
this._launchProfile =
|
|
104
|
+
this._launchProfile = withClientPreset(this._launchProfile ?? { cwd: this.cwd }, preset);
|
|
102
105
|
this._session.extensionRunner.setFlagValue("permission-preset", preset);
|
|
103
106
|
// While a replacement is in flight (or after one failed) the live session is the disposed one:
|
|
104
107
|
// nothing may rebuild it. The preset is recorded above, and apply() syncs the next replacement to
|
|
105
108
|
// it before that one goes live. There is no flag to clear: the check is the session itself.
|
|
106
|
-
if (this._session !== this._disposedSession)
|
|
109
|
+
if (this._session !== this._disposedSession) {
|
|
107
110
|
this.syncFullAccessTrust(this._session, preset);
|
|
111
|
+
applyClientPermissionMode(this._session, preset, { announce: true });
|
|
112
|
+
}
|
|
108
113
|
}
|
|
109
114
|
/**
|
|
110
115
|
* Keeps a Full-access-only project trust in step with the preset (senpi#3414, #3420). Leaving Full
|
|
@@ -317,6 +322,8 @@ export class AgentSessionRuntime {
|
|
|
317
322
|
this._session = result.session;
|
|
318
323
|
if (profile?.permissionPreset !== undefined)
|
|
319
324
|
this._session.extensionRunner.setFlagValue("permission-preset", profile.permissionPreset);
|
|
325
|
+
markHostDefaultPresetFlag(this._session, profile);
|
|
326
|
+
applyClientPermissionMode(this._session, clientNamedPreset(profile), { announce: false });
|
|
320
327
|
if (profile?.promptSurface !== undefined)
|
|
321
328
|
this._session.setPromptSurface(profile.promptSurface);
|
|
322
329
|
if (profile?.browserEngine !== undefined)
|
|
@@ -37,6 +37,7 @@ import { type UserActivityKind } from "./extensions/user-activity.ts";
|
|
|
37
37
|
import { ExternalAdmission } from "./external-admission.ts";
|
|
38
38
|
import { type HoldInputResult } from "./held-inputs.ts";
|
|
39
39
|
import { type InputOrigin } from "./input-origin.ts";
|
|
40
|
+
import { type ConnectionOrigin } from "./turn-origin.ts";
|
|
40
41
|
import { type ItemizedAdmission } from "./itemized-send.ts";
|
|
41
42
|
import { type CustomMessage } from "./messages.ts";
|
|
42
43
|
import { type ModelChangeOrigin } from "./model-change-origin.ts";
|
|
@@ -87,15 +88,17 @@ type WithParentToolCallId<E> = E extends {
|
|
|
87
88
|
} ? E & {
|
|
88
89
|
parentToolCallId?: string;
|
|
89
90
|
} : E;
|
|
90
|
-
/** Why a session-level abort happened, when the caller knows:
|
|
91
|
-
export
|
|
91
|
+
/** Why a session-level abort happened, when the caller knows: a session replacement, or the host process stopping. */
|
|
92
|
+
export type AgentAbortCause = {
|
|
92
93
|
readonly kind: "session_replaced";
|
|
93
94
|
/** What replaced the session: `new_session`, `fork` or a `switch_session`/resume. */
|
|
94
95
|
readonly reason: "new" | "fork" | "resume";
|
|
95
96
|
/** The replacement's transcript and durable session id, when they are known before the teardown. */
|
|
96
97
|
readonly targetSessionFile?: string;
|
|
97
98
|
readonly targetSessionId?: string;
|
|
98
|
-
}
|
|
99
|
+
} | {
|
|
100
|
+
readonly kind: "host_shutdown";
|
|
101
|
+
};
|
|
99
102
|
type AgentSessionAgentEndEvent = Extract<AgentEvent, {
|
|
100
103
|
type: "agent_end";
|
|
101
104
|
}> & {
|
|
@@ -331,6 +334,13 @@ export type AgentSessionEvent = WithParentToolCallId<Exclude<AgentEvent, {
|
|
|
331
334
|
type: "retry_fallback_succeeded";
|
|
332
335
|
model: string;
|
|
333
336
|
chainKey: string;
|
|
337
|
+
} | {
|
|
338
|
+
/** A limit that named no model family was checked on another family once (senpi#5596). */
|
|
339
|
+
type: "usage_limit_scope_probe";
|
|
340
|
+
provider: string;
|
|
341
|
+
heldFamily: string;
|
|
342
|
+
probeFamily: string;
|
|
343
|
+
outcome: "served" | "widened";
|
|
334
344
|
} | {
|
|
335
345
|
type: "retry_fallback_reverted";
|
|
336
346
|
from: string;
|
|
@@ -606,6 +616,8 @@ export interface QueuedInputOptions extends ClientMessageIdentity {
|
|
|
606
616
|
interactiveUser?: boolean;
|
|
607
617
|
/** RPC input that arrived as a thread call from another session: its chain hop count, reported on the `input` event. */
|
|
608
618
|
chainCount?: number;
|
|
619
|
+
/** Internal, RPC input: whether its record arrived on a local or a delegated (remote device) connection. */
|
|
620
|
+
connectionOrigin?: ConnectionOrigin;
|
|
609
621
|
/** Persist the prepared queue record before publishing or enqueuing it. */
|
|
610
622
|
onQueuedInput?: (input: PreparedClientInput) => void;
|
|
611
623
|
/** A steer meant only for this turn (`currentTurnId`): checked where it enters the queue, else `TurnConflictError`. */
|
|
@@ -640,6 +652,8 @@ export interface PromptOptions extends ClientMessageIdentity {
|
|
|
640
652
|
interactiveUser?: boolean;
|
|
641
653
|
/** RPC input that arrived as a thread call from another session: its chain hop count, reported on the `input` event. */
|
|
642
654
|
chainCount?: number;
|
|
655
|
+
/** Internal, RPC input: whether its record arrived on a local or a delegated (remote device) connection. */
|
|
656
|
+
connectionOrigin?: ConnectionOrigin;
|
|
643
657
|
/**
|
|
644
658
|
* Send command-shaped text that no command handles to the model as plain text. Without it, such
|
|
645
659
|
* interactive or RPC input is rejected with `UnknownCommandError`.
|
|
@@ -734,6 +748,8 @@ export declare class AgentSession {
|
|
|
734
748
|
private _eventListeners;
|
|
735
749
|
private readonly _structuredLane;
|
|
736
750
|
private _agentEventQueue;
|
|
751
|
+
/** What `_agentEventQueue` still holds, so a tool call stalled behind it can say what it waits on (senpi#6189). */
|
|
752
|
+
private readonly _agentEventQueueLedger;
|
|
737
753
|
private readonly _lifecycleEvents;
|
|
738
754
|
/**
|
|
739
755
|
* Exact message objects whose message_end persistence is still queued.
|
|
@@ -1460,6 +1476,11 @@ export declare class AgentSession {
|
|
|
1460
1476
|
get currentDeadline(): TurnDeadline | undefined;
|
|
1461
1477
|
/** Adapter for the deadline owner interface: a deadline stop that could not complete. */
|
|
1462
1478
|
_warnDeadline(event: TurnDeadlineWarning, detail: string): void;
|
|
1479
|
+
/**
|
|
1480
|
+
* End the running turn because the process hosting this session is stopping (an RPC host shutting down or
|
|
1481
|
+
* restarting): a system abort whose `agent_end` carries `abortCause: { kind: "host_shutdown" }`, never a user abort.
|
|
1482
|
+
*/
|
|
1483
|
+
abortForHostShutdown(): Promise<void>;
|
|
1463
1484
|
/** Adapter for the deadline owner interface: end the turn through the normal system abort. */
|
|
1464
1485
|
abortTurnForDeadline(): Promise<void>;
|
|
1465
1486
|
/**
|
|
@@ -95,6 +95,8 @@ import { deliveryIdOf, ExternalAdmission } from "./external-admission.js";
|
|
|
95
95
|
import { HELD_INPUT_ENTRY, HeldInputs, heldInputHistory } from "./held-inputs.js";
|
|
96
96
|
import { shouldWarnHighReasoning } from "./high-reasoning-warning.js";
|
|
97
97
|
import { customTurnOrigin, inputAttributionOf, inputOriginOf } from "./input-origin.js";
|
|
98
|
+
import { inputTurnMark, markInputTurnOrigin, noteRunStart, noteUserMessageStart, } from "./turn-origin.js";
|
|
99
|
+
import { releaseDecisionPreset } from "./permission-decision.js";
|
|
98
100
|
import { markInterrupted } from "./interrupted-tool-result.js";
|
|
99
101
|
import { deliveredReceipts, itemNoticeMessage, QueuedDeliveryCleared, } from "./itemized-send.js";
|
|
100
102
|
import { LazyToolActivation } from "./lazy-tool-activation.js";
|
|
@@ -156,6 +158,7 @@ import { formatSkillInvocationPrompt, formatSkillReferenceBody, parseSkillInvoca
|
|
|
156
158
|
import { BUILTIN_SLASH_COMMANDS } from "./slash-commands.js";
|
|
157
159
|
import { bootstrapRuntime, buildToolRegistry, isBuiltinExtensionPath, } from "./runtime/bootstrap.js";
|
|
158
160
|
import { toolInfoOf } from "./tool-info.js";
|
|
161
|
+
import { PendingQueueLedger, queueEntryLabel, STALL_WARNING_MS, watchForStall, } from "./stall-warning.js";
|
|
159
162
|
import { stopResumeDirective } from "./stop-resume-directive.js";
|
|
160
163
|
import { StructuredSessionLane } from "./structured-session-lane.js";
|
|
161
164
|
import { clampThinkingSelection, getSupportedThinkingLevels, getThinkingClampNotice, supportsMax, supportsXhigh, } from "./thinking-levels.js";
|
|
@@ -436,6 +439,8 @@ export class AgentSession {
|
|
|
436
439
|
this._unregisterMemoryReport = () => { };
|
|
437
440
|
this._eventListeners = [];
|
|
438
441
|
this._agentEventQueue = Promise.resolve();
|
|
442
|
+
/** What `_agentEventQueue` still holds, so a tool call stalled behind it can say what it waits on (senpi#6189). */
|
|
443
|
+
this._agentEventQueueLedger = new PendingQueueLedger();
|
|
439
444
|
this._lifecycleEvents = new LifecycleEventSequencer();
|
|
440
445
|
/**
|
|
441
446
|
* Exact message objects whose message_end persistence is still queued.
|
|
@@ -669,7 +674,10 @@ export class AgentSession {
|
|
|
669
674
|
if (event.type === "agent_start") {
|
|
670
675
|
this._lifecycleBinding.startRun();
|
|
671
676
|
this._requestSelectedModel = undefined;
|
|
677
|
+
noteRunStart(this.sessionManager);
|
|
672
678
|
}
|
|
679
|
+
if (event.type === "message_start" && event.message.role === "user")
|
|
680
|
+
noteUserMessageStart(this.sessionManager, event.message);
|
|
673
681
|
// Bind now: the core can start another run before this event's asynchronous delivery.
|
|
674
682
|
const bound = event.type === "agent_start" ? { ...event, runId: this._lifecycleBinding.controller.ledger.runId } : event;
|
|
675
683
|
queuedEvent = bound;
|
|
@@ -758,7 +766,8 @@ export class AgentSession {
|
|
|
758
766
|
this._lifecycleEvents.release(heldLifecycle, (held) => this._emit(held));
|
|
759
767
|
return this._processAgentEvent(queuedEvent, signal);
|
|
760
768
|
};
|
|
761
|
-
const
|
|
769
|
+
const tracked = this._agentEventQueueLedger.track(queueEntryLabel(queuedEvent), deliverThenProcess);
|
|
770
|
+
const processing = this._agentEventQueue.then(tracked, tracked);
|
|
762
771
|
this._agentEventQueue =
|
|
763
772
|
pendingEnd !== undefined
|
|
764
773
|
? processing.finally(() => {
|
|
@@ -780,7 +789,8 @@ export class AgentSession {
|
|
|
780
789
|
this._structuredLane = new StructuredSessionLane(config.internalChannel, (deliver) => {
|
|
781
790
|
if (!this._unsubscribeAgent)
|
|
782
791
|
return;
|
|
783
|
-
|
|
792
|
+
const tracked = this._agentEventQueueLedger.track("structured_record", deliver);
|
|
793
|
+
this._agentEventQueue = this._agentEventQueue.then(tracked, tracked);
|
|
784
794
|
}, (control) => this._recoveryIdentity?.own(control));
|
|
785
795
|
this.sessionManager = config.sessionManager;
|
|
786
796
|
this._unsubscribeRecovery = this.sessionManager.onRecovery((recovery) => {
|
|
@@ -1147,7 +1157,7 @@ export class AgentSession {
|
|
|
1147
1157
|
this._modelRuntime.hasConfiguredAuth(model.provider));
|
|
1148
1158
|
if (available)
|
|
1149
1159
|
return available;
|
|
1150
|
-
throw new AccountUsageLimitError(sessionModel.provider, this._retryFallback.accountError(sessionModel.provider), this._retryFallback.accountResetAt(sessionModel.provider));
|
|
1160
|
+
throw new AccountUsageLimitError(sessionModel.provider, this._retryFallback.accountError(sessionModel.provider), this._retryFallback.accountResetAt(sessionModel.provider), this._retryFallback.widenedFamiliesOf(sessionModel.provider));
|
|
1151
1161
|
}
|
|
1152
1162
|
_logCompactionModelFallback(override, reason, sessionModel) {
|
|
1153
1163
|
const notice = `${override}\u0000${reason}`;
|
|
@@ -1290,33 +1300,56 @@ export class AgentSession {
|
|
|
1290
1300
|
};
|
|
1291
1301
|
}
|
|
1292
1302
|
async preflightToolCall(toolCall, args, options = {}) {
|
|
1303
|
+
// Neither wait below has a deadline of its own: one that never settles is logged once, never cut short (senpi#6189).
|
|
1304
|
+
// The call's own `timeout` bounds its execution, not this phase, which includes a human permission decision.
|
|
1305
|
+
const thresholdMs = STALL_WARNING_MS;
|
|
1306
|
+
const warnStalled = (event, elapsedMs, queue) => this._sessionLogger.warn(event, {
|
|
1307
|
+
toolCallId: toolCall.id,
|
|
1308
|
+
toolName: toolCall.name,
|
|
1309
|
+
...(options.parentToolCallId ? { parentToolCallId: options.parentToolCallId } : {}),
|
|
1310
|
+
thresholdMs,
|
|
1311
|
+
elapsedMs,
|
|
1312
|
+
...queue,
|
|
1313
|
+
});
|
|
1293
1314
|
if (options.waitForEventQueue !== false) {
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
}
|
|
1302
|
-
const runner = this._extensionRunner;
|
|
1303
|
-
if (!runner.hasHandlers("tool_call")) {
|
|
1304
|
-
return undefined;
|
|
1315
|
+
const queueWatch = watchForStall(thresholdMs, (elapsedMs) => warnStalled("tool_call_event_queue_stalled", elapsedMs, this._agentEventQueueLedger.snapshot()));
|
|
1316
|
+
try {
|
|
1317
|
+
await this._agentEventQueue;
|
|
1318
|
+
}
|
|
1319
|
+
finally {
|
|
1320
|
+
queueWatch.stop();
|
|
1321
|
+
}
|
|
1305
1322
|
}
|
|
1323
|
+
const preflightWatch = watchForStall(thresholdMs, (elapsedMs) => warnStalled("tool_call_preflight_stalled", elapsedMs));
|
|
1306
1324
|
try {
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1325
|
+
const signal = options.signal ?? this.agent.signal;
|
|
1326
|
+
// A call released by Stop never runs: block it without asking its hooks (a permission prompt) about it.
|
|
1327
|
+
// Callers such as executeTool only honor an explicit block, so returning nothing here would let it run.
|
|
1328
|
+
if ((await this._waitForToolBarrier(toolCall, signal)) && signal?.aborted) {
|
|
1329
|
+
return { block: true, reason: "Operation aborted" };
|
|
1330
|
+
}
|
|
1331
|
+
const runner = this._extensionRunner;
|
|
1332
|
+
if (!runner.hasHandlers("tool_call")) {
|
|
1333
|
+
return undefined;
|
|
1334
|
+
}
|
|
1335
|
+
try {
|
|
1336
|
+
return await runner.emitToolCall({
|
|
1337
|
+
type: "tool_call",
|
|
1338
|
+
toolName: toolCall.name,
|
|
1339
|
+
toolCallId: toolCall.id,
|
|
1340
|
+
...(options.parentToolCallId ? { parentToolCallId: options.parentToolCallId } : {}),
|
|
1341
|
+
input: args,
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
catch (err) {
|
|
1345
|
+
if (err instanceof Error) {
|
|
1346
|
+
throw err;
|
|
1347
|
+
}
|
|
1348
|
+
throw new Error(`Extension failed, blocking execution: ${String(err)}`);
|
|
1318
1349
|
}
|
|
1319
|
-
|
|
1350
|
+
}
|
|
1351
|
+
finally {
|
|
1352
|
+
preflightWatch.stop();
|
|
1320
1353
|
}
|
|
1321
1354
|
}
|
|
1322
1355
|
async _emitAfterToolCallHooks(toolCall, args, result, isError, parentToolCallId) {
|
|
@@ -3448,6 +3481,7 @@ export class AgentSession {
|
|
|
3448
3481
|
*/
|
|
3449
3482
|
dispose() {
|
|
3450
3483
|
this._disposed = true;
|
|
3484
|
+
releaseDecisionPreset(this.sessionManager);
|
|
3451
3485
|
this._unsubscribeSecurityNotices?.();
|
|
3452
3486
|
this._unfollowProviderAccountChanges();
|
|
3453
3487
|
this.securityNotices.dispose();
|
|
@@ -3717,6 +3751,19 @@ export class AgentSession {
|
|
|
3717
3751
|
_warnDeadline(event, detail) {
|
|
3718
3752
|
this._sessionLogger.warn(event, { detail });
|
|
3719
3753
|
}
|
|
3754
|
+
/**
|
|
3755
|
+
* End the running turn because the process hosting this session is stopping (an RPC host shutting down or
|
|
3756
|
+
* restarting): a system abort whose `agent_end` carries `abortCause: { kind: "host_shutdown" }`, never a user abort.
|
|
3757
|
+
*/
|
|
3758
|
+
async abortForHostShutdown() {
|
|
3759
|
+
if (!this.isStreaming)
|
|
3760
|
+
return;
|
|
3761
|
+
if (this._abortCause === undefined)
|
|
3762
|
+
this._abortCause = { kind: "host_shutdown" };
|
|
3763
|
+
await this._abortActiveAgentAndRetry("system");
|
|
3764
|
+
if (!this.isIdle)
|
|
3765
|
+
await this._waitForIdleAfterAbort();
|
|
3766
|
+
}
|
|
3720
3767
|
/** Adapter for the deadline owner interface: end the turn through the normal system abort. */
|
|
3721
3768
|
async abortTurnForDeadline() {
|
|
3722
3769
|
await this._abortActiveAgentAndRetry("system");
|
|
@@ -4595,7 +4642,21 @@ export class AgentSession {
|
|
|
4595
4642
|
const errorMessage = this._retryFallback.accountError(model.provider);
|
|
4596
4643
|
// Routing around a remembered failure did not observe another provider failure.
|
|
4597
4644
|
if (!(await this._retryFallback.tryFallback("transient", { errorMessage }, false))) {
|
|
4598
|
-
throw new AccountUsageLimitError(model.provider, errorMessage, this._retryFallback.accountResetAt(model.provider));
|
|
4645
|
+
throw new AccountUsageLimitError(model.provider, errorMessage, this._retryFallback.accountResetAt(model.provider), this._retryFallback.widenedFamiliesOf(model.provider));
|
|
4646
|
+
}
|
|
4647
|
+
}
|
|
4648
|
+
// A family held by a weekly limit that named no family binds automated turns the same way, so a loop
|
|
4649
|
+
// moves to another family or stops instead of hammering the held one (senpi#5596, senpi#3131).
|
|
4650
|
+
const heldFamily = this.model && !this._pendingModelSwitch && attributionOf(options) !== "user"
|
|
4651
|
+
? this._retryFallback.heldFamily(this.model)
|
|
4652
|
+
: undefined;
|
|
4653
|
+
if (this.model && heldFamily) {
|
|
4654
|
+
this._retryFallback.resetTurn();
|
|
4655
|
+
this._fallbackTurnFailures = [];
|
|
4656
|
+
if (!(await this._retryFallback.tryFallback("transient", { errorMessage: heldFamily.errorMessage }, false))) {
|
|
4657
|
+
throw new AccountUsageLimitError(this.model.provider, heldFamily.errorMessage, undefined, [
|
|
4658
|
+
heldFamily.family,
|
|
4659
|
+
]);
|
|
4599
4660
|
}
|
|
4600
4661
|
}
|
|
4601
4662
|
}
|
|
@@ -4890,6 +4951,7 @@ export class AgentSession {
|
|
|
4890
4951
|
...clientMessageIdentity(options),
|
|
4891
4952
|
};
|
|
4892
4953
|
this._userInputSources.set(userMessage, options?.source ?? "interactive");
|
|
4954
|
+
markInputTurnOrigin(userMessage, inputTurnMark(options ?? {}));
|
|
4893
4955
|
messages.push(userMessage);
|
|
4894
4956
|
// Consume next-turn messages transactionally: a final admission rejection
|
|
4895
4957
|
// restores them in their original order rather than dropping or duplicating
|
|
@@ -5402,6 +5464,9 @@ export class AgentSession {
|
|
|
5402
5464
|
// stays unstamped: unknown origin, never defaulted to a trusted source.
|
|
5403
5465
|
if (input.source !== undefined)
|
|
5404
5466
|
this._userInputSources.set(message, input.source);
|
|
5467
|
+
// Restored input with no source keeps no mark: an unmarked turn is engine work, never a trusted origin.
|
|
5468
|
+
if (input.source !== undefined)
|
|
5469
|
+
markInputTurnOrigin(message, inputTurnMark(input));
|
|
5405
5470
|
if (input.inputId !== undefined)
|
|
5406
5471
|
this._queuedInputDispositions.track(message, input.inputId);
|
|
5407
5472
|
this._queuedMessages.set(queuedId, message);
|
|
@@ -6376,7 +6441,8 @@ export class AgentSession {
|
|
|
6376
6441
|
return id;
|
|
6377
6442
|
},
|
|
6378
6443
|
emit: (event) => this._lifecycleEvents.emit(event, (lifecycle) => this._emit(lifecycle), (run) => {
|
|
6379
|
-
|
|
6444
|
+
const tracked = this._agentEventQueueLedger.track(queueEntryLabel(event), run);
|
|
6445
|
+
this._agentEventQueue = this._agentEventQueue.then(tracked, tracked);
|
|
6380
6446
|
void this._agentEventQueue.catch(() => { });
|
|
6381
6447
|
}),
|
|
6382
6448
|
holdInterruptedRun: () => {
|