@code-yeongyu/senpi 2026.11.2-3 → 2026.11.3-1
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 +28 -0
- package/dist/bundle/chunks/{anthropic-messages-WUPLDYD6.js → anthropic-messages-AFWQB3KN.js} +1 -1
- package/dist/bundle/chunks/{args-AOI4NEA6.js → args-O3WS4WCO.js} +1 -1
- package/dist/bundle/chunks/{chunk-O4GRBX4R.js → chunk-3WJ2DE2G.js} +1 -1
- package/dist/bundle/chunks/{chunk-LMIETUPG.js → chunk-4BF4FLT6.js} +1 -1
- package/dist/bundle/chunks/{chunk-T5ZJ2Q4O.js → chunk-4SENPCEA.js} +1 -1
- package/dist/bundle/chunks/chunk-5DZD623T.js +448 -0
- package/dist/bundle/chunks/{chunk-TXOR5BQL.js → chunk-6BSMXZKQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-VRWJJMHO.js → chunk-7565XQAU.js} +1 -1
- package/dist/bundle/chunks/{chunk-IWM5QRAE.js → chunk-7KLEFHSU.js} +1 -1
- package/dist/bundle/chunks/{chunk-FO56LSUK.js → chunk-BNIZP4OS.js} +1 -1
- package/dist/bundle/chunks/{chunk-L3V65XW7.js → chunk-CJWSQ6CK.js} +1 -1
- package/dist/bundle/chunks/{chunk-QLTQ3UUI.js → chunk-DAPBNRN5.js} +1 -1
- package/dist/bundle/chunks/{chunk-GIY7PGOH.js → chunk-DPBPO5OU.js} +1 -1
- package/dist/bundle/chunks/chunk-ESQBKTNG.js +2 -0
- package/dist/bundle/chunks/{chunk-N4TSAHRL.js → chunk-EVTTLPIY.js} +1 -1
- package/dist/bundle/chunks/{chunk-NYXXKS6D.js → chunk-F4OHTL2K.js} +3 -2
- package/dist/bundle/chunks/{chunk-TVMW2SUP.js → chunk-FJ2UCBOA.js} +2 -2
- package/dist/bundle/chunks/{chunk-KVPRQ5KN.js → chunk-FLM6GZPT.js} +1 -1
- package/dist/bundle/chunks/{chunk-P4AT7SBE.js → chunk-HBCNDC53.js} +1 -1
- package/dist/bundle/chunks/chunk-MOH5HOHX.js +2 -0
- package/dist/bundle/chunks/{chunk-7FUO655J.js → chunk-MOOFLKLI.js} +1 -1
- package/dist/bundle/chunks/{chunk-IHOQR7TU.js → chunk-PX7FF5LE.js} +1 -1
- package/dist/bundle/chunks/{chunk-QAM6AXA2.js → chunk-QTQ3ES2S.js} +12 -9
- package/dist/bundle/chunks/{chunk-FJSJUVQQ.js → chunk-TOOB6OLG.js} +3 -3
- package/dist/bundle/chunks/{chunk-662SCMTH.js → chunk-VPDQ6MOL.js} +1 -1
- package/dist/bundle/chunks/{chunk-BW4YXS7X.js → chunk-WCRNJYHO.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSVWKOAJ.js → chunk-ZNLCKKF6.js} +170 -226
- package/dist/bundle/chunks/{cli-main-534A3WSC.js → cli-main-XM5FWY3Z.js} +1 -1
- package/dist/bundle/chunks/{credential-accounts-OAK2E5O2.js → credential-accounts-YZYSKA7X.js} +1 -1
- package/dist/bundle/chunks/{health-write-EB4CPHXN.js → health-write-45CX64T2.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-U2PSNNWO.js → help-fast-path-3EDGRKQM.js} +1 -1
- package/dist/bundle/chunks/{host-command-WJIMRBGN.js → host-command-PZ4VYQIW.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-PWVPQ2OV.js → host-session-command-OJFARE5Q.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-NPHFDPGH.js → interactive-mode-7JSJVVIS.js} +1 -1
- package/dist/bundle/chunks/{login-health-7G2DZVOV.js → login-health-YOPTYRTU.js} +1 -1
- package/dist/bundle/chunks/{main-I6FJAFUP.js → main-3YGJ2O4I.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-7E26R5JF.js → multi-session-host-N2RQ7JSZ.js} +4 -4
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-VNBMMIL3.js → openai-codex-responses-YTWLG4OL.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-JLR32APM.js → openai-completions-TIFDYHZL.js} +1 -1
- package/dist/bundle/chunks/{openai-images-LEBNERSM.js → openai-images-OAEMY4RG.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-JCDUNMHA.js → openai-responses-L35NIG5Y.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-CBSDV36M.js → package-manager-cli-JPNA27E5.js} +1 -1
- package/dist/bundle/chunks/{role-LP6LVNCY.js → role-45Y7PQFC.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-ZDCNHIBE.js → rotation-stream-WXWJKJZN.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-GBBTN2WP.js → rpc-mode-Z7MN2ZWA.js} +1 -1
- package/dist/bundle/chunks/{run-attached-tui-PVLUHHJX.js → run-attached-tui-TI6MELEI.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-W45NYTTK.js → schedule-command-OZ5ESMIT.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-LFLUNALC.js → session-control-endpoint-5YKBYJOO.js} +1 -1
- package/dist/bundle/chunks/{session-picker-OZUINLD7.js → session-picker-CMRV72VA.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +324 -376
- package/dist/bundle/chunks/{state-store-SZARKD36.js → state-store-Q47AYMRI.js} +1 -1
- 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.d.ts +8 -0
- package/dist/core/agent-session.js +68 -60
- package/dist/core/credential-pool/classify.d.ts +3 -2
- package/dist/core/credential-pool/classify.js +10 -3
- package/dist/core/dynamic-prompt/build.d.ts +2 -1
- package/dist/core/dynamic-prompt/build.js +1 -2
- package/dist/core/dynamic-prompt/handoff.d.ts +1 -1
- package/dist/core/dynamic-prompt/handoff.js +9 -9
- package/dist/core/dynamic-prompt/identity.js +1 -1
- package/dist/core/dynamic-prompt/intent-gate.d.ts +1 -1
- package/dist/core/dynamic-prompt/intent-gate.js +8 -8
- package/dist/core/dynamic-prompt/policies.d.ts +1 -1
- package/dist/core/dynamic-prompt/policies.js +5 -7
- package/dist/core/dynamic-prompt/style.js +5 -5
- package/dist/core/dynamic-prompt/tool-section.d.ts +5 -0
- package/dist/core/dynamic-prompt/tool-section.js +8 -6
- package/dist/core/dynamic-prompt/verification.d.ts +6 -6
- package/dist/core/dynamic-prompt/verification.js +12 -12
- package/dist/core/dynamic-prompt/working-task.d.ts +1 -1
- package/dist/core/dynamic-prompt/working-task.js +3 -3
- package/dist/core/dynamic-prompt/workstation.js +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.d.ts +13 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.js +64 -2
- package/dist/core/extensions/builtin/anthropic-subscription/session-stream.js +5 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.d.ts +7 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.js +28 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.d.ts +2 -0
- package/dist/core/extensions/builtin/bash-timeout/index.d.ts +1 -1
- package/dist/core/extensions/builtin/bash-timeout/index.js +3 -28
- package/dist/core/extensions/builtin/bash-timeout/timeout.d.ts +0 -11
- package/dist/core/extensions/builtin/bash-timeout/timeout.js +0 -11
- package/dist/core/extensions/builtin/imagegen/index.d.ts +0 -1
- package/dist/core/extensions/builtin/imagegen/index.js +0 -11
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts +5 -5
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js +5 -5
- package/dist/core/extensions/builtin/prompt-preset/glm-5.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/glm-5.js +1 -1
- package/dist/core/extensions/builtin/terminal/extension.js +8 -1
- package/dist/core/extensions/builtin/terminal/notify.js +9 -3
- package/dist/core/extensions/builtin/terminal/prompt.d.ts +7 -1
- package/dist/core/extensions/builtin/terminal/prompt.js +27 -60
- package/dist/core/extensions/builtin/terminal/tools/bash.js +10 -2
- package/dist/core/extensions/builtin/todotools/normalize.d.ts +20 -3
- package/dist/core/extensions/builtin/todotools/normalize.js +251 -5
- package/dist/core/extensions/builtin/todotools/prompt.d.ts +2 -2
- package/dist/core/extensions/builtin/todotools/prompt.js +5 -5
- package/dist/core/extensions/builtin/todotools/tools/todo.js +9 -8
- package/dist/core/extensions/builtin/webfetch/webfetch/tool.js +0 -5
- package/dist/core/extensions/builtin/websearch/index.js +9 -4
- package/dist/core/extensions/builtin/websearch/websearch/tool.d.ts +2 -0
- package/dist/core/extensions/builtin/websearch/websearch/tool.js +3 -1
- package/dist/core/model-runtime.js +1 -1
- package/dist/core/provider-failure.d.ts +6 -0
- package/dist/core/provider-failure.js +6 -2
- package/dist/core/retry-fallback/exhaustion.d.ts +18 -0
- package/dist/core/retry-fallback/exhaustion.js +20 -0
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/tools/bash.d.ts +3 -1
- package/dist/core/tools/bash.js +14 -4
- package/dist/core/tools/edit.d.ts +1 -1
- package/dist/core/tools/edit.js +1 -6
- package/dist/core/tools/grep/index.js +2 -3
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +1 -1
- package/dist/core/tools/read.d.ts +1 -1
- package/dist/core/tools/read.js +1 -1
- package/dist/core/tools/write.d.ts +1 -1
- package/dist/core/tools/write.js +1 -1
- package/dist/engine-trust/shell-trust.d.ts +36 -0
- package/dist/engine-trust/shell-trust.js +44 -0
- package/dist/engine-trust/transport-failure.d.ts +12 -0
- package/dist/engine-trust/transport-failure.js +48 -0
- package/dist/modes/interactive/interactive-mode.js +9 -3
- package/dist/modes/print-mode.js +2 -1
- package/dist/modes/rpc/compact-catalog-families.d.ts +5 -2
- package/dist/modes/rpc/compact-catalog-families.js +5 -2
- package/dist/modes/rpc/compact-catalog-registry.d.ts +9 -1
- package/dist/modes/rpc/compact-catalog-registry.js +9 -2
- package/dist/modes/rpc/compact-recovery-manifest-kinds.d.ts +17 -0
- package/dist/modes/rpc/compact-recovery-manifest-kinds.js +21 -0
- package/dist/modes/rpc/compact-recovery-manifest-shape.d.ts +7 -0
- package/dist/modes/rpc/compact-recovery-manifest.js +11 -3
- package/dist/modes/rpc/compact-socket-commands.js +6 -0
- package/dist/modes/rpc/connection-handler.js +21 -5
- package/dist/modes/rpc/connection-question-bridge.d.ts +3 -1
- package/dist/modes/rpc/connection-question-bridge.js +4 -1
- package/dist/modes/rpc/connection-roles.d.ts +8 -0
- package/dist/modes/rpc/connection-roles.js +18 -0
- package/dist/modes/rpc/method-classes-schema-session.d.ts +4 -0
- package/dist/modes/rpc/method-classes-schema-session.js +1 -0
- package/dist/modes/rpc/method-classes-schema.d.ts +4 -0
- package/dist/modes/rpc/protocol-identity.js +2 -0
- package/dist/modes/rpc/remote-origin.d.ts +31 -0
- package/dist/modes/rpc/remote-origin.js +58 -0
- package/dist/modes/rpc/rpc-protocol-info-types.d.ts +8 -0
- package/dist/modes/rpc/rpc-question-types.d.ts +7 -0
- package/dist/modes/rpc/rpc-question-types.js +0 -3
- package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
- package/dist/modes/rpc/session-registry.js +12 -3
- package/dist/modes/rpc/session-worker-client.js +2 -0
- package/dist/modes/rpc/session-worker-protocol.d.ts +3 -0
- package/dist/modes/rpc/session-worker.js +2 -0
- package/docs/engine-socket/fixtures/admission-routes/c-baseline.json +3 -3
- package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
- package/docs/engine-socket/fixtures/admission-routes/i-reset-stream.json +3 -3
- package/docs/engine-socket/fixtures/recovery-manifest/index.json +32 -0
- package/docs/engine-socket/fixtures/recovery-manifest/one-partial-family.json +118 -0
- package/docs/rpc.md +93 -3
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-7UC4W2T2.js +0 -2
- package/dist/bundle/chunks/chunk-R23WXN4L.js +0 -448
- package/dist/bundle/chunks/chunk-W5NLCRB3.js +0 -2
|
@@ -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{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,applicableStoredState,credentialPoolStatePath,slotHealth}from"./chunk-SAZ6E74O.js";import"./chunk-F7GBSQRV.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-YWD54RHU.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-
|
|
2
|
+
import{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,applicableStoredState,credentialPoolStatePath,slotHealth}from"./chunk-SAZ6E74O.js";import"./chunk-F7GBSQRV.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-YWD54RHU.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-PX7FF5LE.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-V36CXIIB.js";import"./chunk-GVSBCJFI.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-MOH5HOHX.js";import"./chunk-HK46JMSC.js";import"./chunk-ED7VJGL4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-TBARMJ75.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-ISZ4EWIS.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{CREDENTIAL_POOL_STATE_FILENAME,CredentialSlotRepository,acquireHalfOpenLease,applicableStoredState,credentialPoolStatePath,slotHealth};
|
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-TVMW2SUP.js";import"./chunks/chunk-L3V65XW7.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-PP52OWBB.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-IWM5QRAE.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import{preparePrivateFdSpawn,spawnWithPrivateFds}from"./chunks/chunk-6WISUXVI.js";import"./chunks/chunk-XVRRNJQD.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-UKSFF47T.js";import"./chunks/chunk-OM7LH7AP.js";import"./chunks/chunk-QEESHRTS.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-ISZ4EWIS.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";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 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-U2PSNNWO.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-534A3WSC.js")}
|
|
3
|
+
import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunks/chunk-FJ2UCBOA.js";import"./chunks/chunk-CJWSQ6CK.js";import{getLatestPiRelease,isNewerPackageVersion,processBunRuntimeOptions,resolveBunReexec}from"./chunks/chunk-PP52OWBB.js";import{captureStdout,exitAfterOutput,hasInheritedInspectorOption,printThenExit,releaseInheritedInspectorForChild}from"./chunks/chunk-7KLEFHSU.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import{preparePrivateFdSpawn,spawnWithPrivateFds}from"./chunks/chunk-6WISUXVI.js";import"./chunks/chunk-XVRRNJQD.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-UKSFF47T.js";import"./chunks/chunk-OM7LH7AP.js";import"./chunks/chunk-QEESHRTS.js";import{APP_NAME,DISPLAY_VERSION,PACKAGE_NAME,RUNTIME_SNAPSHOT_MARKER,VERSION,brandProfile,findNodePackageDir,getAgentDir,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isBundledNode,readRuntimeSnapshotMarker}from"./chunks/chunk-ISZ4EWIS.js";import"./chunks/chunk-ATQFN5HI.js";import"./chunks/chunk-IKOFCODM.js";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 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-3EDGRKQM.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-XM5FWY3Z.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,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionRunner,FooterComponent,InteractiveMode,JOB_WIDGET_STATE_EVENT,KILL_GUARD_MODULE_URL,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ReservedCustodyKey,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TextTap,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageSelectorComponent,buildNoticeBox,classifyRead,collectOrphanedChildren,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,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,formatDimensionNote,formatSkillsForPrompt,generateDiffString,generateUnifiedPatch,kernelToolsStorage,killGuardProtectedPids,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSkillBlock,readKillGuardSetting,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,stripFrontmatter,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-ZSVWKOAJ.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-LMIETUPG.js";import"./chunks/chunk-TXOR5BQL.js";import"./chunks/chunk-FO56LSUK.js";import"./chunks/chunk-PIAY636U.js";import{DEFAULT_COMPACTION_SETTINGS,SESSION_CONTROL_DELIVERY_TYPE,calculateContextTokens,collectEntriesForBranchSummary,compact,defineTool,estimateTokens,findCutPoint,findTurnStartIndex,generateBranchSummary,generateSummary,generateSummaryWithUsage,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isWriteToolResult,prepareBranchEntries,serializeConversation,sessionControlSenderOf,shouldCompact,withFileMutationQueue}from"./chunks/chunk-R23WXN4L.js";import"./chunks/chunk-VRKA3LIT.js";import"./chunks/chunk-ETCYVVVO.js";import"./chunks/chunk-7ICGN62G.js";import"./chunks/chunk-3ESZE3DG.js";import"./chunks/chunk-R65P6LAT.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-GIY7PGOH.js";import"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-XLLQJALL.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-662SCMTH.js";import"./chunks/chunk-L5OFGHDA.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-UURGXV5B.js";import{AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,UserMessageComponent,copyToClipboard}from"./chunks/chunk-QLTQ3UUI.js";import"./chunks/chunk-J2OBN7TI.js";import"./chunks/chunk-Y4MPEIY5.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SecretInputUnavailableError,keyHint,keyText,rawKeyHint}from"./chunks/chunk-7FUO655J.js";import"./chunks/chunk-LGO25HPL.js";import{Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme}from"./chunks/chunk-BW4YXS7X.js";import"./chunks/chunk-57MRFI6E.js";import"./chunks/chunk-Y3TMJV3J.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-P4AT7SBE.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-NYXXKS6D.js";import{listHostEndpoints}from"./chunks/chunk-XGBRBCIQ.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-WEGTCUO3.js";import"./chunks/chunk-GDPWQJDQ.js";import"./chunks/chunk-7DWTKE4Z.js";import"./chunks/chunk-S2M5D5GS.js";import"./chunks/chunk-6LDUM5CL.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-FNBEICAA.js";import"./chunks/chunk-E6UCZ7E5.js";import"./chunks/chunk-UYO5Z35O.js";import"./chunks/chunk-H52J72VA.js";import"./chunks/chunk-SGS76663.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-O4GRBX4R.js";import"./chunks/chunk-KVPRQ5KN.js";import"./chunks/chunk-W5NLCRB3.js";import"./chunks/chunk-ZNPH5BWS.js";import"./chunks/chunk-6VWIMHMH.js";import"./chunks/chunk-7ORS33CE.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-SAZ6E74O.js";import"./chunks/chunk-F7GBSQRV.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-YWD54RHU.js";import"./chunks/chunk-SOMFLLPD.js";import{parseArgs}from"./chunks/chunk-27XEDYQA.js";import"./chunks/chunk-26UBFF6N.js";import{readOwnFootprint,readProcessFootprint}from"./chunks/chunk-MTQQ2VQH.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-LPHUMR6R.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-OEFCY46F.js";import"./chunks/chunk-KRNXUTZJ.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-QAM6AXA2.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-D2ROBVZ4.js";import{activateKillGuardRuntime,activeKillGuardEnvironment,getPowerShellConfig,getShellConfig,releaseKillGuardRuntime,withBundledBunCommands}from"./chunks/chunk-T5ZJ2Q4O.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-N4TSAHRL.js";import"./chunks/chunk-LNAZ7XEU.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-IHOQR7TU.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-V36CXIIB.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-TG4E7Z7W.js";import"./chunks/chunk-32R442XT.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-7UC4W2T2.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-ED7VJGL4.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-TBARMJ75.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-5CSZPC55.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-PP52OWBB.js";import"./chunks/chunk-IWM5QRAE.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-6WISUXVI.js";import"./chunks/chunk-XVRRNJQD.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-UKSFF47T.js";import"./chunks/chunk-OM7LH7AP.js";import"./chunks/chunk-QEESHRTS.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-ISZ4EWIS.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,REQUIRED_COMPACTION_ERROR_MESSAGE,REQUIRED_HOST_CAPABILITIES,RequiredCompactionError,ReservedCustodyKey,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SecretInputUnavailableError,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,TextTap,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,activateKillGuardRuntime,activeKillGuardEnvironment,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,decideKillGuardRequest,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findReservedKeywordRuns,findReservedKeywordSpans,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getJobWidgetState,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,killGuardProtectedPids,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readKillGuardSetting,readOwnFootprint,readProcessFootprint,readStoredCredential,registerJobWidgetSource,registerReadClassifier,releaseKillGuardRuntime,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionControlSenderOf,sessionEntryToContextMessages,setJobWidgetAuthorResolver,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
|
2
|
+
import{AgentSession,AgentSessionRuntime,ArminComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomMessageComponent,DefaultResourceLoader,EVAL_HANDLE_ERROR_CODES,EvalHandleError,ExtensionRunner,FooterComponent,InteractiveMode,JOB_WIDGET_STATE_EVENT,KILL_GUARD_MODULE_URL,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ReservedCustodyKey,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TextTap,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageSelectorComponent,buildNoticeBox,classifyRead,collectOrphanedChildren,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,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,formatDimensionNote,formatSkillsForPrompt,generateDiffString,generateUnifiedPatch,kernelToolsStorage,killGuardProtectedPids,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,noticeEntryRenderer,noticeMessageRenderer,parseFrontmatter,parseSkillBlock,readKillGuardSetting,readStoredCredential,registerReadClassifier,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,stripFrontmatter,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-ZNLCKKF6.js";import{RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UnknownCommandError,isTransportGoneError}from"./chunks/chunk-4BF4FLT6.js";import"./chunks/chunk-6BSMXZKQ.js";import"./chunks/chunk-BNIZP4OS.js";import"./chunks/chunk-PIAY636U.js";import{DEFAULT_COMPACTION_SETTINGS,SESSION_CONTROL_DELIVERY_TYPE,calculateContextTokens,collectEntriesForBranchSummary,compact,defineTool,estimateTokens,findCutPoint,findTurnStartIndex,generateBranchSummary,generateSummary,generateSummaryWithUsage,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isWriteToolResult,prepareBranchEntries,serializeConversation,sessionControlSenderOf,shouldCompact,withFileMutationQueue}from"./chunks/chunk-5DZD623T.js";import"./chunks/chunk-VRKA3LIT.js";import"./chunks/chunk-ETCYVVVO.js";import"./chunks/chunk-7ICGN62G.js";import"./chunks/chunk-3ESZE3DG.js";import"./chunks/chunk-R65P6LAT.js";import{DefaultPackageManager,SessionSelectorComponent,SettingsManager}from"./chunks/chunk-DPBPO5OU.js";import"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-XLLQJALL.js";import{CURRENT_SESSION_VERSION,SessionManager,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,sessionEntryToContextMessages}from"./chunks/chunk-VPDQ6MOL.js";import"./chunks/chunk-L5OFGHDA.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-UURGXV5B.js";import{AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,UserMessageComponent,copyToClipboard}from"./chunks/chunk-DAPBNRN5.js";import"./chunks/chunk-J2OBN7TI.js";import"./chunks/chunk-Y4MPEIY5.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SecretInputUnavailableError,keyHint,keyText,rawKeyHint}from"./chunks/chunk-MOOFLKLI.js";import"./chunks/chunk-LGO25HPL.js";import{Theme,findReservedKeywordRuns,findReservedKeywordSpans,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme}from"./chunks/chunk-WCRNJYHO.js";import"./chunks/chunk-57MRFI6E.js";import"./chunks/chunk-Y3TMJV3J.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-HBCNDC53.js";import{GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseHostProtocolInfo,probeHost,stopHost}from"./chunks/chunk-F4OHTL2K.js";import{listHostEndpoints}from"./chunks/chunk-XGBRBCIQ.js";import{createSyntheticSourceInfo}from"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-WEGTCUO3.js";import"./chunks/chunk-GDPWQJDQ.js";import"./chunks/chunk-7DWTKE4Z.js";import"./chunks/chunk-S2M5D5GS.js";import"./chunks/chunk-6LDUM5CL.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunks/chunk-FNBEICAA.js";import"./chunks/chunk-E6UCZ7E5.js";import"./chunks/chunk-UYO5Z35O.js";import"./chunks/chunk-H52J72VA.js";import"./chunks/chunk-SGS76663.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-3WJ2DE2G.js";import"./chunks/chunk-FLM6GZPT.js";import"./chunks/chunk-ESQBKTNG.js";import"./chunks/chunk-ZNPH5BWS.js";import"./chunks/chunk-6VWIMHMH.js";import"./chunks/chunk-7ORS33CE.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-SAZ6E74O.js";import"./chunks/chunk-F7GBSQRV.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-YWD54RHU.js";import"./chunks/chunk-SOMFLLPD.js";import{parseArgs}from"./chunks/chunk-27XEDYQA.js";import"./chunks/chunk-26UBFF6N.js";import{readOwnFootprint,readProcessFootprint}from"./chunks/chunk-MTQQ2VQH.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-LPHUMR6R.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-OEFCY46F.js";import"./chunks/chunk-KRNXUTZJ.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-QTQ3ES2S.js";import{sanitizeTerminalLabel,visibleWidth}from"./chunks/chunk-D2ROBVZ4.js";import{activateKillGuardRuntime,activeKillGuardEnvironment,getPowerShellConfig,getShellConfig,releaseKillGuardRuntime,withBundledBunCommands}from"./chunks/chunk-4SENPCEA.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-EVTTLPIY.js";import"./chunks/chunk-LNAZ7XEU.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-PX7FF5LE.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-V36CXIIB.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-TG4E7Z7W.js";import"./chunks/chunk-32R442XT.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-MOH5HOHX.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-ED7VJGL4.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-TBARMJ75.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-5CSZPC55.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-PP52OWBB.js";import"./chunks/chunk-7KLEFHSU.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-6WISUXVI.js";import"./chunks/chunk-XVRRNJQD.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-UKSFF47T.js";import"./chunks/chunk-OM7LH7AP.js";import"./chunks/chunk-QEESHRTS.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-ISZ4EWIS.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,REQUIRED_COMPACTION_ERROR_MESSAGE,REQUIRED_HOST_CAPABILITIES,RequiredCompactionError,ReservedCustodyKey,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,SESSION_CONTROL_DELIVERY_TYPE,SecretInputUnavailableError,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,TUI_PROBE_TIMEOUT_MS,TextTap,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UnknownCommandError,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,activateKillGuardRuntime,activeKillGuardEnvironment,buildContextEntries,buildNoticeBox,buildSessionContext,buildSessionProjection,calculateContextTokens,classifyEndpointLiveness,classifyRead,collectEntriesForBranchSummary,collectOrphanedChildren,compact,compareEngineOrdinal,connectWebViewService,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createHostDaemonPaths,createLocalBashOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,daemonDirectoryName,decideHostAction,decideKillGuardRequest,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,endpointProbeTimeoutMs,engineBuildIdentity,engineBuildIdentityFrom,ensureHost,estimateTokens,findCutPoint,findReservedKeywordRuns,findReservedKeywordSpans,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,gcHostEndpoints,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getJobWidgetState,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,handoffHost,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isSessionControlDeliveryDetails,isToolCallEventType,isTransportGoneError,isWriteToolResult,kernelToolsStorage,keyHint,keyText,killGuardProtectedPids,listHostEndpoints,loadHostLaunchSpec,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,noticeEntryRenderer,noticeMessageRenderer,parseArgs,parseFrontmatter,parseHostLaunchSpec,parseHostProtocolInfo,parseSessionEntries,parseSkillBlock,prepareBranchEntries,probeHost,rawKeyHint,readAllHostStatus,readHostStatus,readKillGuardSetting,readOwnFootprint,readProcessFootprint,readStoredCredential,registerJobWidgetSource,registerReadClassifier,releaseKillGuardRuntime,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runHostCommand,runHostRequest,runPrintMode,runRpcMode,sanitizeTerminalLabel,serializeConversation,sessionControlSenderOf,sessionEntryToContextMessages,setJobWidgetAuthorResolver,shardKey,shardSocketPath,shardSocketPathForKey,shouldCompact,stopHost,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,visibleWidth,withBundledBunCommands,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
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-CJWSQ6CK.js";import{main}from"./chunks/chunk-ZNLCKKF6.js";import"./chunks/chunk-4BF4FLT6.js";import"./chunks/chunk-6BSMXZKQ.js";import"./chunks/chunk-BNIZP4OS.js";import"./chunks/chunk-PIAY636U.js";import"./chunks/chunk-5DZD623T.js";import"./chunks/chunk-VRKA3LIT.js";import"./chunks/chunk-ETCYVVVO.js";import"./chunks/chunk-7ICGN62G.js";import"./chunks/chunk-3ESZE3DG.js";import"./chunks/chunk-R65P6LAT.js";import"./chunks/chunk-DPBPO5OU.js";import{configureHttpDispatcher}from"./chunks/chunk-FEQDJBDL.js";import"./chunks/chunk-XLLQJALL.js";import"./chunks/chunk-VPDQ6MOL.js";import"./chunks/chunk-L5OFGHDA.js";import"./chunks/chunk-UURGXV5B.js";import"./chunks/chunk-DAPBNRN5.js";import"./chunks/chunk-J2OBN7TI.js";import"./chunks/chunk-Y4MPEIY5.js";import"./chunks/chunk-MOOFLKLI.js";import"./chunks/chunk-LGO25HPL.js";import"./chunks/chunk-WCRNJYHO.js";import"./chunks/chunk-57MRFI6E.js";import"./chunks/chunk-Y3TMJV3J.js";import"./chunks/chunk-HBCNDC53.js";import"./chunks/chunk-F4OHTL2K.js";import"./chunks/chunk-XGBRBCIQ.js";import"./chunks/chunk-QMRJYMNH.js";import"./chunks/chunk-WEGTCUO3.js";import"./chunks/chunk-GDPWQJDQ.js";import"./chunks/chunk-7DWTKE4Z.js";import"./chunks/chunk-S2M5D5GS.js";import"./chunks/chunk-6LDUM5CL.js";import"./chunks/chunk-FNBEICAA.js";import"./chunks/chunk-E6UCZ7E5.js";import"./chunks/chunk-UYO5Z35O.js";import"./chunks/chunk-H52J72VA.js";import"./chunks/chunk-SGS76663.js";import"./chunks/chunk-H4QOEVS5.js";import"./chunks/chunk-3WJ2DE2G.js";import"./chunks/chunk-FLM6GZPT.js";import"./chunks/chunk-ESQBKTNG.js";import"./chunks/chunk-ZNPH5BWS.js";import"./chunks/chunk-6VWIMHMH.js";import"./chunks/chunk-7ORS33CE.js";import"./chunks/chunk-KLAX467B.js";import"./chunks/chunk-SAZ6E74O.js";import"./chunks/chunk-F7GBSQRV.js";import"./chunks/chunk-GZVCRV7I.js";import"./chunks/chunk-KUPQO7MC.js";import"./chunks/chunk-U3VOXCGP.js";import"./chunks/chunk-7X72IACK.js";import"./chunks/chunk-YWD54RHU.js";import"./chunks/chunk-SOMFLLPD.js";import"./chunks/chunk-27XEDYQA.js";import"./chunks/chunk-26UBFF6N.js";import"./chunks/chunk-MTQQ2VQH.js";import"./chunks/chunk-HB35RBP4.js";import"./chunks/chunk-YU2P3CAR.js";import"./chunks/chunk-LPHUMR6R.js";import"./chunks/chunk-IYL5E4QQ.js";import"./chunks/chunk-OEFCY46F.js";import"./chunks/chunk-KRNXUTZJ.js";import"./chunks/chunk-AC72EWI5.js";import"./chunks/chunk-RQFD6LG2.js";import"./chunks/chunk-QTQ3ES2S.js";import"./chunks/chunk-D2ROBVZ4.js";import"./chunks/chunk-4SENPCEA.js";import"./chunks/chunk-YU4AYH4C.js";import"./chunks/chunk-EVTTLPIY.js";import"./chunks/chunk-LNAZ7XEU.js";import"./chunks/chunk-DLAY7CIU.js";import"./chunks/chunk-PX7FF5LE.js";import"./chunks/chunk-COH5F7QV.js";import"./chunks/chunk-RFB5CBW7.js";import"./chunks/chunk-Y7QPP7BG.js";import"./chunks/chunk-V36CXIIB.js";import"./chunks/chunk-GVSBCJFI.js";import"./chunks/chunk-QTS2XGPQ.js";import"./chunks/chunk-TG4E7Z7W.js";import"./chunks/chunk-32R442XT.js";import"./chunks/chunk-WHPDEDCC.js";import"./chunks/chunk-MOH5HOHX.js";import"./chunks/chunk-HK46JMSC.js";import"./chunks/chunk-ED7VJGL4.js";import"./chunks/chunk-WDTJ6JKE.js";import"./chunks/chunk-5ROMKDLK.js";import"./chunks/chunk-3W47LTXQ.js";import"./chunks/chunk-TBARMJ75.js";import"./chunks/chunk-3SASTB6Y.js";import"./chunks/chunk-5CSZPC55.js";import"./chunks/chunk-PJ34QVL5.js";import"./chunks/chunk-BMX2U22F.js";import"./chunks/chunk-6APXZK7W.js";import"./chunks/chunk-WOHQJ6JB.js";import"./chunks/chunk-PP52OWBB.js";import"./chunks/chunk-7KLEFHSU.js";import"./chunks/chunk-ZOFZRJSL.js";import"./chunks/chunk-ZFIC2DZV.js";import"./chunks/chunk-6WISUXVI.js";import"./chunks/chunk-XVRRNJQD.js";import"./chunks/chunk-42XRJQM6.js";import"./chunks/chunk-2SOVDETB.js";import"./chunks/chunk-UKSFF47T.js";import"./chunks/chunk-OM7LH7AP.js";import"./chunks/chunk-QEESHRTS.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunks/chunk-ISZ4EWIS.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";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":"5fe886523575efa9","externals":["@earendil-works/chord","@earendil-works/pi-pty","@silvia-odwyer/photon-node","bufferutil","canvas","kerberos","supports-color","utf-8-validate"]}
|
|
@@ -48,6 +48,7 @@ import { type PromptTemplate } from "./prompt-templates.ts";
|
|
|
48
48
|
import { type ProviderFailure } from "./provider-failure.ts";
|
|
49
49
|
import type { ResourceLoader } from "./resource-loader.ts";
|
|
50
50
|
import { type ModelConfigErrorEvent } from "./retry-fallback/model-config-error.ts";
|
|
51
|
+
import { type FallbackRungFailure } from "./retry-fallback/exhaustion.ts";
|
|
51
52
|
import { type InheritResult, type ReleaseInheritedResult, type RunRef } from "./run-holds.ts";
|
|
52
53
|
import { SecurityNoticeSnapshot } from "./security-notices.ts";
|
|
53
54
|
import { type SessionActivitySnapshot } from "./session-activity.ts";
|
|
@@ -338,7 +339,12 @@ export type AgentSessionEvent = WithParentToolCallId<Exclude<AgentEvent, {
|
|
|
338
339
|
} | {
|
|
339
340
|
type: "retry_fallback_exhausted";
|
|
340
341
|
chainKey: string;
|
|
342
|
+
/** The failure of the rung that ran last; kept for older clients. */
|
|
341
343
|
lastError: string;
|
|
344
|
+
/** The failure that started the fallback walk: the turn's first failed rung (senpi#4084). */
|
|
345
|
+
primaryError?: FallbackRungFailure;
|
|
346
|
+
/** Every rung that failed this turn, in the order it ran, the primary first. */
|
|
347
|
+
failures?: FallbackRungFailure[];
|
|
342
348
|
} | ModelConfigErrorEvent | {
|
|
343
349
|
type: "server_fallback_aborted";
|
|
344
350
|
from: string;
|
|
@@ -969,6 +975,7 @@ export declare class AgentSession {
|
|
|
969
975
|
private readonly _fallbackValidationWarnings;
|
|
970
976
|
private _providerRequiredNoticed;
|
|
971
977
|
private readonly _retryFallback;
|
|
978
|
+
private _fallbackTurnFailures;
|
|
972
979
|
private readonly _modelConfigErrors;
|
|
973
980
|
private readonly _selectorCooldowns;
|
|
974
981
|
private readonly _fallbackCircuits;
|
|
@@ -1131,6 +1138,7 @@ export declare class AgentSession {
|
|
|
1131
1138
|
private _emitEntryAppended;
|
|
1132
1139
|
/** Append a transport-provided entry and publish it on the RPC event stream. */
|
|
1133
1140
|
appendSessionEntry(entry: SessionEntry): void;
|
|
1141
|
+
private _emitFallbackExhausted;
|
|
1134
1142
|
private _emit;
|
|
1135
1143
|
private _emitSessionCompactFailed;
|
|
1136
1144
|
/** Mirror stuck-prone lifecycle transitions into logs/session.log (content-free). */
|
|
@@ -128,6 +128,7 @@ import { createModelConfigErrorReporter, isModelConfigFailure, } from "./retry-f
|
|
|
128
128
|
import { ProbeBackScheduler } from "./retry-fallback/probe-scheduler.js";
|
|
129
129
|
import { REQUEST_SHAPE_FAILURE_TEXT, REQUEST_SHAPE_RECOVERY_ENTRY_TYPE, REQUEST_SHAPE_RECOVERY_NOTE, RequestShapeRecovery, } from "./retry-fallback/request-shape.js";
|
|
130
130
|
import { AccountUsageLimitError, describeUsageLimitEntry, describeUsageLimitMessage, usageLimitScope, } from "./retry-fallback/usage-limit.js";
|
|
131
|
+
import { recordRungFailure } from "./retry-fallback/exhaustion.js";
|
|
131
132
|
import { validateFallbackChains } from "./retry-fallback/validate.js";
|
|
132
133
|
import { RunHolds } from "./run-holds.js";
|
|
133
134
|
import { startRunResumeTurn } from "./run-resume-turn.js";
|
|
@@ -610,6 +611,8 @@ export class AgentSession {
|
|
|
610
611
|
this._userActivity = createUserActivitySource();
|
|
611
612
|
this._extensionMode = "print";
|
|
612
613
|
this._providerRequiredNoticed = false;
|
|
614
|
+
// Every rung that failed this turn, in order: the exhaustion event leads with the first (senpi#4084).
|
|
615
|
+
this._fallbackTurnFailures = [];
|
|
613
616
|
this._probeBackLaneSeq = 0;
|
|
614
617
|
// Tool registry for extension getTools/setTools
|
|
615
618
|
this._toolRegistry = new Map();
|
|
@@ -1749,6 +1752,16 @@ export class AgentSession {
|
|
|
1749
1752
|
this.agent.state.messages = this.sessionManager.buildSessionContext().messages;
|
|
1750
1753
|
this._emitEntryAppended(entry.id);
|
|
1751
1754
|
}
|
|
1755
|
+
_emitFallbackExhausted(chainKey, lastError) {
|
|
1756
|
+
const failures = [...this._fallbackTurnFailures];
|
|
1757
|
+
const primaryError = failures[0];
|
|
1758
|
+
this._emit({
|
|
1759
|
+
type: "retry_fallback_exhausted",
|
|
1760
|
+
chainKey,
|
|
1761
|
+
lastError,
|
|
1762
|
+
...(primaryError === undefined ? {} : { primaryError, failures }),
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1752
1765
|
_emit(event, captureSource = event) {
|
|
1753
1766
|
this._recoveryIdentity?.observe(event);
|
|
1754
1767
|
const produced = event;
|
|
@@ -1761,11 +1774,8 @@ export class AgentSession {
|
|
|
1761
1774
|
if (event.type === "entry_appended") {
|
|
1762
1775
|
event = { ...event, entry: describeUsageLimitEntry(event.entry) };
|
|
1763
1776
|
}
|
|
1764
|
-
if (event.type === "retry_fallback_exhausted"
|
|
1765
|
-
event =
|
|
1766
|
-
...event,
|
|
1767
|
-
lastError: new AccountUsageLimitError(this.model?.provider ?? "", event.lastError).message,
|
|
1768
|
-
};
|
|
1777
|
+
if (event.type === "retry_fallback_exhausted") {
|
|
1778
|
+
event = describeExhaustedFailures(event, this.model?.provider ?? "");
|
|
1769
1779
|
}
|
|
1770
1780
|
if (event.type === "agent_end") {
|
|
1771
1781
|
event = {
|
|
@@ -2556,6 +2566,7 @@ export class AgentSession {
|
|
|
2556
2566
|
if (event.type === "message_start" && event.message.role === "user") {
|
|
2557
2567
|
this._overflowRecoveryRungs = 0;
|
|
2558
2568
|
this._retryFallback.resetTurn();
|
|
2569
|
+
this._fallbackTurnFailures = [];
|
|
2559
2570
|
const messageText = userMessageText(event.message.content);
|
|
2560
2571
|
// Image-only input has no text to match: find it by the message the queue handed to the agent (#3592).
|
|
2561
2572
|
const imageOnlyQueued = messageText
|
|
@@ -4107,7 +4118,10 @@ export class AgentSession {
|
|
|
4107
4118
|
const promptGuidelines = [];
|
|
4108
4119
|
for (const name of contributingToolNames) {
|
|
4109
4120
|
const snippet = this._toolPromptSnippets.get(name);
|
|
4110
|
-
|
|
4121
|
+
// A model-facing tool whose schema description the model already reads gets no snippet line;
|
|
4122
|
+
// withheld eval-only tools keep theirs (senpi#5335).
|
|
4123
|
+
const describedToModel = validToolNames.includes(name) && (this._toolRegistry.get(name)?.description.trim() ?? "") !== "";
|
|
4124
|
+
if (snippet && !describedToModel) {
|
|
4111
4125
|
toolSnippets[name] = snippet;
|
|
4112
4126
|
}
|
|
4113
4127
|
const toolGuidelines = this._toolPromptGuidelines.get(name);
|
|
@@ -4130,38 +4144,40 @@ export class AgentSession {
|
|
|
4130
4144
|
customPrompt: loaderSystemPrompt,
|
|
4131
4145
|
appendSystemPrompt: loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined,
|
|
4132
4146
|
};
|
|
4147
|
+
const evalOnlyArmed = this._isEvalOnlyPolicyArmed();
|
|
4148
|
+
const armed = evalOnlyArmed ? (this._evalOnlyToolNames ?? new Set()) : new Set();
|
|
4149
|
+
const registered = new Set([...armed].filter((name) => this._toolRegistry.has(name)));
|
|
4150
|
+
// The eval-only paragraph below states the grep rule for this render, so the grep snippet that
|
|
4151
|
+
// renders the eval-only grep guideline stays out of it (senpi#5335).
|
|
4152
|
+
const { grep: _grepSnippet, ...snippetsWithoutGrep } = toolSnippets;
|
|
4133
4153
|
const prompt = buildDynamicSystemPrompt({
|
|
4134
4154
|
...this._baseSystemPromptOptions,
|
|
4155
|
+
...(registered.has("grep") ? { toolSnippets: snippetsWithoutGrep } : {}),
|
|
4135
4156
|
onParts: (parts) => {
|
|
4136
4157
|
this._baseSystemPromptParts = parts;
|
|
4137
4158
|
},
|
|
4138
4159
|
});
|
|
4139
|
-
if (!
|
|
4160
|
+
if (!evalOnlyArmed)
|
|
4140
4161
|
return prompt;
|
|
4141
|
-
const
|
|
4142
|
-
const registered = new Set([...armed].filter((name) => this._toolRegistry.has(name)));
|
|
4143
|
-
const sentences = [];
|
|
4162
|
+
const helpers = [];
|
|
4144
4163
|
const shellHelpers = ["bash", "powershell"].filter((name) => registered.has(name)).map(evalHelperCall);
|
|
4145
|
-
if (shellHelpers.length > 0)
|
|
4146
|
-
|
|
4147
|
-
|
|
4148
|
-
|
|
4149
|
-
sentences.push(`The workflow tool runs ONLY inside eval cells via ${evalHelperCall("workflow")}; hooks and permissions still apply.`);
|
|
4150
|
-
}
|
|
4164
|
+
if (shellHelpers.length > 0)
|
|
4165
|
+
helpers.push(`${shellHelpers.join(" / ")} shell`);
|
|
4166
|
+
if (registered.has("workflow"))
|
|
4167
|
+
helpers.push(evalHelperCall("workflow"));
|
|
4151
4168
|
// Declared tools and SDK overrides outside the built-in groups still need eval guidance.
|
|
4152
|
-
|
|
4169
|
+
helpers.push(...[...registered]
|
|
4153
4170
|
.filter((name) => name !== "bash" && name !== "powershell" && name !== "workflow" && name !== "grep" && name !== "glob")
|
|
4154
|
-
.map(evalHelperCall);
|
|
4155
|
-
if (otherHelpers.length > 0) {
|
|
4156
|
-
sentences.push(`These tools run ONLY inside eval cells via ${otherHelpers.join(" or ")}; hooks and permissions still apply.`);
|
|
4157
|
-
}
|
|
4171
|
+
.map(evalHelperCall));
|
|
4158
4172
|
if (registered.has("glob")) {
|
|
4159
|
-
|
|
4173
|
+
helpers.push(`${evalHelperCall("glob")} file-name search (glob like **/*.ts, respects .gitignore; over find/ls)`);
|
|
4160
4174
|
}
|
|
4161
4175
|
if (registered.has("grep")) {
|
|
4162
|
-
|
|
4176
|
+
helpers.push(`${evalHelperCall("grep")} text search (structured, respects .gitignore; over rg/grep; page full -> skip, narrow with glob/path)`);
|
|
4163
4177
|
}
|
|
4164
|
-
return
|
|
4178
|
+
return helpers.length > 0
|
|
4179
|
+
? `${prompt}\n\nEval-only tools (hooks + permissions still apply): ${helpers.join("; ")}.`
|
|
4180
|
+
: prompt;
|
|
4165
4181
|
}
|
|
4166
4182
|
/**
|
|
4167
4183
|
* Run `input` extension handlers for queued (steer / follow-up) input.
|
|
@@ -4481,6 +4497,7 @@ export class AgentSession {
|
|
|
4481
4497
|
const model = this.model;
|
|
4482
4498
|
if (model && !this._pendingModelSwitch && this._retryFallback.isProviderSpent(model.provider)) {
|
|
4483
4499
|
this._retryFallback.resetTurn();
|
|
4500
|
+
this._fallbackTurnFailures = [];
|
|
4484
4501
|
const errorMessage = this._retryFallback.accountError(model.provider);
|
|
4485
4502
|
// Routing around a remembered failure did not observe another provider failure.
|
|
4486
4503
|
if (!(await this._retryFallback.tryFallback("transient", { errorMessage }, false))) {
|
|
@@ -10427,11 +10444,7 @@ export class AgentSession {
|
|
|
10427
10444
|
const finishRetryAttempt = (attempt, finalError) => {
|
|
10428
10445
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10429
10446
|
if (exhaustedChainKey) {
|
|
10430
|
-
this.
|
|
10431
|
-
type: "retry_fallback_exhausted",
|
|
10432
|
-
chainKey: exhaustedChainKey,
|
|
10433
|
-
lastError: errorMessage,
|
|
10434
|
-
});
|
|
10447
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10435
10448
|
}
|
|
10436
10449
|
this._emit({
|
|
10437
10450
|
type: "auto_retry_end",
|
|
@@ -10494,6 +10507,11 @@ export class AgentSession {
|
|
|
10494
10507
|
let is429TierRouted = false;
|
|
10495
10508
|
let hintTierDelayMs;
|
|
10496
10509
|
const tryFallback = async (reason, failure) => {
|
|
10510
|
+
recordRungFailure(this._fallbackTurnFailures, {
|
|
10511
|
+
model: `${message.provider}/${message.model}`,
|
|
10512
|
+
reason,
|
|
10513
|
+
error: errorMessage,
|
|
10514
|
+
});
|
|
10497
10515
|
try {
|
|
10498
10516
|
return await this._retryFallback.tryFallback(reason, failure);
|
|
10499
10517
|
}
|
|
@@ -10513,7 +10531,7 @@ export class AgentSession {
|
|
|
10513
10531
|
if (!switchedFallback) {
|
|
10514
10532
|
const chainKey = this._retryFallback.exhaustedChainKey;
|
|
10515
10533
|
if (chainKey)
|
|
10516
|
-
this.
|
|
10534
|
+
this._emitFallbackExhausted(chainKey, errorMessage);
|
|
10517
10535
|
if (this._retryAttempt > 0) {
|
|
10518
10536
|
this._emit({
|
|
10519
10537
|
type: "auto_retry_end",
|
|
@@ -10570,11 +10588,7 @@ export class AgentSession {
|
|
|
10570
10588
|
if (!switchedFallback) {
|
|
10571
10589
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10572
10590
|
if (exhaustedChainKey) {
|
|
10573
|
-
this.
|
|
10574
|
-
type: "retry_fallback_exhausted",
|
|
10575
|
-
chainKey: exhaustedChainKey,
|
|
10576
|
-
lastError: errorMessage,
|
|
10577
|
-
});
|
|
10591
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10578
10592
|
}
|
|
10579
10593
|
this._resolveRetry();
|
|
10580
10594
|
return "not-handled";
|
|
@@ -10604,11 +10618,7 @@ export class AgentSession {
|
|
|
10604
10618
|
if (!switchedFallback) {
|
|
10605
10619
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10606
10620
|
if (exhaustedChainKey) {
|
|
10607
|
-
this.
|
|
10608
|
-
type: "retry_fallback_exhausted",
|
|
10609
|
-
chainKey: exhaustedChainKey,
|
|
10610
|
-
lastError: errorMessage,
|
|
10611
|
-
});
|
|
10621
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10612
10622
|
}
|
|
10613
10623
|
if (this._retryAttempt > 0) {
|
|
10614
10624
|
this._emit({
|
|
@@ -10669,11 +10679,7 @@ export class AgentSession {
|
|
|
10669
10679
|
else {
|
|
10670
10680
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10671
10681
|
if (exhaustedChainKey) {
|
|
10672
|
-
this.
|
|
10673
|
-
type: "retry_fallback_exhausted",
|
|
10674
|
-
chainKey: exhaustedChainKey,
|
|
10675
|
-
lastError: errorMessage,
|
|
10676
|
-
});
|
|
10682
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10677
10683
|
}
|
|
10678
10684
|
this._emit({
|
|
10679
10685
|
type: "auto_retry_end",
|
|
@@ -10721,11 +10727,7 @@ export class AgentSession {
|
|
|
10721
10727
|
else {
|
|
10722
10728
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10723
10729
|
if (exhaustedChainKey) {
|
|
10724
|
-
this.
|
|
10725
|
-
type: "retry_fallback_exhausted",
|
|
10726
|
-
chainKey: exhaustedChainKey,
|
|
10727
|
-
lastError: errorMessage,
|
|
10728
|
-
});
|
|
10730
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10729
10731
|
}
|
|
10730
10732
|
this._emit({
|
|
10731
10733
|
type: "auto_retry_end",
|
|
@@ -10762,11 +10764,7 @@ export class AgentSession {
|
|
|
10762
10764
|
else {
|
|
10763
10765
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10764
10766
|
if (exhaustedChainKey) {
|
|
10765
|
-
this.
|
|
10766
|
-
type: "retry_fallback_exhausted",
|
|
10767
|
-
chainKey: exhaustedChainKey,
|
|
10768
|
-
lastError: errorMessage,
|
|
10769
|
-
});
|
|
10767
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10770
10768
|
}
|
|
10771
10769
|
this._emit({
|
|
10772
10770
|
type: "auto_retry_end",
|
|
@@ -10822,11 +10820,7 @@ export class AgentSession {
|
|
|
10822
10820
|
else {
|
|
10823
10821
|
const exhaustedChainKey = this._retryFallback.exhaustedChainKey;
|
|
10824
10822
|
if (exhaustedChainKey) {
|
|
10825
|
-
this.
|
|
10826
|
-
type: "retry_fallback_exhausted",
|
|
10827
|
-
chainKey: exhaustedChainKey,
|
|
10828
|
-
lastError: errorMessage,
|
|
10829
|
-
});
|
|
10823
|
+
this._emitFallbackExhausted(exhaustedChainKey, errorMessage);
|
|
10830
10824
|
}
|
|
10831
10825
|
this._emit({
|
|
10832
10826
|
type: "auto_retry_end",
|
|
@@ -11802,4 +11796,18 @@ function messageFingerprint(message) {
|
|
|
11802
11796
|
const requestContext = usage?.contextUsage;
|
|
11803
11797
|
return `${size}:${usage?.input ?? ""}:${usage?.output ?? ""}:${usage?.totalTokens ?? ""}:${requestContext?.input}:${requestContext?.output}:${requestContext === null}`;
|
|
11804
11798
|
}
|
|
11799
|
+
// Clients see each rung's provider text through the same account-limit description as `lastError`.
|
|
11800
|
+
function describeExhaustedFailures(event, currentProvider) {
|
|
11801
|
+
const describe = (error, provider) => usageLimitScope(error) === "account" ? new AccountUsageLimitError(provider, error).message : error;
|
|
11802
|
+
const failures = event.failures?.map((failure) => ({
|
|
11803
|
+
...failure,
|
|
11804
|
+
error: describe(failure.error, failure.model.slice(0, Math.max(0, failure.model.indexOf("/")))),
|
|
11805
|
+
}));
|
|
11806
|
+
const primaryError = failures?.[0];
|
|
11807
|
+
return {
|
|
11808
|
+
...event,
|
|
11809
|
+
lastError: describe(event.lastError, currentProvider),
|
|
11810
|
+
...(failures === undefined || primaryError === undefined ? {} : { failures, primaryError }),
|
|
11811
|
+
};
|
|
11812
|
+
}
|
|
11805
11813
|
//# sourceMappingURL=agent-session.js.map
|
|
@@ -31,8 +31,9 @@ export type CredentialAction = {
|
|
|
31
31
|
};
|
|
32
32
|
/**
|
|
33
33
|
* Per-slot exponential cooldown with the server hint as a FLOOR, never an
|
|
34
|
-
* override: a hint can only lengthen the wait the failure count already earned
|
|
35
|
-
*
|
|
34
|
+
* override: a hint can only lengthen the wait the failure count already earned.
|
|
35
|
+
* The guessed backoff stops growing at GUESSED_BACKOFF_CAP_MS; everything caps at
|
|
36
|
+
* 48 hours with the capping recorded.
|
|
36
37
|
*/
|
|
37
38
|
export declare function rateLimitCooldown(failureCount: number, serverHintMs?: number, policy?: {
|
|
38
39
|
baseMs?: number;
|
|
@@ -11,6 +11,12 @@ import { usageLimitResetMs } from "./reset-time.js";
|
|
|
11
11
|
import { isAccountUsageLimitText } from "./usage-limit.js";
|
|
12
12
|
export const COOLDOWN_BASE_MS = DEFAULT_SLOT_BLOCK_MS;
|
|
13
13
|
export const COOLDOWN_CAP_MS = MAX_SLOT_BLOCK_MS;
|
|
14
|
+
/**
|
|
15
|
+
* The longest a guessed backoff may grow. A block with no provider-stated reset is only a guess, so
|
|
16
|
+
* the slot is re-probed at least this often: doubling to the 48 h cap across failed probes kept a
|
|
17
|
+
* spent account blocked for hours after its provider window had reset (senpi#4091).
|
|
18
|
+
*/
|
|
19
|
+
const GUESSED_BACKOFF_CAP_MS = 30 * 60 * 1_000;
|
|
14
20
|
export const RETRY_SAME_MAX_ATTEMPTS = 2;
|
|
15
21
|
/**
|
|
16
22
|
* Carried by every refusal a provider that runs its own account pool (Anthropic Subscription) makes
|
|
@@ -22,13 +28,14 @@ export const RETRY_SAME_MAX_ATTEMPTS = 2;
|
|
|
22
28
|
export const ACCOUNT_POOL_REFUSAL_NOTE = "No request was sent: the account pool refused it locally.";
|
|
23
29
|
/**
|
|
24
30
|
* Per-slot exponential cooldown with the server hint as a FLOOR, never an
|
|
25
|
-
* override: a hint can only lengthen the wait the failure count already earned
|
|
26
|
-
*
|
|
31
|
+
* override: a hint can only lengthen the wait the failure count already earned.
|
|
32
|
+
* The guessed backoff stops growing at GUESSED_BACKOFF_CAP_MS; everything caps at
|
|
33
|
+
* 48 hours with the capping recorded.
|
|
27
34
|
*/
|
|
28
35
|
export function rateLimitCooldown(failureCount, serverHintMs, policy = {}) {
|
|
29
36
|
const cap = policy.capMs ?? COOLDOWN_CAP_MS;
|
|
30
37
|
const base = policy.baseMs ?? COOLDOWN_BASE_MS;
|
|
31
|
-
const backoff = Math.min(cap, base * 2 ** Math.max(0, failureCount));
|
|
38
|
+
const backoff = Math.min(cap, GUESSED_BACKOFF_CAP_MS, base * 2 ** Math.max(0, failureCount));
|
|
32
39
|
const floored = serverHintMs === undefined ? backoff : Math.max(backoff, serverHintMs);
|
|
33
40
|
return {
|
|
34
41
|
cooldownMs: Math.min(cap, floored),
|