@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,5 +1,5 @@
|
|
|
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{CUSTOM_UNSUPPORTED_CAPABILITY,DEFAULT_PROBE_TIMEOUT_MS,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,RPC_CLIENT_CAPABILITIES_ENV,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,acquireHostEnsureLock,anyGenerationLive,busyLegacyHostDetail,computeRuntimeBuildId,decideHostAction,describeSessions,electPointer,engineBuildIdentity,gcEndpoint,gcHostEndpoints,holdProtocolInfo,holdSessionCount,hostEnsureLockOptions,hostEnsureLockTarget,hostLaunchProfile,judgeStaleEngine,observeProtocolInfo,parseHostStopGeneration,probeProtocolInfo,probeSocketReachable,provenLegacyOwner,retireIdleLegacyHost,signalGeneration,socketHostLaunchProfile,staleStopGeneration,stopHost}from"./chunk-NYXXKS6D.js";import{endpointKindOfSocket,listHostEndpoints}from"./chunk-XGBRBCIQ.js";import{requestOnSocket}from"./chunk-WEGTCUO3.js";import{rpcKeyRoot,withRpcKeyRoot}from"./chunk-GDPWQJDQ.js";import{presenterBootstrapStream,relayPresenterBootstrap}from"./chunk-7DWTKE4Z.js";import{INTERNAL_HOST_DIR_PREFIX,INTERNAL_SUPERVISOR_FLAG,OWNER_WATCH_FD,internalHostDirRoots,isHostCrash,keepOwnerPipe,loopLagErrorMs,noteEscalatedStop,readHostCrashRecords,resolveCliMainPath,runtimeExecArgv}from"./chunk-S2M5D5GS.js";import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STOP_TIMEOUT_MS,DEFAULT_HOST_IDLE_EXIT_MS,activeStopProgress,childStalledStopMaxMs,claimOwnerIsLive,clearHostRegistration,hostChildAlive,hostLoopStalled,provenOwner,pruneDeadGenerations,readGenerationRows,readHostProcessMetrics,readHostRegistration,readSessionPathClaims,readStopIntent,releaseGeneration,stallRefusalWindowMs,writeGenerationRecord,writeHostRegistration,writeStopIntent,writtenByThisProcess}from"./chunk-6LDUM5CL.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,callerHostOwner,claimHostOwner,createDaemonDirectories,createHostDaemonPaths,ensureEndpointIdentity,generationPaths,hostDaemonDirectoryPaths,parseJson,parseShardSocket,readFileOrUndefined,readHostOwner,readHostSettings,sameEndpoint,sameHostOwner,sessionDirectoryRemoved,shardKey,shardSocketPathForKey,writeHostOwner,writeHostSettings,writeStateFile}from"./chunk-FNBEICAA.js";import{OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-E6UCZ7E5.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV}from"./chunk-UYO5Z35O.js";import{envSlotVarNames}from"./chunk-7ORS33CE.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{isSessionRuntimeKind,isToolRuntimeKind,toolRuntimeCapability}from"./chunk-27XEDYQA.js";import{adoptedEngineTrust}from"./chunk-N4TSAHRL.js";import{providerCredentialEnvNames}from"./chunk-TG4E7Z7W.js";import{spawnWithPrivateFds}from"./chunk-6WISUXVI.js";import{MAX_SOCKET_PATH_BYTES,generationBindPath,socketEntryListenerState,statSocketIdentity}from"./chunk-OM7LH7AP.js";import{acquireOwnershipSafeLock,ensureSocketSecret,socketSecretPath}from"./chunk-QEESHRTS.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-ISZ4EWIS.js";import{ProcessIdentityUnreadableError,processIsLive,processMatchesPidFile,readProcessStartTime,waitForStartTime}from"./chunk-O5RYI3IW.js";import{writeSync as writeSync2}from"node:fs";import{join as join6,resolve as resolve5}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path2=>["--extension",path2])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^BSK_(HOME|BIN)$/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],PROVIDER_CREDENTIAL_ENV_NAMES=new Set([...providerCredentialEnvNames(),...envSlotVarNames()]),WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","OMO_BROWSER_ENGINE","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID","SENPI_RPC_HOST_WATCH_FD","SENPI_RPC_HOST_WATCH_PPID","SENPI_RPC_HOST_SCRATCH_DIR","SENPI_RPC_HOST_CLEANUP_PATHS","SENPI_RPC_HOST_PUBLIC_SOCKET","SENPI_RPC_HOST_INSTANCE_ID","SENPI_RPC_HOST_GENERATION","SENPI_RPC_HOST_DAEMON_DIR","SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID","SENPI_RPC_INTERNAL_KEY_STDIN","SENPI_RPC_HOST_WATCH_PSTART","SENPI_RPC_HOST_WATCH_PSTART_TICKS","SENPI_RPC_HOST_LIFETIME_FIFO","SENPI_RPC_SOCKET_SECRET_FILE","SENPI_ENGINE_TRUST","SENPI_ENGINE_TRUST_HOP"]);function isTransientDaemonEnvName(name){return TRANSIENT_ENV_NAMES.has(name)}function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)?!1:platform!=="win32"?PROVIDER_CREDENTIAL_ENV_NAMES.has(name)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||PROVIDER_CREDENTIAL_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}import{mkdir,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname4}from"node:path";var hostGenerationScopes=0;function isHostGenerationProcess(){return hostGenerationScopes>0}async function runAsHostGenerationProcess(action){hostGenerationScopes+=1;try{return await action()}finally{hostGenerationScopes-=1}}function decideEnsureAction(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs"||isHostGenerationProcess())return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let decision=decideHostAction(ensureClient(options,startedByUs),protocol,"upgrade");return decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:[...REQUIRED_HOST_CAPABILITIES,...requestedToolRuntime(options.hostArgs??[])],identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function requestedToolRuntime(hostArgs){for(let index=0;index<hostArgs.length;index++){let arg=hostArgs[index]??"",value=arg==="--tool-runtime"?hostArgs[index+1]:arg.startsWith("--tool-runtime=")?arg.slice(15):void 0;if(value!==void 0&&isToolRuntimeKind(value))return[toolRuntimeCapability(value)]}return[]}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}import{lstat}from"node:fs/promises";async function refuseIfStalled(paths,instanceId,socket,protocol){let generation=generationPaths(paths,instanceId);if(await hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:stallRefusalWindowMs()})&&await hostChildAlive(generation)!==!1)throw new HostEnsureRefusedError(socket,"host_stalled",protocol)}async function refuseIfForeignHeld(paths,registered,socket,protocol){if(!await publicEndpointAccepts(socket))return;let holder=await readHostHolder(paths,registered);throw new HostEnsureRefusedError(socket,"foreign_writer",protocol,void 0,holder)}async function readHostHolder(paths,registered){let record=parseJson(await readFileOrUndefined(generationPaths(paths,registered.instanceId).pidFile))??{};return{pid:registered.record.pid,instanceId:registered.instanceId,generation:registered.generation,processStartTime:registered.record.processStartTime,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,launchProfileId:typeof record.launchProfileId=="string"?record.launchProfileId:null,writerPid:registered.writer?.pid??null}}var FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS=2e3;async function publicEndpointAccepts(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!0;let entry=await statSocketIdentity(socket).then(identity=>identity===void 0?"absent":"present",()=>"unknown");return entry==="absent"?!1:entry==="unknown"?!0:probeSocketReachable(socket,FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS)}async function unregisteredEndpointHeld(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!1;let entry=await lstat(socket).then(found=>found.isSocket()?"socket":"not-socket",cause=>cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"?"absent":"unknown");return entry==="absent"?!1:entry!=="socket"?!0:(await socketEntryListenerState(socket)).verdict==="live"}import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{open,readFile as readFile2}from"node:fs/promises";var DEFAULT_STOP_TIMEOUT_MS=Math.max(CHILD_STOP_TIMEOUT_MS,childStalledStopMaxMs())+CHILD_KILL_EXIT_TIMEOUT_MS+5e3,SIGKILL_GRACE_MS=2e3,STOP_PROGRESS_FRESH_MS=1e4,AFTER_STALL_WAIT_GRACE_MS=CHILD_KILL_EXIT_TIMEOUT_MS+5e3,STOP_WAIT_BUDGET_MS=Math.max(DEFAULT_STOP_TIMEOUT_MS,childStalledStopMaxMs()+AFTER_STALL_WAIT_GRACE_MS)+SIGKILL_GRACE_MS;function ensureSender(){return{pid:process.pid,kind:"ensure"}}async function announceStop(target,targetPid){let intent={sender:target.sender,targetPid,reason:target.reason,signal:"SIGTERM",at:new Date().toISOString()};return await writeStopIntent(target.generation,intent),intent}async function matchesPidFileOrUnknown(pidFile,probe){try{return await processMatchesPidFile(pidFile,probe)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!1;throw error}}async function recordEscalation(target,announced){let current=await readStopIntent(target.generation).catch(()=>{});await noteEscalatedStop(target.daemonDir,target.instanceId,current??announced)}async function stopSpawnedChild(child,childExit,termTimeoutMs,target){let exited=()=>child.exitCode!==null||child.signalCode!==null,pid=child.pid;if(exited()||pid===void 0)return;let waitFor=async ms=>{let timer;try{return await Promise.race([childExit.then(()=>!0),new Promise(resolve6=>{timer=setTimeout(()=>resolve6(exited()),ms)})])}finally{clearTimeout(timer)}},announced=await announceStop(target,pid);if(signalPid(pid,"SIGTERM"),!await waitWhileSupervisorReports(target,termTimeoutMs,waitFor)){if(signalPid(pid,"SIGKILL"),!await waitFor(SIGKILL_GRACE_MS))throw new Error(`RPC socket host pid ${pid} remained alive after SIGKILL`);await recordEscalation(target,announced)}}async function stopManagedHost(pidFile,termTimeoutMs,target,readStartTime=readProcessStartTime){let announced=await announceStop(target,pidFile.pid);if(await signalValidated(pidFile,"SIGTERM",readStartTime),!await waitWhileSupervisorReports(target,termTimeoutMs,ms=>waitForGone(pidFile,ms,readStartTime))){if(await signalValidated(pidFile,"SIGKILL",readStartTime),!await waitForGone(pidFile,SIGKILL_GRACE_MS,readStartTime))throw new Error(`RPC socket host pid ${pidFile.pid} remained alive after SIGKILL`);await recordEscalation(target,announced)}}async function waitWhileSupervisorReports(target,termTimeoutMs,waitFor){if(await waitFor(termTimeoutMs))return!0;let extended=!1;for(;;){let untilAt=await activeStopProgress(target.generation,Date.now(),STOP_PROGRESS_FRESH_MS);if(untilAt===void 0)return extended&&await waitFor(AFTER_STALL_WAIT_GRACE_MS);if(extended=!0,await waitFor(Math.min(STOP_PROGRESS_FRESH_MS,Math.max(1,untilAt-Date.now()))))return!0}}async function resolvePidFileOwnership(pidFile,readStartTime=readProcessStartTime){try{return await processMatchesPidFile(pidFile,readStartTime,processIsLive,{attempts:1})?"owns":"gone"}catch(error){if(error instanceof ProcessIdentityUnreadableError)return"unknown";throw error}}async function signalValidated(pidFile,signal,readStartTime=readProcessStartTime){await resolvePidFileOwnership(pidFile,readStartTime)==="owns"&&signalPid(pidFile.pid,signal)}async function waitForGone(pidFile,timeoutMs,readStartTime=readProcessStartTime){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await resolvePidFileOwnership(pidFile,readStartTime)==="gone")return!0;await delay(50)}return await resolvePidFileOwnership(pidFile,readStartTime)==="gone"}function signalPid(pid,signal){try{process.kill(pid,signal)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}import{existsSync}from"node:fs";import{basename,dirname as dirname2,join as join2,resolve as resolve2}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary,sibling=resolveHostLifecycleEntryPath()??null,bundledSupervisor=resolveBundledSupervisorEntryPath()??null){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:sibling!==null?{command:process.execPath,args:[...runtimeExecArgv(),sibling,...supervisorArgs]}:bundledSupervisor!==null?{command:process.execPath,args:[...runtimeExecArgv(),bundledSupervisor,INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:{command:process.execPath,args:[...runtimeExecArgv(),resolveCliMainPath(),INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}}var BUNDLED_SUPERVISOR_ENTRY="host-supervisor.js";function resolveBundledSupervisorEntryPath(){let entry=join2(dirname2(resolveCliMainPath()),BUNDLED_SUPERVISOR_ENTRY);return existsSync(entry)?entry:void 0}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url);if(basename(dirname2(modulePath))==="chunks")return;let extension=modulePath.endsWith(".ts")?".ts":".js",sibling=resolve2(dirname2(modulePath),`host-lifecycle${extension}`);return existsSync(sibling)?sibling:void 0}var SPAWNED_HOST_PROBE_TIMEOUT_MS=1e4;async function pollProtocolInfo(socket,timeoutMs,isCompatible2,childExit){let deadline=Date.now()+timeoutMs,lastProtocol;for(;Date.now()<=deadline;){let probe=holdProtocolInfo(socket,Math.min(SPAWNED_HOST_PROBE_TIMEOUT_MS,Math.max(1,deadline-Date.now()))),raced=childExit?await Promise.race([probe,childExit]):await probe;if(isChildExit(raced)){let held=await probe;if(!held)return{ready:!1,protocol:lastProtocol,exited:raced};if(lastProtocol=held.info,isCompatible2(held.info))return{ready:!0,protocol:held.info,hold:held.hold};held.hold.release()}else if(raced){if(lastProtocol=raced.info,isCompatible2(raced.info))return{ready:!0,protocol:raced.info,hold:raced.hold};raced.hold.release()}await delay2(50)}return{ready:!1,protocol:lastProtocol}}function isChildExit(value){return!!value&&"code"in value&&"signal"in value}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function caseFormsOf(env,name,platform){if(platform!=="win32")return name in env?[name]:[];let upper=name.toUpperCase();return Object.keys(env).filter(key=>key.toUpperCase()===upper)}function deleteName(env,name,platform){for(let key of caseFormsOf(env,name,platform))delete env[key]}function setName(env,name,value,platform){deleteName(env,name,platform),env[name]=value}var ENGINE_TRUST_MARKER_ENV="SENPI_ENGINE_TRUST",ENGINE_TRUST_HOP_ENV="SENPI_ENGINE_TRUST_HOP";var ENGINE_TRUST_FALLBACK_REASONS=["helper-timeout","helper-crash","helper-malformed-output","helper-missing","helper-wrong-arch","helper-signature","access-denied","negatives-incomplete","linux-bundle-unreadable","linux-bundle-malformed"],EngineTrustContractError=class extends Error{constructor(code,message){super(message),this.name="EngineTrustContractError",this.code=code}},path=external_exports.string().min(1).refine(value=>!value.includes("\0")),digest=external_exports.string().regex(/^[0-9a-f]{64}$/u),restoreValue=external_exports.string().nullable().optional(),markerSchema=external_exports.strictObject({v:external_exports.literal(1),file:path,sha256:digest,automatic:external_exports.enum(["os","fallback"]),fallbackReason:external_exports.enum(ENGINE_TRUST_FALLBACK_REASONS).nullable(),owner:external_exports.enum(["server","standalone"]),user:digest.nullable(),defaults:external_exports.strictObject({file:path,dir:path}).nullable(),restore:external_exports.strictObject({NODE_EXTRA_CA_CERTS:restoreValue,NODE_USE_SYSTEM_CA:restoreValue,SSL_CERT_FILE:restoreValue,SSL_CERT_DIR:restoreValue,BUN_OPTIONS:restoreValue})}).refine(marker=>marker.automatic==="fallback"==(marker.fallbackReason!==null)).refine(marker=>marker.owner==="standalone"||marker.defaults!==null).refine(marker=>marker.owner==="server"||marker.restore.BUN_OPTIONS===void 0);function serializeEngineTrustMarker(marker){let parsed=markerSchema.safeParse(marker);if(!parsed.success)throw new EngineTrustContractError("trust-marker-invalid","engine trust marker is not version 1");return JSON.stringify(parsed.data)}var EXTRA_CA_ENV="NODE_EXTRA_CA_CERTS",SERVER_REMOVED_NAMES=["NODE_USE_SYSTEM_CA","BUN_OPTIONS"];function buildTrustLaunchEnvironment(base,options){let{marker,hop,platform}=options,env={...base};if(marker.owner==="server")for(let name of SERVER_REMOVED_NAMES)deleteName(env,name,platform);return marker.defaults!==null&&(setName(env,"SSL_CERT_FILE",representablePath(marker.defaults.file,platform),platform),setName(env,"SSL_CERT_DIR",representablePath(marker.defaults.dir,platform),platform)),setName(env,EXTRA_CA_ENV,marker.file,platform),setName(env,ENGINE_TRUST_MARKER_ENV,serializeEngineTrustMarker(marker),platform),hop?setName(env,ENGINE_TRUST_HOP_ENV,"1",platform):deleteName(env,ENGINE_TRUST_HOP_ENV,platform),definedEntries(env)}function representablePath(path2,platform){if(path2.includes(platform==="win32"?";":":"))throw new EngineTrustContractError("trust-path-unrepresentable","engine trust closure path holds a list separator");return path2}function definedEntries(env){let out={};for(let[name,value]of Object.entries(env))value!==void 0&&(out[name]=value);return out}function engineTrustHandOffEnvironment(marker,platform){return buildTrustLaunchEnvironment({},{marker:{...marker,restore:{}},hop:!1,platform})}var EXPECTED_RUNTIME_BUILD_ID_ENV="SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID",NEW_WORK_COMMANDS=new Set(["prompt","steer","follow_up","send_custom_message","continue_from_leaf","resume_session","append_user_message","bash","compact","wake","edit_assistant_message","edit_user_message"]),DEFAULT_POLL_MS=200,HostIdleHandover=class{constructor(options){this.options=options}view(){return this.operation?.view}admits(commandType){let state=this.operation?.view.state;return state===void 0||state==="handover_blocked"||!NEW_WORK_COMMANDS.has(commandType)}async begin(request){let current=this.operation;if(current!==void 0&¤t.view.operationId===request.operationId)return sameTerms(current.request,request)?answer(current):{kind:"refused",reason:"operation_conflict",detail:"this operation id names other terms"};if(current!==void 0&¤t.view.state!=="handover_blocked")return current.request.targetRuntimeBuildId===request.targetRuntimeBuildId&&!!current.request.mcpPresenterEnforcement==!!request.mcpPresenterEnforcement?answer(current):{kind:"refused",reason:"handover_in_progress",detail:current.view.operationId};let self=this.options.identity();if(self.instanceId!==request.ifInstanceId||self.generation!==request.ifGeneration)return{kind:"refused",reason:"stale_generation",detail:`this host is ${self.instanceId} generation ${self.generation}`};if(self.runtimeBuildId===request.targetRuntimeBuildId)return{kind:"refused",reason:"already_current",detail:self.runtimeBuildId};let operation={request,view:{operationId:request.operationId,state:"handover_pending",targetRuntimeBuildId:request.targetRuntimeBuildId}};return this.operation=operation,this.options.log?.(`handover ${request.operationId} pending: no new work is admitted`),this.idleNow()?(await this.switchOver(operation),answer(operation)):(this.timer=setInterval(()=>this.observe(),this.options.pollMs??DEFAULT_POLL_MS),this.timer.unref?.(),answer(operation))}observe(){let operation=this.operation;operation?.view.state==="handover_pending"&&this.idleNow()&&this.switchOver(operation)}dispose(){this.stopTimer()}idleNow(){try{return this.options.isIdle()}catch(cause){return this.options.log?.(`handover idle check failed, waiting: ${String(cause)}`),!1}}async switchOver(operation){if(operation.view.state!=="handover_pending")return;this.stopTimer(),operation.view={...operation.view,state:"handover_switching"};let outcome=await this.options.perform(operation.request).catch(cause=>({ok:!1,reason:`successor_unavailable: ${String(cause)}`}));operation.view=outcome.ok?{...operation.view,state:"handover_completed",successor:outcome.successor}:{...operation.view,state:"handover_blocked",reason:outcome.reason},this.options.log?.(`handover ${operation.view.operationId} ${operation.view.state}`)}stopTimer(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0}};function sameTerms(a,b){return a.targetRuntimeBuildId===b.targetRuntimeBuildId&&!!a.mcpPresenterEnforcement==!!b.mcpPresenterEnforcement&&a.ifInstanceId===b.ifInstanceId&&a.ifGeneration===b.ifGeneration}function answer(operation){return{kind:"operation",view:operation.view}}function initialHostEnvironment(options){return daemonEnvironment(process.env,options.env,{...trustHandOff(),[ENV_AGENT_DIR]:options.agentDir??getAgentDir(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir})}function trustHandOff(){let marker=adoptedEngineTrust();return marker===void 0?{}:engineTrustHandOffEnvironment(marker,process.platform)}function successorHostEnvironment(options){return daemonEnvironment(process.env,options.env,{...trustHandOff(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),...options.agentDir?{[ENV_AGENT_DIR]:options.agentDir}:{},[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir,...options.expectedRuntimeBuildId!==void 0&&{[EXPECTED_RUNTIME_BUILD_ID_ENV]:options.expectedRuntimeBuildId}})}var DEFAULT_READINESS_TIMEOUT_MS=1e4;async function startHost(paths,socket,options,generation=0){let testOptions=options._test,lifetimeOwner=options.owner?await callerHostOwner():null,instanceId=randomUUID(),stopTarget=reason=>({daemonDir:paths.dir,generation:generationPaths(paths,instanceId),instanceId,sender:ensureSender(),reason});process.platform==="win32"&&await ensureSocketSecret(socketSecretPath(socket)),await writeHostSettings(paths,{socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??9e5,generation,instanceId}),await writeHostOwner(generationPaths(paths,instanceId).dir,lifetimeOwner);let stderr=await open(paths.stderrLog,generation===0?"w":"a",384),pidFile,child,exitedEarly,childExit,presenterEnrollment;try{let supervisorArgs=["--socket",socket,...options.owner?["--owner-fd",String(OWNER_WATCH_FD)]:[],...options.presenterBootstrap?["--mcp-presenter-fd","4"]:[],...options.mcpPresenterEnforcement?["--mcp-presenter-enforcement"]:[],...options.hostArgs??[]],launch=testOptions?.spawn??testOptions?.launch?.(supervisorArgs)??defaultHostLaunch(supervisorArgs);if(child=spawnWithPrivateFds(spawn,launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:initialHostEnvironment({agentDir:options.agentDir,env:options.env,paths,instanceId,generation}),stdio:options.presenterBootstrap?["ignore","ignore",stderr.fd,options.owner?"pipe":"ignore","pipe"]:options.owner?["ignore","ignore",stderr.fd,"pipe"]:["ignore","ignore",stderr.fd]}),options.presenterBootstrap&&(presenterEnrollment=relayPresenterBootstrap(options.presenterBootstrap,child,{kind:"initial",predecessorHostInstance:null})),childExit=new Promise(resolveExit=>{child.once("exit",(code,signal)=>{exitedEarly={code,signal},resolveExit(exitedEarly)})}),options.owner&&keepOwnerPipe(child),child.pid===void 0)throw new Error("failed to spawn RPC socket host");let probe=testOptions?.readProcessStartTime??readProcessStartTime,observedStartTime=await Promise.race([waitForStartTime(child.pid,1e4,probe),childExit.then(()=>{throw new Error("RPC socket host exited before its start time could be read")})]),unhurriedProbe=testOptions?.readProcessStartTime?testOptions.readProcessStartTime:pid=>readProcessStartTime(pid,process.platform,15e3),processStartTime=observedStartTime??await unhurriedProbe(child.pid).catch(()=>{});pidFile={pid:child.pid,processStartTime:processStartTime??null},await testOptions?.beforePidFileWrite?.(),await writeHostRegistration(paths,{record:pidFile,socket,instanceId,generation,launchProfileId:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd()).profile_id,build:engineBuildIdentity()}),child.unref()}catch(error){let exitedBeforeCleanup=exitedEarly;if(!exitedBeforeCleanup&&child?.pid!==void 0&&childExit&&await stopUnregisteredStart(child,childExit,stopTarget("start_failed")),!exitedBeforeCleanup)throw await clearHostRegistration(paths),error;let diagnostic2=await appendStderr(paths,`RPC socket host exited with code ${exitedBeforeCleanup.code??"null"}${exitedBeforeCleanup.signal?` (${exitedBeforeCleanup.signal})`:""} before answering get_protocol_info`);throw await clearHostRegistration(paths),new Error(diagnostic2)}finally{await stderr.close()}let readinessTimeoutMs=testOptions?.readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS,result=await pollProtocolInfo(socket,readinessTimeoutMs,isCompatible,childExit);if(result.ready)return await presenterEnrollment,{pid:pidFile.pid,socket,reused:!1,release:result.hold.release};await testOptions?.beforeReadinessTeardown?.();let stopFailure=await stopSpawnedChild(child,childExit,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS,stopTarget("readiness_timeout")).then(()=>{},error=>error instanceof Error?error.message:String(error)),message=result.protocol?`RPC socket host answered get_protocol_info with protocolVersion ${result.protocol.protocolVersion}, serverVersion ${result.protocol.serverVersion} and capabilities ${JSON.stringify(result.protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`:result.exited?`RPC socket host exited with code ${result.exited.code??"null"}${result.exited.signal?` (${result.exited.signal})`:""} before answering get_protocol_info`:`spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`,diagnostic=await appendStderr(paths,stopFailure===void 0?message:`${message} (teardown also reported: ${stopFailure})`);throw await clearHostRegistration(paths),new Error(diagnostic)}async function stopUnregisteredStart(child,childExit,target){let pid=child.pid,running=()=>child.exitCode===null&&child.signalCode===null;if(pid===void 0||!running())return;let announced=await announceStop(target,pid);try{signalPid(pid,"SIGTERM")}catch{}if(await Promise.race([childExit,delay(2e3)]),!running())return;try{signalPid(pid,"SIGKILL")}catch{}await Promise.race([childExit.then(()=>!0),delay(SIGKILL_GRACE_MS).then(()=>!1)])&&await recordEscalation(target,announced)}async function appendStderr(paths,message){try{let stderr=(await readFile2(paths.stderrLog,"utf8")).trim();return stderr?`${message}
|
|
2
|
+
import{CUSTOM_UNSUPPORTED_CAPABILITY,DEFAULT_PROBE_TIMEOUT_MS,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,RPC_CLIENT_CAPABILITIES_ENV,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,acquireHostEnsureLock,anyGenerationLive,busyLegacyHostDetail,computeRuntimeBuildId,decideHostAction,describeSessions,electPointer,engineBuildIdentity,gcEndpoint,gcHostEndpoints,holdProtocolInfo,holdSessionCount,hostEnsureLockOptions,hostEnsureLockTarget,hostLaunchProfile,judgeStaleEngine,observeProtocolInfo,parseHostStopGeneration,probeProtocolInfo,probeSocketReachable,provenLegacyOwner,retireIdleLegacyHost,signalGeneration,socketHostLaunchProfile,staleStopGeneration,stopHost}from"./chunk-F4OHTL2K.js";import{endpointKindOfSocket,listHostEndpoints}from"./chunk-XGBRBCIQ.js";import{requestOnSocket}from"./chunk-WEGTCUO3.js";import{rpcKeyRoot,withRpcKeyRoot}from"./chunk-GDPWQJDQ.js";import{presenterBootstrapStream,relayPresenterBootstrap}from"./chunk-7DWTKE4Z.js";import{INTERNAL_HOST_DIR_PREFIX,INTERNAL_SUPERVISOR_FLAG,OWNER_WATCH_FD,internalHostDirRoots,isHostCrash,keepOwnerPipe,loopLagErrorMs,noteEscalatedStop,readHostCrashRecords,resolveCliMainPath,runtimeExecArgv}from"./chunk-S2M5D5GS.js";import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STOP_TIMEOUT_MS,DEFAULT_HOST_IDLE_EXIT_MS,activeStopProgress,childStalledStopMaxMs,claimOwnerIsLive,clearHostRegistration,hostChildAlive,hostLoopStalled,provenOwner,pruneDeadGenerations,readGenerationRows,readHostProcessMetrics,readHostRegistration,readSessionPathClaims,readStopIntent,releaseGeneration,stallRefusalWindowMs,writeGenerationRecord,writeHostRegistration,writeStopIntent,writtenByThisProcess}from"./chunk-6LDUM5CL.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,callerHostOwner,claimHostOwner,createDaemonDirectories,createHostDaemonPaths,ensureEndpointIdentity,generationPaths,hostDaemonDirectoryPaths,parseJson,parseShardSocket,readFileOrUndefined,readHostOwner,readHostSettings,sameEndpoint,sameHostOwner,sessionDirectoryRemoved,shardKey,shardSocketPathForKey,writeHostOwner,writeHostSettings,writeStateFile}from"./chunk-FNBEICAA.js";import{OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-E6UCZ7E5.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV}from"./chunk-UYO5Z35O.js";import{envSlotVarNames}from"./chunk-7ORS33CE.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{isSessionRuntimeKind,isToolRuntimeKind,toolRuntimeCapability}from"./chunk-27XEDYQA.js";import{adoptedEngineTrust}from"./chunk-EVTTLPIY.js";import{providerCredentialEnvNames}from"./chunk-TG4E7Z7W.js";import{spawnWithPrivateFds}from"./chunk-6WISUXVI.js";import{MAX_SOCKET_PATH_BYTES,generationBindPath,socketEntryListenerState,statSocketIdentity}from"./chunk-OM7LH7AP.js";import{acquireOwnershipSafeLock,ensureSocketSecret,socketSecretPath}from"./chunk-QEESHRTS.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-ISZ4EWIS.js";import{ProcessIdentityUnreadableError,processIsLive,processMatchesPidFile,readProcessStartTime,waitForStartTime}from"./chunk-O5RYI3IW.js";import{writeSync as writeSync2}from"node:fs";import{join as join6,resolve as resolve5}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path2=>["--extension",path2])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^BSK_(HOME|BIN)$/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],PROVIDER_CREDENTIAL_ENV_NAMES=new Set([...providerCredentialEnvNames(),...envSlotVarNames()]),WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","OMO_BROWSER_ENGINE","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID","SENPI_RPC_HOST_WATCH_FD","SENPI_RPC_HOST_WATCH_PPID","SENPI_RPC_HOST_SCRATCH_DIR","SENPI_RPC_HOST_CLEANUP_PATHS","SENPI_RPC_HOST_PUBLIC_SOCKET","SENPI_RPC_HOST_INSTANCE_ID","SENPI_RPC_HOST_GENERATION","SENPI_RPC_HOST_DAEMON_DIR","SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID","SENPI_RPC_INTERNAL_KEY_STDIN","SENPI_RPC_HOST_WATCH_PSTART","SENPI_RPC_HOST_WATCH_PSTART_TICKS","SENPI_RPC_HOST_LIFETIME_FIFO","SENPI_RPC_SOCKET_SECRET_FILE","SENPI_ENGINE_TRUST","SENPI_ENGINE_TRUST_HOP"]);function isTransientDaemonEnvName(name){return TRANSIENT_ENV_NAMES.has(name)}function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)?!1:platform!=="win32"?PROVIDER_CREDENTIAL_ENV_NAMES.has(name)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||PROVIDER_CREDENTIAL_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}import{mkdir,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname4}from"node:path";var hostGenerationScopes=0;function isHostGenerationProcess(){return hostGenerationScopes>0}async function runAsHostGenerationProcess(action){hostGenerationScopes+=1;try{return await action()}finally{hostGenerationScopes-=1}}function decideEnsureAction(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs"||isHostGenerationProcess())return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let decision=decideHostAction(ensureClient(options,startedByUs),protocol,"upgrade");return decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:[...REQUIRED_HOST_CAPABILITIES,...requestedToolRuntime(options.hostArgs??[])],identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function requestedToolRuntime(hostArgs){for(let index=0;index<hostArgs.length;index++){let arg=hostArgs[index]??"",value=arg==="--tool-runtime"?hostArgs[index+1]:arg.startsWith("--tool-runtime=")?arg.slice(15):void 0;if(value!==void 0&&isToolRuntimeKind(value))return[toolRuntimeCapability(value)]}return[]}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}import{lstat}from"node:fs/promises";async function refuseIfStalled(paths,instanceId,socket,protocol){let generation=generationPaths(paths,instanceId);if(await hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:stallRefusalWindowMs()})&&await hostChildAlive(generation)!==!1)throw new HostEnsureRefusedError(socket,"host_stalled",protocol)}async function refuseIfForeignHeld(paths,registered,socket,protocol){if(!await publicEndpointAccepts(socket))return;let holder=await readHostHolder(paths,registered);throw new HostEnsureRefusedError(socket,"foreign_writer",protocol,void 0,holder)}async function readHostHolder(paths,registered){let record=parseJson(await readFileOrUndefined(generationPaths(paths,registered.instanceId).pidFile))??{};return{pid:registered.record.pid,instanceId:registered.instanceId,generation:registered.generation,processStartTime:registered.record.processStartTime,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,launchProfileId:typeof record.launchProfileId=="string"?record.launchProfileId:null,writerPid:registered.writer?.pid??null}}var FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS=2e3;async function publicEndpointAccepts(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!0;let entry=await statSocketIdentity(socket).then(identity=>identity===void 0?"absent":"present",()=>"unknown");return entry==="absent"?!1:entry==="unknown"?!0:probeSocketReachable(socket,FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS)}async function unregisteredEndpointHeld(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!1;let entry=await lstat(socket).then(found=>found.isSocket()?"socket":"not-socket",cause=>cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"?"absent":"unknown");return entry==="absent"?!1:entry!=="socket"?!0:(await socketEntryListenerState(socket)).verdict==="live"}import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{open,readFile as readFile2}from"node:fs/promises";var DEFAULT_STOP_TIMEOUT_MS=Math.max(CHILD_STOP_TIMEOUT_MS,childStalledStopMaxMs())+CHILD_KILL_EXIT_TIMEOUT_MS+5e3,SIGKILL_GRACE_MS=2e3,STOP_PROGRESS_FRESH_MS=1e4,AFTER_STALL_WAIT_GRACE_MS=CHILD_KILL_EXIT_TIMEOUT_MS+5e3,STOP_WAIT_BUDGET_MS=Math.max(DEFAULT_STOP_TIMEOUT_MS,childStalledStopMaxMs()+AFTER_STALL_WAIT_GRACE_MS)+SIGKILL_GRACE_MS;function ensureSender(){return{pid:process.pid,kind:"ensure"}}async function announceStop(target,targetPid){let intent={sender:target.sender,targetPid,reason:target.reason,signal:"SIGTERM",at:new Date().toISOString()};return await writeStopIntent(target.generation,intent),intent}async function matchesPidFileOrUnknown(pidFile,probe){try{return await processMatchesPidFile(pidFile,probe)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!1;throw error}}async function recordEscalation(target,announced){let current=await readStopIntent(target.generation).catch(()=>{});await noteEscalatedStop(target.daemonDir,target.instanceId,current??announced)}async function stopSpawnedChild(child,childExit,termTimeoutMs,target){let exited=()=>child.exitCode!==null||child.signalCode!==null,pid=child.pid;if(exited()||pid===void 0)return;let waitFor=async ms=>{let timer;try{return await Promise.race([childExit.then(()=>!0),new Promise(resolve6=>{timer=setTimeout(()=>resolve6(exited()),ms)})])}finally{clearTimeout(timer)}},announced=await announceStop(target,pid);if(signalPid(pid,"SIGTERM"),!await waitWhileSupervisorReports(target,termTimeoutMs,waitFor)){if(signalPid(pid,"SIGKILL"),!await waitFor(SIGKILL_GRACE_MS))throw new Error(`RPC socket host pid ${pid} remained alive after SIGKILL`);await recordEscalation(target,announced)}}async function stopManagedHost(pidFile,termTimeoutMs,target,readStartTime=readProcessStartTime){let announced=await announceStop(target,pidFile.pid);if(await signalValidated(pidFile,"SIGTERM",readStartTime),!await waitWhileSupervisorReports(target,termTimeoutMs,ms=>waitForGone(pidFile,ms,readStartTime))){if(await signalValidated(pidFile,"SIGKILL",readStartTime),!await waitForGone(pidFile,SIGKILL_GRACE_MS,readStartTime))throw new Error(`RPC socket host pid ${pidFile.pid} remained alive after SIGKILL`);await recordEscalation(target,announced)}}async function waitWhileSupervisorReports(target,termTimeoutMs,waitFor){if(await waitFor(termTimeoutMs))return!0;let extended=!1;for(;;){let untilAt=await activeStopProgress(target.generation,Date.now(),STOP_PROGRESS_FRESH_MS);if(untilAt===void 0)return extended&&await waitFor(AFTER_STALL_WAIT_GRACE_MS);if(extended=!0,await waitFor(Math.min(STOP_PROGRESS_FRESH_MS,Math.max(1,untilAt-Date.now()))))return!0}}async function resolvePidFileOwnership(pidFile,readStartTime=readProcessStartTime){try{return await processMatchesPidFile(pidFile,readStartTime,processIsLive,{attempts:1})?"owns":"gone"}catch(error){if(error instanceof ProcessIdentityUnreadableError)return"unknown";throw error}}async function signalValidated(pidFile,signal,readStartTime=readProcessStartTime){await resolvePidFileOwnership(pidFile,readStartTime)==="owns"&&signalPid(pidFile.pid,signal)}async function waitForGone(pidFile,timeoutMs,readStartTime=readProcessStartTime){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await resolvePidFileOwnership(pidFile,readStartTime)==="gone")return!0;await delay(50)}return await resolvePidFileOwnership(pidFile,readStartTime)==="gone"}function signalPid(pid,signal){try{process.kill(pid,signal)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}import{existsSync}from"node:fs";import{basename,dirname as dirname2,join as join2,resolve as resolve2}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary,sibling=resolveHostLifecycleEntryPath()??null,bundledSupervisor=resolveBundledSupervisorEntryPath()??null){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:sibling!==null?{command:process.execPath,args:[...runtimeExecArgv(),sibling,...supervisorArgs]}:bundledSupervisor!==null?{command:process.execPath,args:[...runtimeExecArgv(),bundledSupervisor,INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:{command:process.execPath,args:[...runtimeExecArgv(),resolveCliMainPath(),INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}}var BUNDLED_SUPERVISOR_ENTRY="host-supervisor.js";function resolveBundledSupervisorEntryPath(){let entry=join2(dirname2(resolveCliMainPath()),BUNDLED_SUPERVISOR_ENTRY);return existsSync(entry)?entry:void 0}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url);if(basename(dirname2(modulePath))==="chunks")return;let extension=modulePath.endsWith(".ts")?".ts":".js",sibling=resolve2(dirname2(modulePath),`host-lifecycle${extension}`);return existsSync(sibling)?sibling:void 0}var SPAWNED_HOST_PROBE_TIMEOUT_MS=1e4;async function pollProtocolInfo(socket,timeoutMs,isCompatible2,childExit){let deadline=Date.now()+timeoutMs,lastProtocol;for(;Date.now()<=deadline;){let probe=holdProtocolInfo(socket,Math.min(SPAWNED_HOST_PROBE_TIMEOUT_MS,Math.max(1,deadline-Date.now()))),raced=childExit?await Promise.race([probe,childExit]):await probe;if(isChildExit(raced)){let held=await probe;if(!held)return{ready:!1,protocol:lastProtocol,exited:raced};if(lastProtocol=held.info,isCompatible2(held.info))return{ready:!0,protocol:held.info,hold:held.hold};held.hold.release()}else if(raced){if(lastProtocol=raced.info,isCompatible2(raced.info))return{ready:!0,protocol:raced.info,hold:raced.hold};raced.hold.release()}await delay2(50)}return{ready:!1,protocol:lastProtocol}}function isChildExit(value){return!!value&&"code"in value&&"signal"in value}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function caseFormsOf(env,name,platform){if(platform!=="win32")return name in env?[name]:[];let upper=name.toUpperCase();return Object.keys(env).filter(key=>key.toUpperCase()===upper)}function deleteName(env,name,platform){for(let key of caseFormsOf(env,name,platform))delete env[key]}function setName(env,name,value,platform){deleteName(env,name,platform),env[name]=value}var ENGINE_TRUST_MARKER_ENV="SENPI_ENGINE_TRUST",ENGINE_TRUST_HOP_ENV="SENPI_ENGINE_TRUST_HOP";var ENGINE_TRUST_FALLBACK_REASONS=["helper-timeout","helper-crash","helper-malformed-output","helper-missing","helper-wrong-arch","helper-signature","access-denied","negatives-incomplete","linux-bundle-unreadable","linux-bundle-malformed"],EngineTrustContractError=class extends Error{constructor(code,message){super(message),this.name="EngineTrustContractError",this.code=code}},path=external_exports.string().min(1).refine(value=>!value.includes("\0")),digest=external_exports.string().regex(/^[0-9a-f]{64}$/u),restoreValue=external_exports.string().nullable().optional(),markerSchema=external_exports.strictObject({v:external_exports.literal(1),file:path,sha256:digest,automatic:external_exports.enum(["os","fallback"]),fallbackReason:external_exports.enum(ENGINE_TRUST_FALLBACK_REASONS).nullable(),owner:external_exports.enum(["server","standalone"]),user:digest.nullable(),defaults:external_exports.strictObject({file:path,dir:path}).nullable(),restore:external_exports.strictObject({NODE_EXTRA_CA_CERTS:restoreValue,NODE_USE_SYSTEM_CA:restoreValue,SSL_CERT_FILE:restoreValue,SSL_CERT_DIR:restoreValue,BUN_OPTIONS:restoreValue})}).refine(marker=>marker.automatic==="fallback"==(marker.fallbackReason!==null)).refine(marker=>marker.owner==="standalone"||marker.defaults!==null).refine(marker=>marker.owner==="server"||marker.restore.BUN_OPTIONS===void 0);function serializeEngineTrustMarker(marker){let parsed=markerSchema.safeParse(marker);if(!parsed.success)throw new EngineTrustContractError("trust-marker-invalid","engine trust marker is not version 1");return JSON.stringify(parsed.data)}var EXTRA_CA_ENV="NODE_EXTRA_CA_CERTS",SERVER_REMOVED_NAMES=["NODE_USE_SYSTEM_CA","BUN_OPTIONS"];function buildTrustLaunchEnvironment(base,options){let{marker,hop,platform}=options,env={...base};if(marker.owner==="server")for(let name of SERVER_REMOVED_NAMES)deleteName(env,name,platform);return marker.defaults!==null&&(setName(env,"SSL_CERT_FILE",representablePath(marker.defaults.file,platform),platform),setName(env,"SSL_CERT_DIR",representablePath(marker.defaults.dir,platform),platform)),setName(env,EXTRA_CA_ENV,marker.file,platform),setName(env,ENGINE_TRUST_MARKER_ENV,serializeEngineTrustMarker(marker),platform),hop?setName(env,ENGINE_TRUST_HOP_ENV,"1",platform):deleteName(env,ENGINE_TRUST_HOP_ENV,platform),definedEntries(env)}function representablePath(path2,platform){if(path2.includes(platform==="win32"?";":":"))throw new EngineTrustContractError("trust-path-unrepresentable","engine trust closure path holds a list separator");return path2}function definedEntries(env){let out={};for(let[name,value]of Object.entries(env))value!==void 0&&(out[name]=value);return out}function engineTrustHandOffEnvironment(marker,platform){return buildTrustLaunchEnvironment({},{marker:{...marker,restore:{}},hop:!1,platform})}var EXPECTED_RUNTIME_BUILD_ID_ENV="SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID",NEW_WORK_COMMANDS=new Set(["prompt","steer","follow_up","send_custom_message","continue_from_leaf","resume_session","append_user_message","bash","compact","wake","edit_assistant_message","edit_user_message"]),DEFAULT_POLL_MS=200,HostIdleHandover=class{constructor(options){this.options=options}view(){return this.operation?.view}admits(commandType){let state=this.operation?.view.state;return state===void 0||state==="handover_blocked"||!NEW_WORK_COMMANDS.has(commandType)}async begin(request){let current=this.operation;if(current!==void 0&¤t.view.operationId===request.operationId)return sameTerms(current.request,request)?answer(current):{kind:"refused",reason:"operation_conflict",detail:"this operation id names other terms"};if(current!==void 0&¤t.view.state!=="handover_blocked")return current.request.targetRuntimeBuildId===request.targetRuntimeBuildId&&!!current.request.mcpPresenterEnforcement==!!request.mcpPresenterEnforcement?answer(current):{kind:"refused",reason:"handover_in_progress",detail:current.view.operationId};let self=this.options.identity();if(self.instanceId!==request.ifInstanceId||self.generation!==request.ifGeneration)return{kind:"refused",reason:"stale_generation",detail:`this host is ${self.instanceId} generation ${self.generation}`};if(self.runtimeBuildId===request.targetRuntimeBuildId)return{kind:"refused",reason:"already_current",detail:self.runtimeBuildId};let operation={request,view:{operationId:request.operationId,state:"handover_pending",targetRuntimeBuildId:request.targetRuntimeBuildId}};return this.operation=operation,this.options.log?.(`handover ${request.operationId} pending: no new work is admitted`),this.idleNow()?(await this.switchOver(operation),answer(operation)):(this.timer=setInterval(()=>this.observe(),this.options.pollMs??DEFAULT_POLL_MS),this.timer.unref?.(),answer(operation))}observe(){let operation=this.operation;operation?.view.state==="handover_pending"&&this.idleNow()&&this.switchOver(operation)}dispose(){this.stopTimer()}idleNow(){try{return this.options.isIdle()}catch(cause){return this.options.log?.(`handover idle check failed, waiting: ${String(cause)}`),!1}}async switchOver(operation){if(operation.view.state!=="handover_pending")return;this.stopTimer(),operation.view={...operation.view,state:"handover_switching"};let outcome=await this.options.perform(operation.request).catch(cause=>({ok:!1,reason:`successor_unavailable: ${String(cause)}`}));operation.view=outcome.ok?{...operation.view,state:"handover_completed",successor:outcome.successor}:{...operation.view,state:"handover_blocked",reason:outcome.reason},this.options.log?.(`handover ${operation.view.operationId} ${operation.view.state}`)}stopTimer(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0}};function sameTerms(a,b){return a.targetRuntimeBuildId===b.targetRuntimeBuildId&&!!a.mcpPresenterEnforcement==!!b.mcpPresenterEnforcement&&a.ifInstanceId===b.ifInstanceId&&a.ifGeneration===b.ifGeneration}function answer(operation){return{kind:"operation",view:operation.view}}function initialHostEnvironment(options){return daemonEnvironment(process.env,options.env,{...trustHandOff(),[ENV_AGENT_DIR]:options.agentDir??getAgentDir(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir})}function trustHandOff(){let marker=adoptedEngineTrust();return marker===void 0?{}:engineTrustHandOffEnvironment(marker,process.platform)}function successorHostEnvironment(options){return daemonEnvironment(process.env,options.env,{...trustHandOff(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),...options.agentDir?{[ENV_AGENT_DIR]:options.agentDir}:{},[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir,...options.expectedRuntimeBuildId!==void 0&&{[EXPECTED_RUNTIME_BUILD_ID_ENV]:options.expectedRuntimeBuildId}})}var DEFAULT_READINESS_TIMEOUT_MS=1e4;async function startHost(paths,socket,options,generation=0){let testOptions=options._test,lifetimeOwner=options.owner?await callerHostOwner():null,instanceId=randomUUID(),stopTarget=reason=>({daemonDir:paths.dir,generation:generationPaths(paths,instanceId),instanceId,sender:ensureSender(),reason});process.platform==="win32"&&await ensureSocketSecret(socketSecretPath(socket)),await writeHostSettings(paths,{socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??9e5,generation,instanceId}),await writeHostOwner(generationPaths(paths,instanceId).dir,lifetimeOwner);let stderr=await open(paths.stderrLog,generation===0?"w":"a",384),pidFile,child,exitedEarly,childExit,presenterEnrollment;try{let supervisorArgs=["--socket",socket,...options.owner?["--owner-fd",String(OWNER_WATCH_FD)]:[],...options.presenterBootstrap?["--mcp-presenter-fd","4"]:[],...options.mcpPresenterEnforcement?["--mcp-presenter-enforcement"]:[],...options.hostArgs??[]],launch=testOptions?.spawn??testOptions?.launch?.(supervisorArgs)??defaultHostLaunch(supervisorArgs);if(child=spawnWithPrivateFds(spawn,launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:initialHostEnvironment({agentDir:options.agentDir,env:options.env,paths,instanceId,generation}),stdio:options.presenterBootstrap?["ignore","ignore",stderr.fd,options.owner?"pipe":"ignore","pipe"]:options.owner?["ignore","ignore",stderr.fd,"pipe"]:["ignore","ignore",stderr.fd]}),options.presenterBootstrap&&(presenterEnrollment=relayPresenterBootstrap(options.presenterBootstrap,child,{kind:"initial",predecessorHostInstance:null})),childExit=new Promise(resolveExit=>{child.once("exit",(code,signal)=>{exitedEarly={code,signal},resolveExit(exitedEarly)})}),options.owner&&keepOwnerPipe(child),child.pid===void 0)throw new Error("failed to spawn RPC socket host");let probe=testOptions?.readProcessStartTime??readProcessStartTime,observedStartTime=await Promise.race([waitForStartTime(child.pid,1e4,probe),childExit.then(()=>{throw new Error("RPC socket host exited before its start time could be read")})]),unhurriedProbe=testOptions?.readProcessStartTime?testOptions.readProcessStartTime:pid=>readProcessStartTime(pid,process.platform,15e3),processStartTime=observedStartTime??await unhurriedProbe(child.pid).catch(()=>{});pidFile={pid:child.pid,processStartTime:processStartTime??null},await testOptions?.beforePidFileWrite?.(),await writeHostRegistration(paths,{record:pidFile,socket,instanceId,generation,launchProfileId:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd()).profile_id,build:engineBuildIdentity()}),child.unref()}catch(error){let exitedBeforeCleanup=exitedEarly;if(!exitedBeforeCleanup&&child?.pid!==void 0&&childExit&&await stopUnregisteredStart(child,childExit,stopTarget("start_failed")),!exitedBeforeCleanup)throw await clearHostRegistration(paths),error;let diagnostic2=await appendStderr(paths,`RPC socket host exited with code ${exitedBeforeCleanup.code??"null"}${exitedBeforeCleanup.signal?` (${exitedBeforeCleanup.signal})`:""} before answering get_protocol_info`);throw await clearHostRegistration(paths),new Error(diagnostic2)}finally{await stderr.close()}let readinessTimeoutMs=testOptions?.readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS,result=await pollProtocolInfo(socket,readinessTimeoutMs,isCompatible,childExit);if(result.ready)return await presenterEnrollment,{pid:pidFile.pid,socket,reused:!1,release:result.hold.release};await testOptions?.beforeReadinessTeardown?.();let stopFailure=await stopSpawnedChild(child,childExit,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS,stopTarget("readiness_timeout")).then(()=>{},error=>error instanceof Error?error.message:String(error)),message=result.protocol?`RPC socket host answered get_protocol_info with protocolVersion ${result.protocol.protocolVersion}, serverVersion ${result.protocol.serverVersion} and capabilities ${JSON.stringify(result.protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`:result.exited?`RPC socket host exited with code ${result.exited.code??"null"}${result.exited.signal?` (${result.exited.signal})`:""} before answering get_protocol_info`:`spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`,diagnostic=await appendStderr(paths,stopFailure===void 0?message:`${message} (teardown also reported: ${stopFailure})`);throw await clearHostRegistration(paths),new Error(diagnostic)}async function stopUnregisteredStart(child,childExit,target){let pid=child.pid,running=()=>child.exitCode===null&&child.signalCode===null;if(pid===void 0||!running())return;let announced=await announceStop(target,pid);try{signalPid(pid,"SIGTERM")}catch{}if(await Promise.race([childExit,delay(2e3)]),!running())return;try{signalPid(pid,"SIGKILL")}catch{}await Promise.race([childExit.then(()=>!0),delay(SIGKILL_GRACE_MS).then(()=>!1)])&&await recordEscalation(target,announced)}async function appendStderr(paths,message){try{let stderr=(await readFile2(paths.stderrLog,"utf8")).trim();return stderr?`${message}
|
|
3
3
|
${stderr}`:message}catch(error){if(isNodeErrorCode(error,"ENOENT"))return message;throw error}}import{appendFile}from"node:fs/promises";import{basename as basename2,join as join4}from"node:path";import{readFile as readFile3,rename,writeFile}from"node:fs/promises";import{join as join3}from"node:path";var GC_SKIP_INITIAL_BACKOFF_MS=10*6e4,GC_SKIP_MAX_BACKOFF_MS=1440*6e4,skipEntrySchema=external_exports.object({skipUntil:external_exports.number(),backoffMs:external_exports.number()}),markerSchema2=external_exports.object({completedAt:external_exports.number(),cursor:external_exports.string().nullable(),examined:external_exports.number(),removed:external_exports.number(),stoppedBy:external_exports.enum(["time","count","exhausted"]),skip:external_exports.record(external_exports.string(),skipEntrySchema)});function hostGcPassMarkerPath(agentDir){return join3(agentDir,"rpc-host-daemon","gc-last-run.json")}function parseHostGcPassMarker(text){try{let parsed=markerSchema2.safeParse(JSON.parse(text));return parsed.success?parsed.data:void 0}catch(error){if(error instanceof SyntaxError)return;throw error}}async function readHostGcPassMarker(agentDir){let text=await readFile3(hostGcPassMarkerPath(agentDir),"utf8").catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});return text===void 0?void 0:parseHostGcPassMarker(text)}async function writeHostGcPassMarker(agentDir,marker){let path2=hostGcPassMarkerPath(agentDir),staged=`${path2}.${process.pid}.tmp`;await writeFile(staged,`${JSON.stringify(marker)}
|
|
4
4
|
`,{mode:384}),await rename(staged,path2)}function nextSkip(previous,now){let backoffMs=previous===void 0?GC_SKIP_INITIAL_BACKOFF_MS:Math.min(previous.backoffMs*2,GC_SKIP_MAX_BACKOFF_MS);return{skipUntil:now+backoffMs,backoffMs}}var passesRunning=new Map;function opportunisticHostGcRunning(agentDir){return passesRunning.has(agentDir)}function trackOpportunisticHostGc(agentDir,pass){passesRunning.set(agentDir,pass),pass.finally(()=>{passesRunning.get(agentDir)===pass&&passesRunning.delete(agentDir)})}var OPPORTUNISTIC_GC_BUDGET={budgetMs:1500,maxEndpoints:32,minIntervalMs:3e5};async function gcHostEndpointsOpportunistically(options){let now=options.now??Date.now,budgetMs=options.budgetMs??OPPORTUNISTIC_GC_BUDGET.budgetMs,maxEndpoints=options.maxEndpoints??OPPORTUNISTIC_GC_BUDGET.maxEndpoints,minIntervalMs=options.minIntervalMs??OPPORTUNISTIC_GC_BUDGET.minIntervalMs,previous=await readHostGcPassMarker(options.agentDir),startedAt=now();if(previous!==void 0&&startedAt-previous.completedAt<minIntervalMs)return{ran:!1};process.platform!=="win32"&&await gcRpcPublicKeys(options.agentDir,{deadline:startedAt+budgetMs,maxRecords:maxEndpoints});let candidates=await gcCandidates(options),present=new Set(candidates.map(endpoint=>endpoint.name)),skip={};for(let[name,entry]of Object.entries(previous?.skip??{}))present.has(name)&&(skip[name]=entry);let cursor=previous?.cursor??null,examined=0,removed=0,stoppedBy="exhausted";for(let endpoint of rotateAfter(candidates,cursor)){if((skip[endpoint.name]?.skipUntil??0)>now())continue;if(examined>=maxEndpoints){stoppedBy="count";break}if(now()-startedAt>=budgetMs){stoppedBy="time";break}examined+=1,cursor=endpoint.name;let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,{staleEngine:{}}).catch(()=>({removed:!1}));"stopped"in outcome?delete skip[endpoint.name]:outcome.removed?(removed+=1,delete skip[endpoint.name]):skip[endpoint.name]=nextSkip(skip[endpoint.name],now())}let marker={completedAt:now(),cursor,examined,removed,stoppedBy,skip};return await writeHostGcPassMarker(options.agentDir,marker),{ran:!0,marker}}function scheduleOpportunisticHostGc(options){if(opportunisticHostGcRunning(options.agentDir))return;let pass=new Promise(resolve6=>{setImmediate(()=>{gcHostEndpointsOpportunistically(options).then(()=>{},error=>recordPassFailure(options.agentDir,error)).finally(resolve6)}).unref()});trackOpportunisticHostGc(options.agentDir,pass)}async function gcCandidates(options){let targetName=basename2(createHostDaemonPaths({socket:options.exclude,agentDir:options.agentDir}).dir),candidates=[];for(let endpoint of await listHostEndpoints(options.agentDir)){let name=basename2(endpoint.dir);endpoint.socket===null||name===targetName||sameEndpoint(endpoint.socket,options.exclude)||candidates.push({...endpoint,socket:endpoint.socket,name})}return candidates}function rotateAfter(endpoints,cursor){if(cursor===null)return endpoints;let start=endpoints.findIndex(endpoint=>endpoint.name>cursor);return start<=0?endpoints:[...endpoints.slice(start),...endpoints.slice(0,start)]}async function recordPassFailure(agentDir,error){let line=`${new Date().toISOString()} gc pass failed: ${error instanceof Error?error.message:String(error)}
|
|
5
5
|
`;await appendFile(join4(agentDir,"rpc-host-daemon","gc-pass.log"),line,{mode:384}).catch(logError=>{logError instanceof Error&&"code"in logError&&logError.code==="ENOENT"||process.emitWarning(`host gc pass failed and could not be recorded: ${String(logError)}`)})}import{realpath as realpath2}from"node:fs/promises";import{basename as basename3,dirname as dirname3,resolve as resolve3}from"node:path";async function foreignAgentDirRefusal(socket,callerAgentDir,host){let hostAgentDir=host.agentDir??await layoutAgentDir(socket);if(hostAgentDir===void 0)return;let detail=await agentDirMismatch(socket,callerAgentDir,hostAgentDir);return detail===void 0?void 0:{action:"refuse",reason:"foreign_agent_dir",upgradeable:!1,detail}}async function agentDirMismatch(socket,callerAgentDir,hostAgentDir){let[ours,theirs]=await Promise.all([canonicalDirectory(callerAgentDir),canonicalDirectory(hostAgentDir)]);if(theirs!==ours)return`${socket} is served by the host of agent dir ${theirs}, and this client's agent dir is ${ours}; a host is only replaced by a client of its own agent dir - run with that agent dir to upgrade it, or use a socket of your own`}async function layoutAgentDir(socket){let rpcDirectory=dirname3(socket);if(basename3(socket)!=="rpc.sock"||basename3(rpcDirectory)!=="rpc")return;let agentDir=dirname3(rpcDirectory),paths=createHostDaemonPaths({socket,agentDir});return await provenOwner(await readHostRegistration(paths),socket)===void 0?void 0:agentDir}async function canonicalDirectory(path2){return realpath2(path2).catch(()=>resolve3(path2))}import{spawn as spawn2}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{open as open2,rm,writeFile as writeFile2}from"node:fs/promises";var DEFAULT_HANDOFF_READINESS_MS=3e4,SUCCESSOR_EXIT_WAIT_MS=5e3,SUCCESSOR_START_BUDGET_MS=1e4+DEFAULT_HANDOFF_READINESS_MS+2e3+SUCCESSOR_EXIT_WAIT_MS;async function startSuccessor(context){let{options,paths,host,owner,drainGate}=context,generation=(host.generation??0)+1,instanceId=randomUUID2(),bindSocket=generationBindPath(options.socket,generation);if(Buffer.byteLength(bindSocket)>MAX_SOCKET_PATH_BYTES)return{action:"refuse",reason:"socket_path_too_long",upgradeable:!0,detail:bindSocket};let replaced=await statSocketIdentity(options.socket);if(!replaced)return{action:"refuse",reason:"socket_replaced",upgradeable:!0};let running=await readHostSettings(paths),lifetimeOwner=host.instanceId?await readHostOwner(generationPaths(paths,host.instanceId).dir):null,inheritOwnerPipe=lifetimeOwner?.pid===process.pid&&sameHostOwner(lifetimeOwner,await callerHostOwner()),bootSettings=await readFileOrUndefined(paths.settingsFile);await writeHostSettings(paths,{socket:options.socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??running?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??running?.idleExitMs??9e5,generation,instanceId});let child,exited;try{await writeHostOwner(generationPaths(paths,instanceId).dir,lifetimeOwner??null),await options._test?.beforeSpawn?.();let argv=["--socket",options.socket,"--bind",bindSocket,"--replace",`${replaced.dev}:${replaced.ino}`,...inheritOwnerPipe?["--owner-fd",String(OWNER_WATCH_FD)]:[],...options.presenterBootstrap?["--mcp-presenter-fd","4"]:[],...options.mcpPresenterEnforcement||host.capabilities.includes("mcp_form_presenter_v1")?["--mcp-presenter-enforcement"]:[],...options.hostArgs??[]],launch=(options._test?.launch??options.launch)?.(argv)??defaultHostLaunch(argv),stderr=await open2(paths.stderrLog,"a",384),spawned=spawnWithPrivateFds(spawn2,launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:successorHostEnvironment({agentDir:options.agentDir,env:options.env,expectedRuntimeBuildId:options.expectedRuntimeBuildId,paths,generation,instanceId}),stdio:options.presenterBootstrap?["ignore","ignore",stderr.fd,inheritOwnerPipe?"pipe":"ignore","pipe"]:inheritOwnerPipe?["ignore","ignore",stderr.fd,"pipe"]:["ignore","ignore",stderr.fd]}),presenterEnrollment=options.presenterBootstrap?relayPresenterBootstrap(options.presenterBootstrap,spawned,{kind:"replacement",predecessorHostInstance:host.instanceId}):void 0;if(child=spawned,exited=new Promise(resolve6=>spawned.once("exit",()=>resolve6())),await stderr.close(),inheritOwnerPipe&&keepOwnerPipe(spawned),child.pid===void 0)throw new Error("failed to spawn the successor generation");let processStartTime=await waitForStartTime(child.pid,1e4).catch(()=>{})??null,registration={record:{pid:child.pid,processStartTime},socket:options.socket,instanceId,generation,launchProfileId:hostLaunchProfile(["--mode","rpc","--multi-session",...options.hostArgs??[]],process.cwd()).profile_id};await writeGenerationRecord(paths,registration),await options._test?.afterSpawn?.(child.pid);let answer2=await awaitSuccessor(options,host,exited);if(!answer2){let reason=await abortReason(options.socket,replaced),cleanupFailure=await abandonSuccessor({child,exited,paths,instanceId,bootSettings,reason:"successor_readiness_timeout"});return{action:"refuse",reason,upgradeable:!0,...cleanupFailure&&{detail:cleanupFailure}}}return await options._test?.beforeRegistration?.(),await writeHostRegistration(paths,{...registration,...successorBuild(answer2)}),await presenterEnrollment,child.unref(),owner!==void 0&&(drainGate===void 0||await drainGate())&&signalGeneration(owner.pid,"SIGUSR1"),{action:"handoff",pid:child.pid,socket:options.socket,generation:answer2.generation??generation,instanceId:answer2.instanceId??""}}catch(cause){let cleanupFailure=await abandonSuccessor({child,exited,paths,instanceId,bootSettings,reason:"successor_start_failed"}),detail=cause instanceof Error?cause.message:String(cause);return{action:"refuse",reason:"successor_unavailable",upgradeable:!0,detail:cleanupFailure?`${detail}; ${cleanupFailure}`:detail}}}async function abandonSuccessor(context){let{child,exited,paths,instanceId,bootSettings}=context,target={daemonDir:paths.dir,generation:generationPaths(paths,instanceId),instanceId,sender:{pid:process.pid,kind:"successor"},reason:context.reason},killed=child?.pid!==void 0&&child.exitCode===null&&child.signalCode===null?await announceStop(target,child.pid):void 0;killed!==void 0&&child?.pid!==void 0&&signalPid(child.pid,"SIGKILL");try{bootSettings===void 0?await rm(paths.settingsFile,{force:!0}):await writeFile2(paths.settingsFile,bootSettings,{mode:HOST_STATE_FILE_MODE}),child?.pid===void 0?await rm(generationPaths(paths,instanceId).dir,{recursive:!0,force:!0}):exited!==void 0&&await exitedWithin(exited,SUCCESSOR_EXIT_WAIT_MS)&&(killed!==void 0&&await recordEscalation(target,killed),await releaseGeneration(paths,{instanceId,pid:child.pid}));return}catch(cause){return`successor cleanup failed: ${cause instanceof Error?cause.message:String(cause)}`}}async function exitedWithin(exited,ms){let timer,timedOut=new Promise(resolve6=>{timer=setTimeout(()=>resolve6(!1),ms)});try{return await Promise.race([exited.then(()=>!0),timedOut])}finally{clearTimeout(timer)}}function successorBuild(answer2){return answer2.engineVersion===void 0||answer2.engineOrdinal===void 0?{}:{build:{text:answer2.engineVersion,ordinal:answer2.engineOrdinal}}}async function awaitSuccessor(options,previous,exited){let deadline=Date.now()+(options._test?.readinessTimeoutMs??DEFAULT_HANDOFF_READINESS_MS),childGone=!1;for(exited.then(()=>{childGone=!0});Date.now()<=deadline;){let answer2=await probeProtocolInfo(options.socket,2e3);if(answer2&&answer2.instanceId!==void 0&&answer2.instanceId!==previous.instanceId)return answer2;if(childGone)return;await delay3(50)}}async function abortReason(socket,replaced){let current=await statSocketIdentity(socket).catch(()=>{});return current===void 0||current.dev!==replaced.dev||current.ino!==replaced.ino?"socket_replaced":"successor_unavailable"}function delay3(ms){return new Promise(resolve6=>setTimeout(resolve6,ms))}var SESSION_COUNT_TIMEOUT_MS=1e4;async function handoffUnregisteredHost(options,paths,host){let counted=await holdSessionCount(options.socket,SESSION_COUNT_TIMEOUT_MS);try{let legacy=await provenLegacyOwner(paths,options.socket),sessions=counted?.sessions;if(sessions!==0)return legacy!==void 0?{action:"refuse",reason:"legacy_host",upgradeable:!0,detail:busyLegacyHostDetail(legacy.pid,options.socket,sessions)}:{action:"refuse",reason:"unknown_owner",upgradeable:!0,detail:`${options.socket} has no provable owner and holds ${describeSessions(sessions)}; it is never signalled - let that work finish, then retry`};let result=await startSuccessor({options,paths,host,owner:legacy,drainGate:async()=>await counted?.recount(SESSION_COUNT_TIMEOUT_MS)===0});return result.action==="handoff"&&legacy===void 0&&warnUnsignalledPredecessor(options.socket,host),result}finally{counted?.close()}}function warnUnsignalledPredecessor(socket,host){process.stderr.write(`generation handoff: no provable owner for ${socket}; the host it replaced (instance ${host.instanceId??"unknown"}, engine ${host.engineVersion??"unknown"}) listed 0 sessions and was not signalled; it drains itself on losing the public socket
|
|
@@ -0,0 +1,2 @@
|
|
|
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{peekProviderDiagnostic,siwcErrorForCode}from"./chunk-3SASTB6Y.js";var PROVIDER_DIAGNOSTIC_MAX_BYTES=512;function categoryForProviderCode(code){let siwc=siwcErrorForCode(code);if(siwc!==void 0)return siwc.category;switch(code){case"authentication_error":case"invalid_api_key":return"auth";case"rate_limit_error":case"rate_limit_exceeded":return"rate_limit";case"insufficient_quota":case"exceeded_current_quota_error":case"usage_limit_reached":case"usage_not_included":return"quota";case"context_length_exceeded":return"context_limit";case"invalid_request_error":return"invalid_request";case"overloaded_error":case"api_error":case"timeout_error":return"provider_unavailable";case"billing_error":case"permission_error":case"not_found_error":return"unknown";default:return}}var TLS_CHAIN_VERIFICATION_CODES=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_UNTRUSTED"]);function isTlsChainVerificationCode(code){return TLS_CHAIN_VERIFICATION_CODES.has(code)}function categoryForTransportCode(code){switch(code){case"ECONNRESET":case"ECONNREFUSED":case"ETIMEDOUT":case"ENOTFOUND":case"EAI_AGAIN":case"EPIPE":case"UND_ERR_SOCKET":case"UND_ERR_CONNECT_TIMEOUT":case"UND_ERR_HEADERS_TIMEOUT":case"UND_ERR_BODY_TIMEOUT":case"UND_ERR_CLOSED":case"APIConnectionError":case"APIConnectionTimeoutError":return"network";default:return isTlsChainVerificationCode(code)?"network":void 0}}function isProviderCodeStatusCompatible(code,status){let siwc=siwcErrorForCode(code);if(siwc!==void 0)return status===siwc.status;switch(code){case"authentication_error":case"invalid_api_key":return status===401;case"rate_limit_error":case"rate_limit_exceeded":case"insufficient_quota":case"exceeded_current_quota_error":case"usage_limit_reached":case"usage_not_included":return status===429;case"context_length_exceeded":case"invalid_request_error":return status===400;case"overloaded_error":case"api_error":case"timeout_error":return status>=500&&status<=599;case"billing_error":return status===402;case"permission_error":return status===403;case"not_found_error":return status===404;default:return!1}}var OPAQUE_PROVIDER_CODE=/^[a-z]+(?:[_.][a-z]+)*$/,OPAQUE_PROVIDER_CODE_MAX_LENGTH=64;function isOpaqueProviderCode(code){return code.length<=OPAQUE_PROVIDER_CODE_MAX_LENGTH&&OPAQUE_PROVIDER_CODE.test(code)&&categoryForProviderCode(code)===void 0}function isProviderDiagnosticResetsAt(value){return typeof value=="number"&&Number.isInteger(value)&&value>9466848e5&&value<41024448e5}function categoryForProviderStatus(status){return status===401?"auth":status===400?"invalid_request":status>=500&&status<=599?"provider_unavailable":"unknown"}function isProviderDiagnosticStatus(value){return typeof value=="number"&&Number.isInteger(value)&&value>=400&&value<=599}function isProviderDiagnosticCategory(value){switch(value){case"auth":case"rate_limit":case"quota":case"context_limit":case"invalid_request":case"provider_unavailable":case"network":case"unknown":return!0;default:return!1}}function buildProviderDiagnostic(input){let diagnostic={category:input.category,evidence:input.evidence};return input.httpStatus!==void 0&&(diagnostic.httpStatus=input.httpStatus),input.code!==void 0&&(diagnostic.code=input.code),input.route!==void 0&&(diagnostic.route=input.route),input.resetsAt!==void 0&&(input.category==="quota"||input.category==="rate_limit")&&(diagnostic.resetsAt=input.resetsAt),new TextEncoder().encode(JSON.stringify(diagnostic)).length<=PROVIDER_DIAGNOSTIC_MAX_BYTES?diagnostic:void 0}function classifyProviderFailure(facts){let statusSupplied=facts.status!==void 0&&facts.status!==null;if(statusSupplied&&!isProviderDiagnosticStatus(facts.status))return;let status=statusSupplied&&isProviderDiagnosticStatus(facts.status)?facts.status:void 0,category=facts.code===void 0?void 0:categoryForProviderCode(facts.code);if(facts.code!==void 0&&category!==void 0)return status!==void 0&&!isProviderCodeStatusCompatible(facts.code,status)?void 0:buildProviderDiagnostic({category,...status===void 0?{}:{httpStatus:status},code:facts.code,evidence:"structured_code"});if(status!==void 0)return buildProviderDiagnostic({category:categoryForProviderStatus(status),httpStatus:status,evidence:"structured_status"})}function readField(value,key){return Reflect.get(value,key)}function sanitizeProviderDiagnostic(value){try{if(typeof value!="object"||value===null||Array.isArray(value))return;let category=readField(value,"category"),evidence=readField(value,"evidence"),httpStatus=readField(value,"httpStatus"),code=readField(value,"code"),resetsAt=readField(value,"resetsAt"),route=readField(value,"route");if(route!==void 0&&route!=="siwc")return;let routed=route==="siwc"?{route}:{};if(!isProviderDiagnosticCategory(category)||httpStatus!==void 0&&!isProviderDiagnosticStatus(httpStatus)||resetsAt!==void 0&&!isProviderDiagnosticResetsAt(resetsAt))return;let reset=resetsAt===void 0?{}:{resetsAt};return evidence==="structured_status"?code!==void 0||!isProviderDiagnosticStatus(httpStatus)||category!==categoryForProviderStatus(httpStatus)?void 0:buildProviderDiagnostic({category,httpStatus,evidence,...reset,...routed}):evidence==="structured_transport"?httpStatus!==void 0||typeof code!="string"||categoryForTransportCode(code)!==category?void 0:buildProviderDiagnostic({category,code,evidence}):evidence!=="structured_code"||typeof code!="string"?void 0:isOpaqueProviderCode(code)?category!=="unknown"||httpStatus!==void 0?void 0:buildProviderDiagnostic({category,code,evidence}):categoryForProviderCode(code)!==category||httpStatus!==void 0&&!isProviderCodeStatusCompatible(code,httpStatus)?void 0:buildProviderDiagnostic({category,...httpStatus===void 0?{}:{httpStatus},code,evidence,...reset,...routed})}catch{return}}function readProviderDiagnostic(error){return sanitizeProviderDiagnostic(peekProviderDiagnostic(error))}export{PROVIDER_DIAGNOSTIC_MAX_BYTES,categoryForProviderCode,isTlsChainVerificationCode,categoryForTransportCode,isOpaqueProviderCode,isProviderDiagnosticResetsAt,isProviderDiagnosticStatus,buildProviderDiagnostic,classifyProviderFailure,sanitizeProviderDiagnostic,readProviderDiagnostic};
|
|
@@ -1,4 +1,4 @@
|
|
|
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{theme}from"./chunk-
|
|
2
|
+
import{theme}from"./chunk-WCRNJYHO.js";import{Container,Input,Spacer,Text,getKeybindings,nextRenderRevision}from"./chunk-D2ROBVZ4.js";var DynamicBorder=class{constructor(color=str=>theme.fg("border",str)){this.revision=nextRenderRevision(),this.color=color}invalidate(){this.revision=nextRenderRevision()}getRenderRevision(){return this.revision}render(width){return[this.color("\u2500".repeat(Math.max(1,width)))]}};var KEY_DISPLAY_ALIASES=new Map([["escape","esc"]]);function formatKeyPart(part,options){let lowerPart=part.toLowerCase(),displayPart=KEY_DISPLAY_ALIASES.get(lowerPart)??(process.platform==="darwin"&&lowerPart==="alt"?"option":part);return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}var stdoutTakeoverState,stderrTakeoverState,visibleStderrObservation;var rawStdoutWriteTail=Promise.resolve();function getRawStdoutWrite(){return stdoutTakeoverState?stdoutTakeoverState.rawStdoutWrite:process.stdout.write.bind(process.stdout)}async function writeRawStdoutChunk(text){for(;;)try{await new Promise((resolve,reject)=>{try{getRawStdoutWrite()(text,error=>{error?reject(error):resolve()})}catch(error){reject(error instanceof Error?error:new Error(String(error)))}});return}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),code=writeError.code;if(code!=="ENOBUFS"&&code!=="EAGAIN"&&code!=="EWOULDBLOCK")throw writeError;await new Promise(resolve=>setTimeout(resolve,10))}}function takeOverStdout(){if(stdoutTakeoverState)return;let rawStdoutWrite=process.stdout.write.bind(process.stdout),rawStderrWrite=process.stderr.write.bind(process.stderr),originalStdoutWrite=process.stdout.write;process.stdout.write=((chunk,encodingOrCallback,callback)=>typeof encodingOrCallback=="function"?rawStderrWrite(String(chunk),encodingOrCallback):rawStderrWrite(String(chunk),callback)),stdoutTakeoverState={rawStdoutWrite,rawStderrWrite,originalStdoutWrite}}function restoreStdout(){stdoutTakeoverState&&(process.stdout.write=stdoutTakeoverState.originalStdoutWrite,stdoutTakeoverState=void 0)}function stdioChunkToString(chunk,encoding){return typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding)}function normalizeThrownError(error){return error instanceof Error?error:new Error(String(error))}function writeOriginalStderr(state,text){text.length!==0&&state.originalStderrWrite.call(process.stderr,text)}function observeVisibleStderrWrites(listener){if(!visibleStderrObservation){let original=stderrTakeoverState?.originalStderrWrite??process.stderr.write,listeners=new Set,writer=function(...args){for(let notify2 of listeners)notify2();return Reflect.apply(original,this,args)};visibleStderrObservation={original,writer,listeners},stderrTakeoverState?stderrTakeoverState.originalStderrWrite=writer:process.stderr.write=writer}let observation=visibleStderrObservation,notify=()=>listener();return observation.listeners.add(notify),()=>{!observation.listeners.delete(notify)||observation.listeners.size>0||(stderrTakeoverState?.originalStderrWrite===observation.writer&&(stderrTakeoverState.originalStderrWrite=observation.original),process.stderr.write===observation.writer&&(process.stderr.write=observation.original),visibleStderrObservation=void 0)}}function takeOverStderr(onHiddenDiagnostic,formatHiddenDiagnosticFallback){if(stderrTakeoverState)return;let originalStderrWrite=process.stderr.write;process.stderr.write=((chunk,encodingOrCallback,callback)=>{let text=stdioChunkToString(chunk,typeof encodingOrCallback=="string"?encodingOrCallback:void 0);try{stderrTakeoverState?.onHiddenDiagnostic?.(text)}catch(error){let state=stderrTakeoverState;if(state){let fallbackText=state.formatHiddenDiagnosticFallback?.(text)??text;writeOriginalStderr(state,fallbackText)}let writeError=normalizeThrownError(error);return typeof encodingOrCallback=="function"?encodingOrCallback(writeError):callback?.(writeError),!1}return typeof encodingOrCallback=="function"?encodingOrCallback(null):callback?.(null),!0}),stderrTakeoverState={formatHiddenDiagnosticFallback,originalStderrWrite,onHiddenDiagnostic}}function restoreStderr(){stderrTakeoverState&&(process.stderr.write=stderrTakeoverState.originalStderrWrite,stderrTakeoverState=void 0)}function isStdoutTakenOver(){return stdoutTakeoverState!==void 0}function writeRawStdout(text){text.length!==0&&(rawStdoutWriteTail=rawStdoutWriteTail.then(()=>writeRawStdoutChunk(text)),rawStdoutWriteTail.catch(()=>{process.exit(1)}))}async function waitForRawStdoutBackpressure(){for(;;){let tail=rawStdoutWriteTail;if(await tail,tail===rawStdoutWriteTail)return}}async function flushRawStdout(){await waitForRawStdoutBackpressure(),await writeRawStdoutChunk("")}var SecretInputUnavailableError=class extends Error{constructor(reason){super("This client cannot collect a secret; use the TUI or the host's settings route."),this.code="secret_input_unavailable",this.name="SecretInputUnavailableError",this.reason=reason}};function resolveSecretInputTimeout(opts){let timeout=opts?.timeout??18e5;if(!Number.isFinite(timeout)||timeout<=0)throw new Error("Invalid secret input timeout");return timeout}function armSecretInputDeadline(deadline,expire){let timer,check=()=>{let remaining=deadline-Date.now();remaining<=0?expire():timer=setTimeout(check,Math.min(remaining,2147483647))};return timer=setTimeout(check,Math.max(0,Math.min(deadline-Date.now(),2**31-1))),()=>clearTimeout(timer)}function isSecretInputValue(value){return!/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value)}var CountdownTimer=class{constructor(timeoutMs,tui,onTick,onExpire){this.tui=tui,this.onTick=onTick,this.onExpire=onExpire,this.remainingSeconds=Math.ceil(timeoutMs/1e3),this.onTick(this.remainingSeconds),this.intervalId=setInterval(()=>{this.remainingSeconds--,this.onTick(this.remainingSeconds),this.tui?.requestRender(),this.remainingSeconds<=0&&(this.dispose(),this.onExpire())},1e3)}dispose(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}};var ExtensionInputComponent=class extends Container{get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}constructor(title,_placeholder,onSubmit,onCancel,opts){if(super(),this._focused=!1,this.secret=opts?.secret===!0,this.onSubmitCallback=onSubmit,this.onCancelCallback=onCancel,this.baseTitle=title,this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.titleText=new Text(theme.fg("accent",title),1,0),this.addChild(this.titleText),opts?.description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("text",opts.description),1,0))),this.addChild(new Spacer(1)),this.secret){let deadline=opts?.deadlineAtMs??Date.now()+(opts?.timeout??18e5);this.secretTimer=armSecretInputDeadline(deadline,()=>this.onCancelCallback())}else opts?.timeout&&opts.timeout>0&&opts.tui&&(this.countdown=new CountdownTimer(opts.timeout,opts.tui,s=>this.titleText.setText(theme.fg("accent",`${this.baseTitle} (${s}s)`)),()=>this.onCancelCallback()));this.input=new Input({secret:this.secret,onInvalidInput:()=>this.titleText.setText(theme.fg("warning","Secret input must be a single line without control characters."))}),this.secret&&(this.input.onSubmit=value=>this.onSubmitCallback(value),this.input.onEscape=()=>this.onCancelCallback()),opts?.initialValue&&this.input.handleInput(opts.initialValue),this.addChild(this.input),this.addChild(new Spacer(1)),this.addChild(new Text(`${keyHint("tui.select.confirm","submit")} ${keyHint("tui.select.cancel","cancel")}`,1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}handleInput(keyData){if(this.secret){this.input.handleInput(keyData);return}let kb=getKeybindings();kb.matches(keyData,"tui.select.confirm")||keyData===`
|
|
3
3
|
`?this.onSubmitCallback(this.input.getValue()):kb.matches(keyData,"tui.select.cancel")?this.onCancelCallback():this.input.handleInput(keyData)}dispose(){this.countdown?.dispose(),this.secretTimer?.(),this.secret&&this.input.dispose(),this.onSubmitCallback=()=>{},this.onCancelCallback=()=>{}}};var ExtensionSelectorComponent=class _ExtensionSelectorComponent extends Container{static{this.DEFAULT_MAX_VISIBLE_OPTIONS=10}constructor(title,options,onSelect,onCancel,opts){super(),this.selectedIndex=0,this.answerSettled=!1,this.options=options,this.onSelectCallback=onSelect,this.onCancelCallback=onCancel,this.onToggleToolsExpanded=opts?.onToggleToolsExpanded,this.baseTitle=title,this.maxVisibleOptions=opts?.tui?Math.max(5,Math.floor(opts.tui.terminal.rows/2)):_ExtensionSelectorComponent.DEFAULT_MAX_VISIBLE_OPTIONS,this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.titleText=new Text(theme.fg("accent",theme.bold(title)),1,0),this.addChild(this.titleText),opts?.description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("text",opts.description),1,0))),this.addChild(new Spacer(1)),opts?.timeout&&opts.timeout>0&&opts.tui&&(this.countdown=new CountdownTimer(opts.timeout,opts.tui,s=>this.titleText.setText(theme.fg("accent",theme.bold(`${this.baseTitle} (${s}s)`))),()=>this.onCancelCallback())),this.listContainer=new Container,this.addChild(this.listContainer),this.addChild(new Spacer(1)),this.addChild(new Text(rawKeyHint("\u2191\u2193","navigate")+" "+keyHint("tui.select.confirm","select")+" "+keyHint("tui.select.cancel","cancel"),1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder),this.updateList()}updateList(){this.listContainer.clear();let count=this.options.length,startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisibleOptions/2),count-this.maxVisibleOptions)),endIndex=Math.min(startIndex+this.maxVisibleOptions,count);startIndex>0&&this.listContainer.addChild(new Text(theme.fg("muted",` \u2026 ${startIndex} more above`),1,0));for(let i=startIndex;i<endIndex;i++){let text=i===this.selectedIndex?theme.fg("accent","\u2192 ")+theme.fg("accent",this.options[i]):` ${theme.fg("text",this.options[i])}`;this.listContainer.addChild(new Text(text,1,0))}endIndex<count&&this.listContainer.addChild(new Text(theme.fg("muted",` \u2026 ${count-endIndex} more below`),1,0))}handleInput(keyData){if(this.answerSettled)return;let kb=getKeybindings();if(kb.matches(keyData,"app.tools.expand"))this.onToggleToolsExpanded?.();else if(kb.matches(keyData,"tui.select.up")||keyData==="k")this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList();else if(kb.matches(keyData,"tui.select.down")||keyData==="j")this.selectedIndex=Math.min(this.options.length-1,this.selectedIndex+1),this.updateList();else if(kb.matches(keyData,"tui.select.confirm")||keyData===`
|
|
4
4
|
`){let selected=this.options[this.selectedIndex];selected&&this.onSelectCallback(selected)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancelCallback()}dispose(){this.answerSettled=!0,this.countdown?.dispose()}};export{DynamicBorder,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint,takeOverStdout,restoreStdout,observeVisibleStderrWrites,takeOverStderr,restoreStderr,isStdoutTakenOver,writeRawStdout,waitForRawStdoutBackpressure,flushRawStdout,SecretInputUnavailableError,resolveSecretInputTimeout,armSecretInputDeadline,isSecretInputValue,CountdownTimer,ExtensionInputComponent,ExtensionSelectorComponent};
|
|
@@ -140,7 +140,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
140
140
|
`)}function extractUserMessageText(msg){if(msg.role!=="user")return"";let content=msg.content;return typeof content=="string"?content.trim():content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
141
141
|
`).trim()}function hasUserMessageImages(msg){return msg.role==="user"&&Array.isArray(msg.content)&&msg.content.some(item=>item.type==="image")}function buildCursorRootPromptContent(content){if(typeof content=="string"){let text=content.trim();return text?[{type:"text",text}]:[]}let parts=[];for(let item of content)if(item.type==="text"){let text=item.text.trim();text&&parts.push({type:"text",text})}else parts.push({type:"image",image:`data:${item.mimeType};base64,${item.data}`,mediaType:item.mimeType});return parts}function cursorUserContentKey(content){if(typeof content=="string")return content.trim();let hash=createHash("sha256");for(let item of content)hash.update(item.type),item.type==="text"?hash.update(item.text):(hash.update(item.mimeType),hash.update(item.data));return hash.digest("hex")}function buildCursorAssistantContent(msg){let content=[];for(let item of msg.content)item.type==="text"?item.text&&content.push({type:"text",text:item.text}):item.type==="toolCall"&&content.push({type:"tool-call",toolCallId:item.id,toolName:item.name,args:item.arguments});return content}function findLastUserMessageIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="user")return i;return-1}function buildRootPromptMessagesJson(messages,systemPromptIds,blobStore,activeUserMessageIndex=findLastUserMessageIndex(messages)){let entries=[...systemPromptIds],pushJson=obj=>{let bytes=new TextEncoder().encode(JSON.stringify(obj));entries.push(storeCursorBlob(blobStore,bytes))};for(let i=0;i<messages.length&&i!==activeUserMessageIndex;i++){let msg=messages[i];if(msg.role==="user"){let content=buildCursorRootPromptContent(msg.content);if(content.length===0)continue;pushJson({role:"user",content})}else if(msg.role==="assistant"){let content=buildCursorAssistantContent(msg);if(content.length===0)continue;pushJson({role:"assistant",content})}else msg.role==="toolResult"&&pushJson({role:"tool",id:msg.toolCallId,content:[{type:"tool-result",toolName:msg.toolName,toolCallId:msg.toolCallId,result:toolResultToText(msg),...msg.isError?{isError:!0}:{}}]})}return entries}function isPlainRecord(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isJsonValue(value){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isJsonValue);if(!isPlainRecord(value))return!1;for(let key in value)if(!isJsonValue(value[key]))return!1;return!0}function encodeCursorMcpArguments(toolCall){let encoded={};for(let name in toolCall.arguments){let value=toolCall.arguments[name];if(value!==void 0){if(!isJsonValue(value))throw new Error(`Cursor tool argument ${toolCall.name}.${name} is not JSON-serializable`);encoded[name]=toBinary(ValueSchema,fromJson(ValueSchema,value))}}return encoded}function createCursorMcpResult(result){return result.isError?create(McpToolResultSchema,{result:{case:"error",value:create(McpToolErrorSchema,{error:toolResultToText(result)})}}):create(McpToolResultSchema,{result:{case:"success",value:create(McpSuccessSchema,{content:result.content.map(item=>item.type==="text"?create(McpToolResultContentItemSchema,{content:{case:"text",value:create(McpTextContentSchema,{text:item.text})}}):create(McpToolResultContentItemSchema,{content:{case:"image",value:create(McpImageContentSchema,{data:Uint8Array.from(Uint8Array.from(atob(item.data),c=>c.charCodeAt(0))),mimeType:item.mimeType})}}))})}})}function createCursorToolCallStep(toolCall,result){let mcpCall=create(McpToolCallSchema,{args:create(McpArgsSchema,{name:toolCall.name,args:encodeCursorMcpArguments(toolCall),toolCallId:toolCall.id,providerIdentifier:"pi-agent",toolName:toolCall.name}),...result?{result:createCursorMcpResult(result)}:{}});return create(ConversationStepSchema,{message:{case:"toolCall",value:create(ToolCallSchema,{tool:{case:"mcpToolCall",value:mcpCall},toolCallId:toolCall.id})}})}function buildConversationTurns(messages,blobStore,activeUserMessageIndex=findLastUserMessageIndex(messages)){let turns=[],historyEnd=activeUserMessageIndex>=0?activeUserMessageIndex:messages.length,toolResults=new Map,pairedToolCallIds=new Set;for(let index=0;index<historyEnd;index++){let message=messages[index];if(message.role==="toolResult")toolResults.set(message.toolCallId,message);else if(message.role==="assistant")for(let item of message.content)item.type==="toolCall"&&pairedToolCallIds.add(item.id)}let i=0;for(;i<messages.length;){let msg=messages[i];if(msg.role!=="user"){i++;continue}if(i===activeUserMessageIndex)break;let userText=extractUserMessageText(msg);if(userText.length===0&&!hasUserMessageImages(msg)){i++;continue}let userMessage=createCursorUserMessage(msg.content,userText,deterministicUuid(`u:${turns.length}:${cursorUserContentKey(msg.content)}`)),userMessageBlobId=storeCursorBlob(blobStore,toBinary(UserMessageSchema,userMessage)),stepBlobIds=[];for(i++;i<messages.length&&messages[i].role!=="user";){let stepMsg=messages[i];if(stepMsg.role==="assistant")for(let item of stepMsg.content){let step;if(item.type==="text"){if(!item.text)continue;step=create(ConversationStepSchema,{message:{case:"assistantMessage",value:create(AssistantMessageSchema,{text:item.text})}})}else{if(item.type==="thinking")continue;if(item.type==="toolCall")step=createCursorToolCallStep(item,toolResults.get(item.id));else continue}stepBlobIds.push(storeCursorBlob(blobStore,toBinary(ConversationStepSchema,step)))}else if(stepMsg.role==="toolResult"&&!pairedToolCallIds.has(stepMsg.toolCallId)){let text=toolResultToText(stepMsg);if(text){let prefix=stepMsg.isError?"[Tool Error]":"[Tool Result]",step=create(ConversationStepSchema,{message:{case:"assistantMessage",value:create(AssistantMessageSchema,{text:`${prefix}
|
|
142
142
|
${text}`})}});stepBlobIds.push(storeCursorBlob(blobStore,toBinary(ConversationStepSchema,step)))}}i++}let agentTurn=create(AgentConversationTurnStructureSchema,{userMessage:userMessageBlobId,steps:stepBlobIds}),turn=create(ConversationTurnStructureSchema,{turn:{case:"agentConversationTurn",value:agentTurn}});turns.push(storeCursorBlob(blobStore,toBinary(ConversationTurnStructureSchema,turn)))}return turns}function createCursorUserMessage(content,text,messageId=randomUUID()){let images=typeof content=="string"?[]:extractImages(content);return create(UserMessageSchema,{text,messageId,...images.length>0?{selectedContext:create(SelectedContextSchema,{selectedImages:images})}:{}})}function extractImages(content){return content.filter(item=>item.type==="image").map(image=>create(SelectedImageSchema,{uuid:randomUUID(),mimeType:image.mimeType,dataOrBlobId:{case:"data",value:Uint8Array.from(atob(image.data),c=>c.charCodeAt(0))}}))}function measureCursorModelInputSerializedBytes(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){let blobStore=new Map,total=0;for(let blobId of buildRootPromptMessagesJson(messages,[],blobStore,activeUserMessageIndex))total+=readCursorBlob(blobStore,blobId).byteLength;return total}function measureCursorHistorySerializedBytes(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){return buildCursorHistoryWireBytesForTest(messages,activeUserMessageIndex).reduce((total,bytes)=>total+bytes.byteLength,0)}function buildCursorHistoryWireBytesForTest(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){let blobStore=new Map;return buildRootPromptMessagesJson(messages,[],blobStore,activeUserMessageIndex),buildConversationTurns(messages,blobStore,activeUserMessageIndex),[...blobStore.values()]}function piReadArgs(path,offset,limit){return limit!==void 0&&Math.floor(limit)<=0?null:{path,offset:offset!==void 0?Math.max(1,Math.floor(offset)):void 0,limit:limit!==void 0?Math.floor(limit):void 0}}function piLsPath(basePath){return basePath||"."}function piLimit(limit){return limit===void 0?void 0:Math.max(1,Math.floor(limit))}function piTimeout(timeout){return timeout!==void 0&&timeout>=0?timeout:void 0}function composeShellCommand(command,workingDirectory){return workingDirectory?`cd ${`'${workingDirectory.replace(/'/g,"'\\''")}'`} && { ${command}
|
|
143
|
-
}`:command}function omitUndefinedArgs(args){let out={};for(let key of Object.keys(args)){let value=args[key];value!==void 0&&(out[key]=value)}return out}var warmers=new Map;function registerPromptCacheWarmer(api,warmer){warmers.set(api,warmer)}function getPromptCacheWarmer(api){return warmers.get(api)}async function warmPromptCache(model,context,options={}){if(isOpenAIResponsesPromptCacheModel(model)){if((options.cacheRetention??model.cacheRetention)==="none")return{supported:!1};let warmer=getPromptCacheWarmer(model.api);if(warmer===void 0)return{supported:!1};let{usage,usageRaw:usageRaw2}=await warmer(model,context,options);return{supported:!0,usage:{input:usage.input,output:usage.output,cacheRead:usage.cacheRead,cacheWrite:usage.cacheWrite,cost:usage.cost},usageRaw:usageRaw2}}if(model.api!=="anthropic-messages"||!isAnthropicApiBaseUrl(model.baseUrl))return{supported:!1};let anthropicModel=model,[{default:Anthropic},{buildAnthropicWarmPromptCacheParams}]=await Promise.all([import("./sdk-3UTSBCRC.js"),import("./anthropic-messages-
|
|
143
|
+
}`:command}function omitUndefinedArgs(args){let out={};for(let key of Object.keys(args)){let value=args[key];value!==void 0&&(out[key]=value)}return out}var warmers=new Map;function registerPromptCacheWarmer(api,warmer){warmers.set(api,warmer)}function getPromptCacheWarmer(api){return warmers.get(api)}async function warmPromptCache(model,context,options={}){if(isOpenAIResponsesPromptCacheModel(model)){if((options.cacheRetention??model.cacheRetention)==="none")return{supported:!1};let warmer=getPromptCacheWarmer(model.api);if(warmer===void 0)return{supported:!1};let{usage,usageRaw:usageRaw2}=await warmer(model,context,options);return{supported:!0,usage:{input:usage.input,output:usage.output,cacheRead:usage.cacheRead,cacheWrite:usage.cacheWrite,cost:usage.cost},usageRaw:usageRaw2}}if(model.api!=="anthropic-messages"||!isAnthropicApiBaseUrl(model.baseUrl))return{supported:!1};let anthropicModel=model,[{default:Anthropic},{buildAnthropicWarmPromptCacheParams}]=await Promise.all([import("./sdk-3UTSBCRC.js"),import("./anthropic-messages-AFWQB3KN.js")]),headers=providerHeadersToRecord(options.headers),client=new Anthropic({apiKey:options.apiKey??null,baseURL:anthropicModel.baseUrl,dangerouslyAllowBrowser:!0,fetch:getAnthropicCompat(anthropicModel).supportsGzipRequestBody?withGzipRequestBodies(options.fetch):options.fetch,defaultHeaders:{...anthropicModel.headers,...headers}}),params=buildAnthropicWarmPromptCacheParams(anthropicModel,context,options),transformed=await options.onPayload?.(params,anthropicModel,{model:anthropicModel,headers});transformed!==void 0&&(params=transformed);let sanitized={...params};delete sanitized.stream,delete sanitized.thinking,delete sanitized.output_config,delete sanitized.tool_choice,sanitized.max_tokens=0;let usageRaw=(await client.beta.messages.create(sanitized,{maxRetries:0,...options.signal?{signal:options.signal}:{},...options.timeoutMs!==void 0?{timeout:options.timeoutMs}:{}})).usage;return{supported:!0,usage:{input:usageRaw.input_tokens,output:usageRaw.output_tokens,cacheRead:usageRaw.cache_read_input_tokens??0,cacheWrite:usageRaw.cache_creation_input_tokens??0},usageRaw}}var DEFAULT_API="faux",DEFAULT_PROVIDER="faux",DEFAULT_MODEL_ID="faux-1",DEFAULT_MODEL_NAME="Faux Model",DEFAULT_BASE_URL="http://localhost:0",DEFAULT_MIN_TOKEN_SIZE=3,DEFAULT_MAX_TOKEN_SIZE=5,DEFAULT_USAGE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function fauxText(text){return{type:"text",text}}function fauxThinking(thinking){return{type:"thinking",thinking}}function fauxToolCall(name,arguments_,options={}){return{type:"toolCall",id:options.id??randomId("tool"),name,arguments:arguments_}}function normalizeFauxAssistantContent(content){return typeof content=="string"?[fauxText(content)]:Array.isArray(content)?content:[content]}function fauxAssistantMessage(content,options={}){return{role:"assistant",content:normalizeFauxAssistantContent(content),api:DEFAULT_API,provider:DEFAULT_PROVIDER,model:DEFAULT_MODEL_ID,usage:DEFAULT_USAGE,stopReason:options.stopReason??"stop",...options.stopDetails===void 0?{}:{stopDetails:options.stopDetails},...options.deferred===void 0?{}:{deferred:options.deferred},...options.errorMessage===void 0?{}:{errorMessage:options.errorMessage},...options.abortSource===void 0?{}:{abortSource:options.abortSource},...options.responseId===void 0?{}:{responseId:options.responseId},timestamp:options.timestamp??Date.now()}}function estimateTokens(text){return Math.ceil(text.length/4)}function randomId(prefix){return`${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function cloneStreamOptionsForLog(options){if(options)return{...options}}function cloneToolForLog(tool){return{name:tool.name,description:tool.description,parameters:structuredClone(tool.parameters),...tool.freeform?{freeform:structuredClone(tool.freeform)}:{}}}function toLoggedContext(transcript){let systemPrompt=getCurrentSystemPrompt(transcript.messages),tools=getCurrentTools(transcript.messages);return{...systemPrompt?{systemPrompt}:{},messages:structuredClone(transcript.messages.filter(message=>message.role!=="system")),...tools.length>0?{tools:tools.map(cloneToolForLog)}:{},...transcript.activeToolNames?{activeToolNames:[...transcript.activeToolNames]}:{}}}function contentToText(content){return typeof content=="string"?content:content.map(block=>block.type==="text"?block.text:`[image:${block.mimeType}:${block.data.length}]`).join(`
|
|
144
144
|
`)}function assistantContentToText(content){return content.map(block=>block.type==="text"?block.text:block.type==="thinking"?block.thinking:block.type==="providerNative"?"":`${block.name}:${JSON.stringify(block.arguments)}`).join(`
|
|
145
145
|
`)}function toolResultToText2(message){return[message.toolName,...message.content.map(block=>contentToText([block]))].join(`
|
|
146
146
|
`)}function messageToText(message){return message.role==="system"?[getSystemMessageText(message),...message.toolsRemoved?.map(tool=>`tool-:${JSON.stringify(tool)}`)??[],...message.toolsAdded?.map(tool=>`tool+:${JSON.stringify(tool)}`)??[]].filter(part=>part.length>0).join(`
|