@code-yeongyu/senpi 2026.10.16-2 → 2026.10.16-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundle/chunks/chunk-74YFRVGQ.js +2 -0
  3. package/dist/bundle/chunks/{chunk-KRAABTZY.js → chunk-AVALXFDW.js} +2 -2
  4. package/dist/bundle/chunks/{chunk-V5JFWWGJ.js → chunk-FMYLLJBQ.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-VY43SSYL.js → chunk-HJPX7PBL.js} +30 -27
  6. package/dist/bundle/chunks/{chunk-QQUHMCOM.js → chunk-I5ZJEXTM.js} +1 -1
  7. package/dist/bundle/chunks/chunk-K2EVQGGT.js +31 -0
  8. package/dist/bundle/chunks/chunk-WL4Y6XN6.js +18 -0
  9. package/dist/bundle/chunks/{chunk-Q7RD3NOC.js → chunk-X5VCHHXR.js} +1 -1
  10. package/dist/bundle/chunks/{cli-main-JDL52ADK.js → cli-main-JVPFJGP5.js} +1 -1
  11. package/dist/bundle/chunks/google-generative-ai-AI6PAUPA.js +2 -0
  12. package/dist/bundle/chunks/google-vertex-USNRIFF7.js +2 -0
  13. package/dist/bundle/chunks/google-vertex-adc-JZURL4XM.js +2 -0
  14. package/dist/bundle/chunks/{interactive-mode-7IM7YJYH.js → interactive-mode-BROZRY34.js} +1 -1
  15. package/dist/bundle/chunks/{multi-session-host-3MEEUMYU.js → multi-session-host-SMQR5SCJ.js} +2 -2
  16. package/dist/bundle/chunks/{openai-codex-responses-T26WW2RE.js → openai-codex-responses-NV27Q6VV.js} +1 -1
  17. package/dist/bundle/chunks/{package-manager-cli-UCHXVBQ2.js → package-manager-cli-2QFJY2AS.js} +1 -1
  18. package/dist/bundle/chunks/{rpc-mode-D4BJKWFL.js → rpc-mode-Z45T3NZO.js} +1 -1
  19. package/dist/bundle/chunks/{session-control-endpoint-NBSRSAJS.js → session-control-endpoint-H7FFWF2A.js} +1 -1
  20. package/dist/bundle/chunks/{session-picker-6TSBGWOA.js → session-picker-2O2BNBVE.js} +1 -1
  21. package/dist/bundle/chunks/session-worker.js +36 -33
  22. package/dist/bundle/cli.js +2 -2
  23. package/dist/bundle/index.js +1 -1
  24. package/dist/bundle/rpc-entry.js +1 -1
  25. package/dist/bundle/runtime-manifest.json +1 -1
  26. package/dist/core/agent-session.d.ts +16 -0
  27. package/dist/core/agent-session.js +46 -2
  28. package/dist/core/dynamic-prompt/intent-gate.d.ts +3 -0
  29. package/dist/core/dynamic-prompt/intent-gate.js +4 -3
  30. package/dist/core/dynamic-prompt/policies.d.ts +4 -1
  31. package/dist/core/dynamic-prompt/policies.js +3 -2
  32. package/dist/core/dynamic-prompt/working-task.d.ts +4 -1
  33. package/dist/core/dynamic-prompt/working-task.js +3 -2
  34. package/dist/core/dynamic-prompt/workstation.d.ts +4 -3
  35. package/dist/core/dynamic-prompt/workstation.js +1 -0
  36. package/dist/core/extensions/builtin/goal/index.js +18 -8
  37. package/dist/core/extensions/builtin/goal/monitor-continuation.js +7 -0
  38. package/dist/core/extensions/builtin/goal/reload-reengagement.js +5 -0
  39. package/dist/core/extensions/builtin/index.js +3 -0
  40. package/dist/core/extensions/builtin/prompt-preset/contract.js +6 -1
  41. package/dist/core/extensions/builtin/prompt-preset/gemini-4-argon.d.ts +7 -0
  42. package/dist/core/extensions/builtin/prompt-preset/gemini-4-argon.js +83 -0
  43. package/dist/core/extensions/builtin/prompt-preset/matchers.d.ts +2 -0
  44. package/dist/core/extensions/builtin/prompt-preset/matchers.js +12 -0
  45. package/dist/core/extensions/builtin/prompt-preset/presets.js +3 -0
  46. package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
  47. package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
  48. package/dist/core/extensions/builtin/vertex-model-garden/auth.d.ts +16 -0
  49. package/dist/core/extensions/builtin/vertex-model-garden/auth.js +19 -0
  50. package/dist/core/extensions/builtin/vertex-model-garden/index.d.ts +6 -0
  51. package/dist/core/extensions/builtin/vertex-model-garden/index.js +27 -0
  52. package/dist/core/extensions/builtin/vertex-model-garden/models.d.ts +3 -0
  53. package/dist/core/extensions/builtin/vertex-model-garden/models.js +34 -0
  54. package/dist/core/extensions/builtin/vertex-model-garden/transport.d.ts +14 -0
  55. package/dist/core/extensions/builtin/vertex-model-garden/transport.js +35 -0
  56. package/dist/core/extensions/types.d.ts +32 -1
  57. package/dist/core/provider-api-key-auth.d.ts +9 -1
  58. package/dist/core/provider-api-key-auth.js +34 -0
  59. package/dist/core/provider-composer.d.ts +23 -0
  60. package/dist/core/settings-manager.d.ts +4 -0
  61. package/dist/core/settings-manager.js +6 -0
  62. package/dist/core/settings-shapes.d.ts +4 -0
  63. package/dist/core/turn-deadline.d.ts +92 -0
  64. package/dist/core/turn-deadline.js +179 -0
  65. package/dist/modes/rpc/client-admission-record.d.ts +1 -0
  66. package/dist/modes/rpc/client-admissions.d.ts +6 -3
  67. package/dist/modes/rpc/client-admissions.js +9 -4
  68. package/dist/modes/rpc/connection-handler.js +8 -3
  69. package/dist/modes/rpc/effect-commands.d.ts +1 -1
  70. package/dist/modes/rpc/effect-commands.js +2 -2
  71. package/dist/modes/rpc/effect-outcome-copy.d.ts +4 -4
  72. package/dist/modes/rpc/effect-outcome-copy.js +4 -4
  73. package/dist/modes/rpc/effect-record.d.ts +2 -0
  74. package/dist/modes/rpc/effect-record.js +2 -0
  75. package/dist/modes/rpc/effect-status.js +1 -1
  76. package/dist/modes/rpc/session-unload.js +4 -1
  77. package/docs/rpc.md +4 -1
  78. package/docs/settings.md +3 -1
  79. package/package.json +6 -6
  80. package/dist/bundle/chunks/chunk-7ASXJ4AD.js +0 -47
  81. package/dist/bundle/chunks/google-generative-ai-YNIOL5FT.js +0 -2
  82. package/dist/bundle/chunks/google-vertex-CF6AYVXL.js +0 -2
@@ -1,3 +1,3 @@
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
2
  import{require_semver}from"./chunk-ZOFZRJSL.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{APP_NAME,BRAND,DISPLAY_VERSION,PACKAGE_NAME,brandProfile,envValue}from"./chunk-NP42HAJO.js";import{__toESM}from"./chunk-IKOFCODM.js";import{spawnSync}from"node:child_process";import{homedir as osHomedir}from"node:os";import{posix,win32}from"node:path";var RUNTIME_ENV_VAR="SENPI_RUNTIME",MIN_BUN_VERSION="1.4.0";function normalize(path){return path.replaceAll("\\","/")}function paths(options){return options.platform==="win32"?win32:posix}function bunRoot(options){let configured=options.env.BUN_INSTALL;return configured!==void 0&&configured.trim()!==""?configured:paths(options).join(options.homedir,".bun")}function resolveOrSelf(path,options){try{return options.realpath(path)}catch{return path}}function isUnderBunGlobalTree(scriptRealPath,options){let globalRoot=paths(options).join(bunRoot(options),"install","global"),script=normalize(scriptRealPath);for(let candidate of new Set([globalRoot,resolveOrSelf(globalRoot,options)]))if(script.startsWith(`${normalize(candidate)}/`))return!0;return!1}function isInstalledPackageScript(scriptRealPath){return normalize(scriptRealPath).includes("/node_modules/")}function bunVersionSatisfies(version){let actual=/^v?(\d+)\.(\d+)\.(\d+)/.exec(version?.trim()??""),minimum=/^(\d+)\.(\d+)\.(\d+)/.exec(MIN_BUN_VERSION);if(!actual||!minimum)return!1;for(let index=1;index<=3;index++){let difference=Number(actual[index])-Number(minimum[index]);if(difference!==0)return difference>0}return!0}function bunExecutableName(options){return options.platform==="win32"?"bun.exe":"bun"}function pathCandidateNames(options){if(options.platform!=="win32")return["bun"];let extensions=(options.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(extension=>extension.trim()).filter(extension=>extension.length>0);return extensions.length>0?extensions.map(extension=>`bun${extension}`):["bun.exe"]}function findBunBinary(options){let path=paths(options),executable=bunExecutableName(options),rootCandidates=[path.join(bunRoot(options),"bin",executable),path.join(options.homedir,".bun","bin",executable)];for(let candidate of rootCandidates)if(options.exists(candidate))return candidate;let pathValue=options.env.PATH??options.env.Path;if(pathValue===void 0||pathValue==="")return;let names=pathCandidateNames(options);for(let directory of pathValue.split(path.delimiter))if(directory!=="")for(let name of names){let candidate=path.join(directory,name);if(options.exists(candidate))return candidate}}function readRuntimePin(options){let value=options.env[RUNTIME_ENV_VAR];if(value==="node"||value==="bun")return value}function resolveBunReexec(input){if(input.versions.bun!==void 0)return{action:"stay",reason:"already-bun"};let pinned=readRuntimePin(input.options);if(pinned==="node")return{action:"stay",reason:"runtime-pinned-node"};if(input.hasInheritedInspectorOption)return{action:"stay",reason:"inspector"};let trustsInstalledBun=pinned==="bun"||isUnderBunGlobalTree(input.scriptRealPath,input.options);if(!trustsInstalledBun&&!isInstalledPackageScript(input.scriptRealPath))return{action:"stay",reason:"not-bun-install"};let bunPath=findBunBinary(input.options);return bunPath===void 0?{action:"stay",reason:"bun-not-found"}:!trustsInstalledBun&&!bunVersionSatisfies(input.options.bunVersion(bunPath))?{action:"stay",reason:"bun-too-old"}:{action:"reexec",bunPath}}function readBunVersion(bunPath){try{let result=spawnSync(bunPath,["--version"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(result.status!==0)return;let version=result.stdout.trim();return version===""?void 0:version}catch{return}}function processBunRuntimeOptions(exists,realpath){return{env:process.env,homedir:osHomedir(),platform:process.platform,exists,realpath,bunVersion:readBunVersion}}import{format}from"node:util";var OUTPUT_DELIVERY_LIMIT_MS=3e4,nativeLog=console.log,nativeStdoutWrite=process.stdout.write;async function captureStdout(print){if(console.log!==nativeLog||process.stdout.write!==nativeStdoutWrite)return{result:await print(),output:""};let chunks=[];console.log=(...args)=>{chunks.push(`${format(...args)}
3
- `)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}function getPiUserAgent(version=DISPLAY_VERSION){let runtime=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`${BRAND?.userAgent??APP_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`}var modeHandlers=new WeakSet;function markModeCrashHandler(listener){modeHandlers.add(listener)}function hasModeCrashHandler(event){return process.listeners(event).some(listener=>modeHandlers.has(listener))}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var StaleExtensionContextError=class extends Error{constructor(){super(...arguments),this.name="StaleExtensionContextError"}};var STALE_EXTENSION_CONTEXT_ERROR_PREFIX="This extension ctx is stale after session replacement or reload.",STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE="stale extension generation after reload";function isStaleExtensionContextError(error){return error instanceof StaleExtensionContextError?!0:error instanceof Error&&(error.message.startsWith(STALE_EXTENSION_CONTEXT_ERROR_PREFIX)||error.message===STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE)}var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var import_semver=__toESM(require_semver(),1);var REGISTRY_BASE_URL="https://registry.npmjs.org",LATEST_VERSION_URL=`${REGISTRY_BASE_URL}/${encodeURIComponent(PACKAGE_NAME)}/latest`;function latestVersionUrl(channel){return channel?`${REGISTRY_BASE_URL}/-/package/${encodeURIComponent(channel.packageName)}/dist-tags`:LATEST_VERSION_URL}function readAvailableVersion(payload,channel){if(typeof payload!="object"||payload===null)return;let source=payload,raw=channel?source[channel.distTag]:source.version;return typeof raw=="string"&&raw.trim()?raw.trim():void 0}var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4,RELEASE_CHANGELOG_BASE_URL="https://github.com/code-yeongyu/senpi/blob",RELEASE_CHANGELOG_PATH="packages/coding-agent/CHANGELOG.md",SENPI_CALVER_PATTERN=/^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-([2-9]\d*))?$/;function parseSenpiCalVer(version){let match=SENPI_CALVER_PATTERN.exec(version);if(match)return[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??1)]}function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let leftTrimmed=leftVersion.trim(),rightTrimmed=rightVersion.trim(),leftCalVer=parseSenpiCalVer(leftTrimmed),rightCalVer=parseSenpiCalVer(rightTrimmed);if(leftCalVer&&rightCalVer){for(let index=0;index<leftCalVer.length;index++)if(leftCalVer[index]!==rightCalVer[index])return leftCalVer[index]<rightCalVer[index]?-1:1;return 0}let left=(0,import_semver.valid)(leftTrimmed),right=(0,import_semver.valid)(rightTrimmed);if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0&&comparison>0}function getReleaseChangelogUrl(version){let trimmedVersion=version.trim(),channel=brandProfile()?.update;if(channel?.changelogUrl)return channel.changelogUrl.replace("{version}",trimmedVersion);let tag=trimmedVersion.startsWith("v")?trimmedVersion:`v${trimmedVersion}`;return`${RELEASE_CHANGELOG_BASE_URL}/${tag}/${RELEASE_CHANGELOG_PATH}`}async function getLatestPiRelease(currentVersion,options={}){if(envValue("OFFLINE"))return;let brand=brandProfile(),channel=brand?.update;if(brand&&!channel)return;let response=await fetchWithRetry(latestVersionUrl(channel),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json(),availableVersion=readAvailableVersion(data,channel);if(!availableVersion)return;if(channel)return{version:availableVersion,packageName:channel.packageName};let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:availableVersion,packageName,note}}async function checkForNewPiVersion(currentVersion){if(!envValue("SKIP_VERSION_CHECK"))try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-UCHXVBQ2.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-UCHXVBQ2.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-46PTZGIB.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-NP3HHQJ3.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-2RHSWBQO.js");return await runScheduleCommand(args.slice(1))}export{RUNTIME_ENV_VAR,MIN_BUN_VERSION,bunVersionSatisfies,findBunBinary,resolveBunReexec,processBunRuntimeOptions,captureStdout,exitAfterOutput,printThenExit,getPiUserAgent,StaleExtensionContextError,isStaleExtensionContextError,markModeCrashHandler,hasModeCrashHandler,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,formatVersionCheckError,isNewerPackageVersion,getReleaseChangelogUrl,getLatestPiRelease,checkForNewPiVersion,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
3
+ `)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}function getPiUserAgent(version=DISPLAY_VERSION){let runtime=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`${BRAND?.userAgent??APP_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`}var modeHandlers=new WeakSet;function markModeCrashHandler(listener){modeHandlers.add(listener)}function hasModeCrashHandler(event){return process.listeners(event).some(listener=>modeHandlers.has(listener))}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var StaleExtensionContextError=class extends Error{constructor(){super(...arguments),this.name="StaleExtensionContextError"}};var STALE_EXTENSION_CONTEXT_ERROR_PREFIX="This extension ctx is stale after session replacement or reload.",STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE="stale extension generation after reload";function isStaleExtensionContextError(error){return error instanceof StaleExtensionContextError?!0:error instanceof Error&&(error.message.startsWith(STALE_EXTENSION_CONTEXT_ERROR_PREFIX)||error.message===STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE)}var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var import_semver=__toESM(require_semver(),1);var REGISTRY_BASE_URL="https://registry.npmjs.org",LATEST_VERSION_URL=`${REGISTRY_BASE_URL}/${encodeURIComponent(PACKAGE_NAME)}/latest`;function latestVersionUrl(channel){return channel?`${REGISTRY_BASE_URL}/-/package/${encodeURIComponent(channel.packageName)}/dist-tags`:LATEST_VERSION_URL}function readAvailableVersion(payload,channel){if(typeof payload!="object"||payload===null)return;let source=payload,raw=channel?source[channel.distTag]:source.version;return typeof raw=="string"&&raw.trim()?raw.trim():void 0}var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4,RELEASE_CHANGELOG_BASE_URL="https://github.com/code-yeongyu/senpi/blob",RELEASE_CHANGELOG_PATH="packages/coding-agent/CHANGELOG.md",SENPI_CALVER_PATTERN=/^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-([2-9]\d*))?$/;function parseSenpiCalVer(version){let match=SENPI_CALVER_PATTERN.exec(version);if(match)return[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??1)]}function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let leftTrimmed=leftVersion.trim(),rightTrimmed=rightVersion.trim(),leftCalVer=parseSenpiCalVer(leftTrimmed),rightCalVer=parseSenpiCalVer(rightTrimmed);if(leftCalVer&&rightCalVer){for(let index=0;index<leftCalVer.length;index++)if(leftCalVer[index]!==rightCalVer[index])return leftCalVer[index]<rightCalVer[index]?-1:1;return 0}let left=(0,import_semver.valid)(leftTrimmed),right=(0,import_semver.valid)(rightTrimmed);if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0&&comparison>0}function getReleaseChangelogUrl(version){let trimmedVersion=version.trim(),channel=brandProfile()?.update;if(channel?.changelogUrl)return channel.changelogUrl.replace("{version}",trimmedVersion);let tag=trimmedVersion.startsWith("v")?trimmedVersion:`v${trimmedVersion}`;return`${RELEASE_CHANGELOG_BASE_URL}/${tag}/${RELEASE_CHANGELOG_PATH}`}async function getLatestPiRelease(currentVersion,options={}){if(envValue("OFFLINE"))return;let brand=brandProfile(),channel=brand?.update;if(brand&&!channel)return;let response=await fetchWithRetry(latestVersionUrl(channel),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json(),availableVersion=readAvailableVersion(data,channel);if(!availableVersion)return;if(channel)return{version:availableVersion,packageName:channel.packageName};let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:availableVersion,packageName,note}}async function checkForNewPiVersion(currentVersion){if(!envValue("SKIP_VERSION_CHECK"))try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-2QFJY2AS.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-2QFJY2AS.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-46PTZGIB.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-NP3HHQJ3.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-2RHSWBQO.js");return await runScheduleCommand(args.slice(1))}export{RUNTIME_ENV_VAR,MIN_BUN_VERSION,bunVersionSatisfies,findBunBinary,resolveBunReexec,processBunRuntimeOptions,captureStdout,exitAfterOutput,printThenExit,getPiUserAgent,StaleExtensionContextError,isStaleExtensionContextError,markModeCrashHandler,hasModeCrashHandler,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,formatVersionCheckError,isNewerPackageVersion,getReleaseChangelogUrl,getLatestPiRelease,checkForNewPiVersion,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{enableStartupCompileCache}from"./chunk-V5JFWWGJ.js";import{installStaleExtensionContainment,main}from"./chunk-VY43SSYL.js";import"./chunk-6MEETY7N.js";import"./chunk-43WLJPEG.js";import{configureHttpDispatcher}from"./chunk-QQUHMCOM.js";import"./chunk-P37AEPIE.js";import"./chunk-DCQCK6CK.js";import"./chunk-M2NJDRVW.js";import"./chunk-77PE5H2A.js";import"./chunk-UUMKAA7S.js";import"./chunk-KRAABTZY.js";import"./chunk-IRKWZZKD.js";import"./chunk-JABBHOD5.js";import"./chunk-D6XX3VBK.js";import"./chunk-WIAXG52U.js";import"./chunk-QN2BHP3M.js";import"./chunk-4R4PRTF5.js";import"./chunk-TEGEPQIA.js";import"./chunk-MBT6FT2E.js";import"./chunk-EL4NYWZT.js";import"./chunk-QMRJYMNH.js";import"./chunk-ZMUAAPGV.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-DPRV3FR7.js";import"./chunk-SSEGIXRL.js";import"./chunk-QC4KECXI.js";import"./chunk-YU4AYH4C.js";import"./chunk-VNVSXIJO.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-BJ7LHDCD.js";import"./chunk-26UBFF6N.js";import"./chunk-ZDTNH3XU.js";import"./chunk-5HYU3KLH.js";import"./chunk-BPOEQRHX.js";import"./chunk-7ASLQ243.js";import"./chunk-U3VOXCGP.js";import"./chunk-2VZJTDUX.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-G3OOGWMC.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-Q7RD3NOC.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-NP42HAJO.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-QXREUA5F.js";import"./chunk-WASCMT6Y.js";import"./chunk-RKJNJ3GI.js";import"./chunk-WHPDEDCC.js";import"./chunk-RUGYFYH7.js";import"./chunk-PFNBY43W.js";import"./chunk-7THM57HH.js";import"./chunk-UAQW2T7G.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-3W47LTXQ.js";import"./chunk-4D2PPFKR.js";import"./chunk-WDTJ6JKE.js";import"./chunk-2ON6BFHO.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
3
+ import{enableStartupCompileCache}from"./chunk-FMYLLJBQ.js";import{installStaleExtensionContainment,main}from"./chunk-HJPX7PBL.js";import"./chunk-6MEETY7N.js";import"./chunk-43WLJPEG.js";import"./chunk-4R4PRTF5.js";import{configureHttpDispatcher}from"./chunk-I5ZJEXTM.js";import"./chunk-P37AEPIE.js";import"./chunk-DCQCK6CK.js";import"./chunk-M2NJDRVW.js";import"./chunk-77PE5H2A.js";import"./chunk-UUMKAA7S.js";import"./chunk-AVALXFDW.js";import"./chunk-IRKWZZKD.js";import"./chunk-TEGEPQIA.js";import"./chunk-JABBHOD5.js";import"./chunk-D6XX3VBK.js";import"./chunk-WIAXG52U.js";import"./chunk-QN2BHP3M.js";import"./chunk-MBT6FT2E.js";import"./chunk-EL4NYWZT.js";import"./chunk-QMRJYMNH.js";import"./chunk-ZMUAAPGV.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-DPRV3FR7.js";import"./chunk-SSEGIXRL.js";import"./chunk-QC4KECXI.js";import"./chunk-YU4AYH4C.js";import"./chunk-VNVSXIJO.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-BJ7LHDCD.js";import"./chunk-26UBFF6N.js";import"./chunk-ZDTNH3XU.js";import"./chunk-5HYU3KLH.js";import"./chunk-BPOEQRHX.js";import"./chunk-7ASLQ243.js";import"./chunk-U3VOXCGP.js";import"./chunk-2VZJTDUX.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-G3OOGWMC.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-X5VCHHXR.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-NP42HAJO.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-QXREUA5F.js";import"./chunk-WASCMT6Y.js";import"./chunk-RKJNJ3GI.js";import"./chunk-WHPDEDCC.js";import"./chunk-RUGYFYH7.js";import"./chunk-PFNBY43W.js";import"./chunk-7THM57HH.js";import"./chunk-UAQW2T7G.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-3W47LTXQ.js";import"./chunk-4D2PPFKR.js";import"./chunk-WDTJ6JKE.js";import"./chunk-2ON6BFHO.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
@@ -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{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-WL4Y6XN6.js";import"./chunk-K2EVQGGT.js";import"./chunk-4XY6YHML.js";import"./chunk-GQ3YLXVZ.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-H5FG6VPZ.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-4D2PPFKR.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-2ON6BFHO.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,providerHeadersToRecord(options?.headers)),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||output.content.push(toProviderNativeContent(part))}candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
@@ -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{buildGoogleAuthOptions,resolveVertexProjectFromEnv}from"./chunk-74YFRVGQ.js";import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-WL4Y6XN6.js";import"./chunk-K2EVQGGT.js";import"./chunk-4XY6YHML.js";import"./chunk-GQ3YLXVZ.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-H5FG6VPZ.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-4D2PPFKR.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-2ON6BFHO.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||output.content.push(toProviderNativeContent(part))}candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=resolveVertexProjectFromEnv(options);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
@@ -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{buildGoogleAuthOptions,resolveVertexProjectFromEnv}from"./chunk-74YFRVGQ.js";import{require_src}from"./chunk-K2EVQGGT.js";import"./chunk-5ROMKDLK.js";import{__toESM}from"./chunk-IKOFCODM.js";var import_google_auth_library=__toESM(require_src(),1);var CLOUD_PLATFORM_SCOPE="https://www.googleapis.com/auth/cloud-platform",authByKey=new Map;function getGoogleAuth(env){let authOptions=buildGoogleAuthOptions(env),key=authOptions?.keyFilename??"",auth=authByKey.get(key);return auth||(auth=new import_google_auth_library.GoogleAuth({...authOptions,scopes:[CLOUD_PLATFORM_SCOPE]}),authByKey.set(key,auth)),auth}async function getVertexAdcAccess(options){let auth=getGoogleAuth(options?.env),client=await auth.getClient(),{token}=await client.getAccessToken();if(!token)throw new Error("Google Application Default Credentials returned no access token.");let adcQuotaProject=client.quotaProjectId||void 0,project=resolveVertexProjectFromEnv(options)??adcQuotaProject??(await auth.getProjectId().catch(()=>null)||void 0);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or a quota project in Application Default Credentials.");return{accessToken:token,project,quotaProject:adcQuotaProject??project}}export{getVertexAdcAccess};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-VY43SSYL.js";import"./chunk-6MEETY7N.js";import"./chunk-43WLJPEG.js";import"./chunk-QQUHMCOM.js";import"./chunk-P37AEPIE.js";import"./chunk-DCQCK6CK.js";import"./chunk-M2NJDRVW.js";import"./chunk-77PE5H2A.js";import"./chunk-UUMKAA7S.js";import"./chunk-KRAABTZY.js";import"./chunk-IRKWZZKD.js";import"./chunk-JABBHOD5.js";import"./chunk-D6XX3VBK.js";import"./chunk-WIAXG52U.js";import"./chunk-QN2BHP3M.js";import"./chunk-4R4PRTF5.js";import"./chunk-TEGEPQIA.js";import"./chunk-MBT6FT2E.js";import"./chunk-EL4NYWZT.js";import"./chunk-QMRJYMNH.js";import"./chunk-ZMUAAPGV.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-DPRV3FR7.js";import"./chunk-SSEGIXRL.js";import"./chunk-QC4KECXI.js";import"./chunk-YU4AYH4C.js";import"./chunk-VNVSXIJO.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-BJ7LHDCD.js";import"./chunk-26UBFF6N.js";import"./chunk-ZDTNH3XU.js";import"./chunk-5HYU3KLH.js";import"./chunk-BPOEQRHX.js";import"./chunk-7ASLQ243.js";import"./chunk-U3VOXCGP.js";import"./chunk-2VZJTDUX.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-G3OOGWMC.js";import"./chunk-Q7RD3NOC.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-NP42HAJO.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-QXREUA5F.js";import"./chunk-WASCMT6Y.js";import"./chunk-RKJNJ3GI.js";import"./chunk-WHPDEDCC.js";import"./chunk-RUGYFYH7.js";import"./chunk-PFNBY43W.js";import"./chunk-7THM57HH.js";import"./chunk-UAQW2T7G.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-3W47LTXQ.js";import"./chunk-4D2PPFKR.js";import"./chunk-WDTJ6JKE.js";import"./chunk-2ON6BFHO.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
2
+ import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-HJPX7PBL.js";import"./chunk-6MEETY7N.js";import"./chunk-43WLJPEG.js";import"./chunk-4R4PRTF5.js";import"./chunk-I5ZJEXTM.js";import"./chunk-P37AEPIE.js";import"./chunk-DCQCK6CK.js";import"./chunk-M2NJDRVW.js";import"./chunk-77PE5H2A.js";import"./chunk-UUMKAA7S.js";import"./chunk-AVALXFDW.js";import"./chunk-IRKWZZKD.js";import"./chunk-TEGEPQIA.js";import"./chunk-JABBHOD5.js";import"./chunk-D6XX3VBK.js";import"./chunk-WIAXG52U.js";import"./chunk-QN2BHP3M.js";import"./chunk-MBT6FT2E.js";import"./chunk-EL4NYWZT.js";import"./chunk-QMRJYMNH.js";import"./chunk-ZMUAAPGV.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-DPRV3FR7.js";import"./chunk-SSEGIXRL.js";import"./chunk-QC4KECXI.js";import"./chunk-YU4AYH4C.js";import"./chunk-VNVSXIJO.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-BJ7LHDCD.js";import"./chunk-26UBFF6N.js";import"./chunk-ZDTNH3XU.js";import"./chunk-5HYU3KLH.js";import"./chunk-BPOEQRHX.js";import"./chunk-7ASLQ243.js";import"./chunk-U3VOXCGP.js";import"./chunk-2VZJTDUX.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-G3OOGWMC.js";import"./chunk-X5VCHHXR.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-NP42HAJO.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-QXREUA5F.js";import"./chunk-WASCMT6Y.js";import"./chunk-RKJNJ3GI.js";import"./chunk-WHPDEDCC.js";import"./chunk-RUGYFYH7.js";import"./chunk-PFNBY43W.js";import"./chunk-7THM57HH.js";import"./chunk-UAQW2T7G.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-3W47LTXQ.js";import"./chunk-4D2PPFKR.js";import"./chunk-WDTJ6JKE.js";import"./chunk-2ON6BFHO.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
@@ -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{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,ClientAdmissions,EMPTY_SESSION_CONTEXT,EffectLedger,HostMcpRegistry,ProviderScope,answerEffectFromTranscript,beginEffect,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,drainSessionEffects,effectAnswer,effectStatusRecord,foreignSessionHolders,installSessionEffectSink,isEffectBegin,latestSessionEffect,parsePermissionPresetName,readCodemodeKernelRows,readMainThreadHeapBytes,readOwnFootprint,runWithProviderScope,startHostChildReaper,subscriptionLimits}from"./chunk-VY43SSYL.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY}from"./chunk-6MEETY7N.js";import{readProcessStartMs}from"./chunk-43WLJPEG.js";import{flushRawStdout,liveToolMediaScope,omitInlineMedia,takeOverStdout,toolMediaPersister,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-QQUHMCOM.js";import{SessionManager,assertValidSessionId}from"./chunk-P37AEPIE.js";import{resolveMovedPath}from"./chunk-DCQCK6CK.js";import"./chunk-M2NJDRVW.js";import"./chunk-77PE5H2A.js";import"./chunk-UUMKAA7S.js";import{DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionQuestionBridges,sessionRetryFallbackError}from"./chunk-KRAABTZY.js";import"./chunk-IRKWZZKD.js";import"./chunk-JABBHOD5.js";import"./chunk-D6XX3VBK.js";import"./chunk-WIAXG52U.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-4R4PRTF5.js";import"./chunk-TEGEPQIA.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,beginHandoverResponse,handoverRefusal,hostGeneration,hostInstanceId,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,protocolIdentity,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-MBT6FT2E.js";import{AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DETACH_CONNECTION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,EVAL_CELLS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,parseClientCapabilities}from"./chunk-EL4NYWZT.js";import"./chunk-QMRJYMNH.js";import"./chunk-ZMUAAPGV.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-DPRV3FR7.js";import{killTrackedDetachedChildren}from"./chunk-SSEGIXRL.js";import"./chunk-QC4KECXI.js";import"./chunk-YU4AYH4C.js";import"./chunk-VNVSXIJO.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-BJ7LHDCD.js";import"./chunk-26UBFF6N.js";import"./chunk-ZDTNH3XU.js";import{ClientOccupancy,armHostWatchdog,loopLagErrorMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-5HYU3KLH.js";import{MAX_RPC_LINE_CHARACTERS,PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,attachJsonlLineReader,authenticateSocket,canonicalSessionPath,createEndpointReservations,createHostDaemonPaths,ensureSocketSecret,ownGenerationDir,parseIdleExitMs,readSocketIdentityFile,resolveSocketTransportAddress,serializeJsonLine,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile,writeHeartbeat,writeStallEvidence}from"./chunk-BPOEQRHX.js";import{processStartTimeMs}from"./chunk-7ASLQ243.js";import"./chunk-U3VOXCGP.js";import"./chunk-2VZJTDUX.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-G3OOGWMC.js";import"./chunk-Q7RD3NOC.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-NP42HAJO.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-QXREUA5F.js";import"./chunk-WASCMT6Y.js";import"./chunk-RKJNJ3GI.js";import"./chunk-WHPDEDCC.js";import"./chunk-RUGYFYH7.js";import"./chunk-PFNBY43W.js";import"./chunk-7THM57HH.js";import"./chunk-UAQW2T7G.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-3W47LTXQ.js";import"./chunk-4D2PPFKR.js";import"./chunk-WDTJ6JKE.js";import"./chunk-2ON6BFHO.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join as join2}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);return beginHandoverResponse(parsed.id,typeof request=="string"?request:await this.handover.begin(request))}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{existsSync as existsSync4}from"node:fs";import{createHash}from"node:crypto";import{existsSync,renameSync}from"node:fs";import{mkdir,readdir,readFile,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var recordDir=daemonDir=>join(daemonDir,"handover-parked"),entryFile=(daemonDir,sessionPath)=>join(recordDir(daemonDir),`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`),mutationChain=Promise.resolve();function enqueueMutation(mutation){let next=mutationChain.then(mutation,mutation);return mutationChain=next.catch(()=>{}),next}function isEntry(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;let record=value;return typeof record.sessionPath=="string"&&typeof record.retainOnDisconnect=="boolean"&&(record.durableSessionId===void 0||typeof record.durableSessionId=="string")&&(record.cwd===void 0||typeof record.cwd=="string")&&(record.thinkingLevel===void 0||typeof record.thinkingLevel=="string")&&(record.permissionPreset===void 0||typeof record.permissionPreset=="string"&&parsePermissionPresetName(record.permissionPreset)!==void 0)&&sessionPromptSurfaceError(record.promptSurface)===void 0&&sessionBrowserEngineError(record.browserEngine)===void 0&&sessionKindError(record.sessionKind)===void 0&&sessionContextError(record.sessionContext)===void 0&&sessionAutoTitleError(record.autoTitle)===void 0&&sessionRetryFallbackError(record.retryFallback)===void 0&&(record.model===void 0||typeof record.model=="object"&&record.model!==null&&typeof record.model.provider=="string"&&typeof record.model.modelId=="string")}async function writeEntryFile(daemonDir,entry){await mkdir(recordDir(daemonDir),{recursive:!0,mode:448});let file=entryFile(daemonDir,entry.sessionPath),tmp=`${file}.${process.pid}.${Math.random().toString(16).slice(2,10)}.tmp`;await writeFile(tmp,`${JSON.stringify(entry,null,2)}
2
+ import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,ClientAdmissions,EMPTY_SESSION_CONTEXT,EffectLedger,HostMcpRegistry,ProviderScope,answerEffectFromTranscript,beginEffect,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,drainSessionEffects,effectAnswer,effectStatusRecord,foreignSessionHolders,installSessionEffectSink,isEffectBegin,latestSessionEffect,parsePermissionPresetName,readCodemodeKernelRows,readMainThreadHeapBytes,readOwnFootprint,runWithProviderScope,startHostChildReaper,subscriptionLimits}from"./chunk-HJPX7PBL.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY}from"./chunk-6MEETY7N.js";import{readProcessStartMs}from"./chunk-43WLJPEG.js";import"./chunk-4R4PRTF5.js";import{flushRawStdout,liveToolMediaScope,omitInlineMedia,takeOverStdout,toolMediaPersister,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-I5ZJEXTM.js";import{SessionManager,assertValidSessionId}from"./chunk-P37AEPIE.js";import{resolveMovedPath}from"./chunk-DCQCK6CK.js";import"./chunk-M2NJDRVW.js";import"./chunk-77PE5H2A.js";import"./chunk-UUMKAA7S.js";import{DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionQuestionBridges,sessionRetryFallbackError}from"./chunk-AVALXFDW.js";import"./chunk-IRKWZZKD.js";import"./chunk-TEGEPQIA.js";import"./chunk-JABBHOD5.js";import"./chunk-D6XX3VBK.js";import"./chunk-WIAXG52U.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,beginHandoverResponse,handoverRefusal,hostGeneration,hostInstanceId,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,protocolIdentity,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-MBT6FT2E.js";import{AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DETACH_CONNECTION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,EVAL_CELLS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,parseClientCapabilities}from"./chunk-EL4NYWZT.js";import"./chunk-QMRJYMNH.js";import"./chunk-ZMUAAPGV.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-DPRV3FR7.js";import{killTrackedDetachedChildren}from"./chunk-SSEGIXRL.js";import"./chunk-QC4KECXI.js";import"./chunk-YU4AYH4C.js";import"./chunk-VNVSXIJO.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-BJ7LHDCD.js";import"./chunk-26UBFF6N.js";import"./chunk-ZDTNH3XU.js";import{ClientOccupancy,armHostWatchdog,loopLagErrorMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-5HYU3KLH.js";import{MAX_RPC_LINE_CHARACTERS,PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,attachJsonlLineReader,authenticateSocket,canonicalSessionPath,createEndpointReservations,createHostDaemonPaths,ensureSocketSecret,ownGenerationDir,parseIdleExitMs,readSocketIdentityFile,resolveSocketTransportAddress,serializeJsonLine,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile,writeHeartbeat,writeStallEvidence}from"./chunk-BPOEQRHX.js";import{processStartTimeMs}from"./chunk-7ASLQ243.js";import"./chunk-U3VOXCGP.js";import"./chunk-2VZJTDUX.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-G3OOGWMC.js";import"./chunk-X5VCHHXR.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-NP42HAJO.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-QXREUA5F.js";import"./chunk-WASCMT6Y.js";import"./chunk-RKJNJ3GI.js";import"./chunk-WHPDEDCC.js";import"./chunk-RUGYFYH7.js";import"./chunk-PFNBY43W.js";import"./chunk-7THM57HH.js";import"./chunk-UAQW2T7G.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-3W47LTXQ.js";import"./chunk-4D2PPFKR.js";import"./chunk-WDTJ6JKE.js";import"./chunk-2ON6BFHO.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join as join2}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);return beginHandoverResponse(parsed.id,typeof request=="string"?request:await this.handover.begin(request))}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{existsSync as existsSync4}from"node:fs";import{createHash}from"node:crypto";import{existsSync,renameSync}from"node:fs";import{mkdir,readdir,readFile,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var recordDir=daemonDir=>join(daemonDir,"handover-parked"),entryFile=(daemonDir,sessionPath)=>join(recordDir(daemonDir),`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`),mutationChain=Promise.resolve();function enqueueMutation(mutation){let next=mutationChain.then(mutation,mutation);return mutationChain=next.catch(()=>{}),next}function isEntry(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;let record=value;return typeof record.sessionPath=="string"&&typeof record.retainOnDisconnect=="boolean"&&(record.durableSessionId===void 0||typeof record.durableSessionId=="string")&&(record.cwd===void 0||typeof record.cwd=="string")&&(record.thinkingLevel===void 0||typeof record.thinkingLevel=="string")&&(record.permissionPreset===void 0||typeof record.permissionPreset=="string"&&parsePermissionPresetName(record.permissionPreset)!==void 0)&&sessionPromptSurfaceError(record.promptSurface)===void 0&&sessionBrowserEngineError(record.browserEngine)===void 0&&sessionKindError(record.sessionKind)===void 0&&sessionContextError(record.sessionContext)===void 0&&sessionAutoTitleError(record.autoTitle)===void 0&&sessionRetryFallbackError(record.retryFallback)===void 0&&(record.model===void 0||typeof record.model=="object"&&record.model!==null&&typeof record.model.provider=="string"&&typeof record.model.modelId=="string")}async function writeEntryFile(daemonDir,entry){await mkdir(recordDir(daemonDir),{recursive:!0,mode:448});let file=entryFile(daemonDir,entry.sessionPath),tmp=`${file}.${process.pid}.${Math.random().toString(16).slice(2,10)}.tmp`;await writeFile(tmp,`${JSON.stringify(entry,null,2)}
3
3
  `,{mode:384}),renameSync(tmp,file)}function recordHandoverParkedSession(daemonDir,entry){return enqueueMutation(()=>writeEntryFile(daemonDir,entry))}async function readHandoverParkedSessions(daemonDir){let names;try{names=(await readdir(recordDir(daemonDir))).filter(name=>name.endsWith(".json"))}catch{return[]}let entries=[];for(let name of names){let file=join(recordDir(daemonDir),name);try{let parsed=JSON.parse(await readFile(file,"utf8"));isEntry(parsed)&&entries.push(parsed)}catch(cause){cause instanceof SyntaxError&&(process.stderr.write(`senpi rpc handover-parked entry ${name} is corrupt; dropping it
4
4
  `),await rm(file,{force:!0}))}}return entries}function clearHandoverParkedSession(daemonDir,sessionPath){return enqueueMutation(()=>rm(entryFile(daemonDir,sessionPath),{force:!0}))}function dropHandoverParkedSessionIfFileGone(daemonDir,sessionPath){return existsSync(sessionPath)?Promise.resolve():clearHandoverParkedSession(daemonDir,sessionPath)}import{existsSync as existsSync3}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code){return{id:command.id,type:"response",command:"warm",success:!1,error:code}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.holderEndpoint?{holderEndpoint:Object.freeze({...profile.holderEndpoint})}:{},...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{},...profile.retryFallback?{retryFallback:Object.freeze({modelFallback:profile.retryFallback.modelFallback,fallbackChains:Object.freeze(Object.fromEntries(Object.entries(profile.retryFallback.fallbackChains).map(([key,entries])=>[key,Object.freeze([...entries])])))})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}function assertRequestedModelResolved(profile,diagnostics){let requested=profile.creationModel;if(requested===void 0)return;let unresolved=diagnostics.find(diagnostic=>diagnostic.code==="model_unresolved");if(unresolved!==void 0)throw new RpcSessionRegistryError("open_failed",`model_unavailable: ${unresolved.message}`,{reason:"model_unavailable",requestedModel:`${requested.provider}/${requested.modelId}`})}var observations=new Set(["get_state","get_effect_status","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_session_stats","resolve_path","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_fast_mode","get_commands","get_loaded_surfaces","get_media","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek"]);function refreshesSessionActivity(command){return!observations.has(command)}var SESSION_CONTEXT_PATCH_LIMITS={keyPattern:/^[a-z][a-z0-9_]{0,63}$/,valueChars:256,overlayBytes:4096},RESERVED_SESSION_CONTEXT_KEYS=new Set(["host_socket","host_instance","shard_key","tree_key","parent_session_id","root_session_id"]);function refuse(reason,action){return{refusal:{reason,action}}}function applyContextPatch(overlay,patch){let shape='send patch as an object of lowercase keys to string, number, boolean or null values, e.g. { "task_status": "running" }';if(typeof patch!="object"||patch===null||Array.isArray(patch))return refuse("patch must be an object",shape);let entries=Object.entries(patch);if(entries.length===0)return refuse("patch has no keys",shape);let merged={...overlay};for(let[key,value]of entries){if(!SESSION_CONTEXT_PATCH_LIMITS.keyPattern.test(key))return refuse(`key "${key}" must match ${SESSION_CONTEXT_PATCH_LIMITS.keyPattern.source}`,"rename the key to lowercase letters, digits and underscores");if(RESERVED_SESSION_CONTEXT_KEYS.has(key))return refuse(`key "${key}" is set by the host and cannot be patched`,"drop that key from the patch; the host keeps it current");if(typeof value=="string"&&value.length>SESSION_CONTEXT_PATCH_LIMITS.valueChars)return refuse(`value for "${key}" is ${value.length} characters, at most ${SESSION_CONTEXT_PATCH_LIMITS.valueChars} are accepted`,"shorten the value or store it elsewhere and publish a reference");if(typeof value=="number"&&!Number.isFinite(value))return refuse(`value for "${key}" must be a finite number`,shape);if(value!==null&&typeof value!="string"&&typeof value!="number"&&typeof value!="boolean")return refuse(`value for "${key}" must be a string, number, boolean or null`,shape);merged[key]=value}let bytes=Buffer.byteLength(JSON.stringify(merged));return bytes>SESSION_CONTEXT_PATCH_LIMITS.overlayBytes?refuse(`patched context would be ${bytes} bytes, at most ${SESSION_CONTEXT_PATCH_LIMITS.overlayBytes} are accepted`,"remove keys with null or shorten values before adding more"):{overlay:merged}}function publishedSessionContext(base,overlay){if(overlay===void 0)return base;let published={...base};for(let[key,value]of Object.entries(overlay))value===null?delete published[key]:published[key]=value;return published}var DEFAULT_OPEN_IN_PROGRESS_WAIT_MS=45e3,OPEN_IN_PROGRESS_WAIT_RETRY_MS=2e3;function openInProgressWaitMs(){let override=Number(process.env.SENPI_OPEN_IN_PROGRESS_WAIT_MS);return Number.isFinite(override)&&override>0?override:DEFAULT_OPEN_IN_PROGRESS_WAIT_MS}var OpenInProgressWaitError=class extends Error{};function openingOwner(sessionPath){return{instanceId:hostInstanceId(),pid:process.pid,processStartTime:null,sessionPath,attached:!0,current:!0}}function waitWithDeadline(openCompletion,waitMs){let timer;return Promise.race([openCompletion,new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new OpenInProgressWaitError),waitMs)})]).finally(()=>{timer!==void 0&&clearTimeout(timer)})}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing){let inFlight=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="opening");if(inFlight?.[1].openCompletion!==void 0){try{await waitWithDeadline(inFlight[1].openCompletion,openInProgressWaitMs())}catch(cause){throw cause instanceof OpenInProgressWaitError?new RpcSessionRegistryError("session_path_in_use","the session is still opening",{reason:"open_in_progress",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS,owner:openingOwner(sessionPath)}):new RpcSessionRegistryError("session_path_in_use","the in-flight open failed",{reason:"open_failed",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}return attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now)}throw new RpcSessionRegistryError("session_path_in_use")}let[handle,entry]=existing,wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;if(entry.attachments+=1,entry.detachedAt=void 0,pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),!entry.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface:profile.promptSurface}),entry.runtime?.setPromptSurface(profile.promptSurface)),profile.browserEngine!==void 0&&profile.browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine:profile.browserEngine}),entry.runtime?.setBrowserEngine(profile.browserEngine)),profile.permissionPreset!==void 0&&(entry.profile=frozenProfile({...entry.profile,permissionPreset:profile.permissionPreset}),entry.runtime?.setPermissionPreset(profile.permissionPreset)),entry.lastCommandAt=now,wasParked&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed")),await entry.lifecycleMutex),{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,attached:!0}}function syncRuntimeMetadata(entries,reservations,pathReservations){for(let entry of entries){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(reservations.delete(entry.reservationKey),pathReservations?.release(entry.reservationKey)),currentKey&&(reservations.add(currentKey),pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}async function settleClosingReservation(entries,sessionPath,closeGraceMs){let closing=[...entries].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve=>{deadline=setTimeout(resolve,closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}import{existsSync as existsSync2}from"node:fs";function resolveMovedProfile(requested){let profile={...requested,cwd:resolveMovedPath(requested.cwd),...requested.sessionPath?{sessionPath:resolveMovedPath(requested.sessionPath)}:{}};if(profile.sessionPath!==requested.sessionPath&&profile.sessionPath&&!existsSync2(profile.sessionPath))throw new RpcSessionRegistryError("open_failed",`moved session file does not exist: ${profile.sessionPath}`);return profile}function createEntrySwitchSession(entry,createRuntime,syncRuntimeMetadata2){return(sessionPath,options)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath,options);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),ClientAdmissions.sealQueuedOnReplace(replacement),EffectLedger.sealOnReplace(replacement),runtime.releaseSessionHold(),entry.runtime=replacement,syncRuntimeMetadata2(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation}}function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
5
5
  `)}function beginSessionClose(host,handle,onRole,options){let entry=host.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.detachedAt??=host.now(),entry.reservationKey&&!sessionIsWriting(entry)&&host.markDetached(entry.reservationKey),entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),entry)}async function releaseWithinGrace(host,handle,key){let timer,late=new Promise(resolve=>{timer=setTimeout(()=>resolve("late"),host.closeGraceMs)}),removal=host.releaseReservation(key).then(()=>"removed",cause=>(reportDetachedFailure(handle,cause),"failed")),outcome=await Promise.race([removal,late]);clearTimeout(timer),outcome==="late"&&reportDetachedFailure(handle,new Error(`session path reservation was not removed within ${host.closeGraceMs} ms; closing anyway`))}function closeSession(host,handle){return beginSessionClose(host,handle).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle)}function closeMarkedSession(host,handle){host.sync();let entry=host.get(handle);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await disposeOnce().catch(()=>{}),await entry.scope.close?.())},release=async()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.reservationKey&&await releaseWithinGrace(host,handle,entry.reservationKey),entry.state="closed",host.delete(handle))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle,cause)}})(),settled=!1,finish=async()=>{settled||(settled=!0,await release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle,cause)),graceful.catch(cause=>reportDetachedFailure(handle,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>(reportDetachedFailure(handle,cause),finish())),completion}var RpcSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new Set,this.nextHandle=0,options.createRuntime.prepare&&(this.warm=createRegistryWarm(options.createRuntime.prepare,{agentDir:options.agentDir,...options.mcpRegistry!==void 0?{mcpRegistry:options.mcpRegistry}:{}})),this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle=>this.entries.get(handle),delete:handle=>{let deleted=this.entries.delete(handle);return this.options.onSizeChange?.(this.entries.size),deleted},releaseReservation:async key=>{await this.options.pathReservations?.release(key),this.reservations.delete(key)},markDetached:key=>this.options.pathReservations?.setAttached(key,!1),now:()=>this.now(),sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}holderPids(observedStarts){return this.options.pathReservations?.holderPids?.(observedStarts)??Promise.resolve([])}async openSession(requested,options){this.validateProfile(requested);let profile=resolveMovedProfile(requested);this.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalSessionPath(profile.sessionPath):void 0,requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(sessionPath!==void 0&&entry2.reservationKey===sessionPath))throw new RpcSessionRegistryError("session_id_in_use")}if(sessionPath&&await settleClosingReservation(this.entries.values(),sessionPath,this.closeGraceMs),sessionPath&&this.reservations.has(sessionPath))return attachToOpenSession(this.entries,sessionPath,profile,options,this.options.pathReservations,this.now());if(options?.attachOnly)throw new RpcSessionRegistryError("session_not_held",void 0,{reason:"session_not_held",action:"rediscover_holder"});if(sessionPath){this.reservations.add(sessionPath);let holder=this.options.pathReservations?await this.options.pathReservations.claim(sessionPath):void 0;if(holder)throw this.reservations.delete(sessionPath),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let isResume=sessionPath!==void 0&&existsSync3(sessionPath),sessionStartEvent=isResume?{type:"session_start",reason:"resume"}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,handle=`rpc-${++this.nextHandle}`,settleOpen,openCompletion=new Promise((resolve,reject)=>{settleOpen={resolve,reject}});openCompletion.catch(()=>{});let entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve(),openCompletion};entry.switchSession=createEntrySwitchSession(entry,this.options.createRuntime,()=>this.syncRuntimeMetadata()),requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),this.entries.set(handle,entry),this.options.onSizeChange?.(this.entries.size);try{let newSessionOptions=requestedDurableId!==void 0?{id:requestedDurableId}:void 0,manager=sessionPath?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(this.options.createRuntime,{cwd:manager.getCwd(),agentDir:this.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),assertRequestedModelResolved(runtimeProfile,entry.runtime.diagnostics),ClientAdmissions.sealQueuedOnReplace(entry.runtime),EffectLedger.sealOnReplace(entry.runtime),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",settleOpen.resolve(),{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{this.entries.delete(handle),this.options.onSizeChange?.(this.entries.size),sessionPath&&await releaseWithinGrace(this.teardownHost,handle,sessionPath)}}if(error2 instanceof RpcSessionRegistryError)throw settleOpen.reject(error2),error2;let wrapped=new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0);throw settleOpen.reject(wrapped),wrapped}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return(entry.attachments>0||refreshesSessionActivity(command))&&(entry.lastCommandAt=this.now()),entry}beginClose(handle,onRole,options){return beginSessionClose(this.teardownHost,handle,onRole,options)}async close(handle){return closeSession(this.teardownHost,handle)}async closeMarked(handle){return closeMarkedSession(this.teardownHost,handle)}list(){this.syncRuntimeMetadata();let now=this.now();return[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:publishedSessionContext(entry.context,entry.contextOverlay),attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state,idleMs:Math.max(0,now-entry.lastCommandAt)}))}syncRuntimeMetadata(){syncRuntimeMetadata(this.entries.values(),this.reservations,this.options.pathReservations)}validateProfile(profile){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");if(profile.durableSessionId!==void 0)try{assertValidSessionId(profile.durableSessionId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}}};var HANDOVER_PARKED_REOPEN_BUDGET_MS=12e4,HANDOVER_PARKED_REOPEN_POLL_MS=250,HANDOVER_PARKED_REOPEN_MAX_ATTEMPTS=8,HANDOVER_PARKED_REOPEN_QUIET_STREAK=8;async function reopenHandoverParkedSessions(open,agentDir,socket,holder){let daemonDir=createHostDaemonPaths({socket,agentDir}).dir,deadline=Date.now()+HANDOVER_PARKED_REOPEN_BUDGET_MS,reopenAttempts=new Map,heldPolls=new Map,emptyStreak=0,sawAnyPark=!1;for(;;){if(holder?.shouldReopen!==void 0&&!holder.shouldReopen())return;let parked=await readHandoverParkedSessions(daemonDir);for(let entry of parked)sawAnyPark=!0,await reopenOne(daemonDir,open,entry,reopenAttempts,heldPolls,holder);if(emptyStreak=(await readHandoverParkedSessions(daemonDir)).length===0?emptyStreak+1:0,sawAnyPark&&emptyStreak>=HANDOVER_PARKED_REOPEN_QUIET_STREAK||Date.now()>=deadline)return;await new Promise(resolve=>setTimeout(resolve,HANDOVER_PARKED_REOPEN_POLL_MS))}}async function reopenOne(daemonDir,open,entry,attempts,heldPolls,holder){if(await dropHandoverParkedSessionIfFileGone(daemonDir,entry.sessionPath),!existsSync4(entry.sessionPath)){process.stderr.write(`senpi rpc successor dropped a parked session whose file is gone: ${entry.sessionPath}
@@ -13,7 +13,7 @@ import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILI
13
13
  `),{type:"open_session",sessionPath:entry.sessionPath,...entry.cwd!==void 0?{cwd:entry.cwd}:{},...entry.durableSessionId!==void 0?{durableSessionId:entry.durableSessionId}:{},...entry.model!==void 0?{provider:entry.model.provider,modelId:entry.model.modelId}:{},...thinkingLevel!==void 0?{thinkingLevel}:{},...entry.permissionPreset!==void 0?{permissionPreset:entry.permissionPreset}:{},...entry.promptSurface!==void 0?{promptSurface:entry.promptSurface}:{},...entry.browserEngine!==void 0?{browserEngine:entry.browserEngine}:{},...entry.sessionKind!==void 0?{kind:entry.sessionKind}:{},...entry.sessionContext!==void 0?{context:entry.sessionContext}:{},...entry.autoTitle!==void 0?{auto_title:entry.autoTitle}:{},...entry.retryFallback!==void 0?{retryFallback:entry.retryFallback}:{},retain_on_disconnect:entry.retainOnDisconnect}}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
14
14
  `)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),droppedAfterClose=!1,handler=await runWithProviderScope(entry.scope,async()=>{let writeInScope=bindToProviderScope(enqueueRecords),taggedSink={writeRaw:chunk=>{if(entry.scope.state==="closed"){droppedAfterClose||process.stderr.write(`senpi rpc host: dropped a record for closed session ${sessionId} at ${new Date().toISOString()}
15
15
  `),droppedAfterClose=!0;return}writeInScope(chunk)},waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),publishLoadedSurfacesChanged:(previous,digest)=>{entry.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}import{execFile}from"node:child_process";var READ_ONLY_OR_CONTROL=new Set(["get_state","get_effect_status","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_fast_mode","get_session_stats","resolve_path","get_fork_messages","get_entries","get_tree","get_last_assistant_text","get_messages","get_media","get_commands","get_loaded_surfaces","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek","eval_cells.stop","export_html","export_jsonl","abort","interrupt","abort_compaction","abort_branch_summary","abort_retry","abort_bash","clear_queue","check_reload_veto","cleanup_bash_output","set_client_info","extension_ui_response","extension_ui_progress"]);function readProcessStarts(){let windows=process.platform==="win32",command=windows?"powershell.exe":"ps",args=windows?["-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }']:["-axo","pid=,lstart="];return new Promise(resolve=>{execFile(command,args,{timeout:windows?5e3:1e3,maxBuffer:4*1024*1024,windowsHide:!0,...windows?{}:{env:{...process.env,LC_ALL:"C",LANG:"C"}}},(error2,stdout)=>{if(error2)return resolve(void 0);let starts=new Map;for(let line of stdout.split(`
16
- `)){let row=/^\s*(\d+)\s+(.+)$/.exec(line);if(!row)continue;let start=processStartTimeMs(row[2]);start!==void 0&&starts.set(Number(row[1]),start)}resolve(starts)})})}function sessionHeldCheck(resolveDaemonPids){let daemonPids,processStarts,pidStarts=new Map,observedStarts=new Map;return async(sessionFile,sessionId)=>{let holders=await foreignSessionHolders(sessionFile,sessionId,{readProcessStartMs:pid=>{let probe=pidStarts.get(pid);return probe||(probe=(async()=>{process.platform!=="linux"&&(processStarts??=readProcessStarts());let start=(await processStarts)?.get(pid)??await readProcessStartMs(pid);return observedStarts.set(pid,start),start})(),pidStarts.set(pid,probe)),probe}});if(holders.length===0)return;daemonPids??=resolveDaemonPids?.(observedStarts)??Promise.resolve([]);let family=await daemonPids,foreign=holders.filter(holder=>!family.includes(holder.pid));if(foreign.length>0)throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD,void 0,{holders:foreign.map(({pid,cwd,host_socket,host_instance})=>({pid,...cwd===void 0?{}:{cwd},...host_socket===void 0?{}:{host_socket},...host_instance===void 0?{}:{host_instance}}))})}}async function dispatchSessionBinding(command,entry,binding,acknowledgePrompt,daemonPids){if(!binding)throw new RpcSessionRegistryError("unknown_session");if(!READ_ONLY_OR_CONTROL.has(command.type)){let assertSessionNotHeld=sessionHeldCheck(daemonPids),state=entry.worker?.snapshot?.state;await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),"sessionPath"in command&&await assertSessionNotHeld(command.sessionPath)}command.type==="prompt"&&acknowledgePrompt(),await binding.handle(command)}var NOTHING_DROPPED={deliveries:[],user_messages:[]};function takeQueuedInput(session){let admittedBefore=session.externalAdmission.list().pending,cleared=session.clearQueue({abortWillFollow:!0}),stillAdmitted=new Set(session.externalAdmission.list().pending);return{deliveries:admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId)),user_messages:cleared.ordered.map(queued=>queued.text)}}async function abortAndSettle(port,sessionId,session){session.abortBash();let stopStarts=session.subscribe(event=>{event.type==="agent_start"&&session.abort()}),deadline,expired=new Promise(resolve=>{deadline=setTimeout(resolve,1e4)});try{await Promise.race([Promise.allSettled([session.abort().then(()=>session.waitForIdle()),port.otherRequestsSettled(sessionId),...port.pendingPrompts(sessionId)]),expired])}finally{clearTimeout(deadline),stopStarts()}}var SESSION_RELEASED_ENTRY_TYPE="session_released",RELEASED_ADMISSION_CLOSED="release_session handed this session to another runtime; deliver there instead (admission is closed here)",RELEASE_QUEUED_HINT="queued user input is still owed a turn; release with interrupt: true to take it out and receive it in dropped.user_messages";async function releaseSession(port,command){if(command.reason!=="takeover")return refusal2(command.id,RPC_ERROR_INVALID_RELEASE_REASON);if(port.draining())return refusal2(command.id,RPC_ERROR_HOST_DRAINING);let first=releasable(port,command,void 0);if(!("session"in first))return first;let busy=busySignals(port,command.sessionId,first.session),interrupted=busy.length>0;if(interrupted&&command.interrupt!==!0)return refusal2(command.id,busyCode(busy),{attachments:first.attachments,...busyData(busy)});let admission=first.session.externalAdmission,dropped=NOTHING_DROPPED,answer2;try{interrupted&&(admission.close(RELEASED_ADMISSION_CLOSED),dropped=takeQueuedInput(first.session),await abortAndSettle(port,command.sessionId,first.session));let manager=first.session.sessionManager;return manager.isTranscriptFlushed()||await manager.persistHeaderNow(),answer2=await claimAndRelease(port,command,interrupted,dropped),answer2}catch(cause){return answer2=refusal2(command.id,RPC_ERROR_RELEASE_FAILED,{detail:cause instanceof Error?cause.message:String(cause),...interrupted?{interrupted:!0,dropped}:{}}),answer2}finally{answer2?.success!==!0&&admission.reopen()}}async function claimAndRelease(port,command,interrupted,dropped){let taken=interrupted?{interrupted:!0,dropped}:void 0,ready=releasable(port,command,taken);if(!("session"in ready))return ready;let stillBusy=busySignals(port,command.sessionId,ready.session);if(stillBusy.length>0)return refusal2(command.id,busyCode(stillBusy),{attachments:ready.attachments,...busyData(stillBusy),interrupted,...taken});let admission=ready.session.externalAdmission;admission.close(RELEASED_ADMISSION_CLOSED);try{ready.session.sessionManager.appendCustomEntry(SESSION_RELEASED_ENTRY_TYPE,{reason:command.reason,interrupted,attachments:ready.attachments,host_instance:port.hostInstance??null,released_at:new Date().toISOString()})}catch(cause){throw admission.reopen(),cause}return await port.tearDown(command.sessionId,ready.sessionPath)?{id:command.id,type:"response",command:"release_session",success:!0,data:{released:!0,session_path:ready.sessionPath,attachments:ready.attachments,dropped}}:refusal2(command.id,RPC_ERROR_SESSION_CLOSING,taken)}function busySignals(port,sessionId,session){let activity=session.activitySnapshot,signals=[];return activity.isStreaming&&signals.push("turn"),port.pendingPrompts(sessionId).length>0&&signals.push("prompt"),session.pendingMessageCount>0&&signals.push("queued"),session.externalAdmission.list().pending.length>0&&signals.push("delivery"),activity.isBashRunning&&signals.push("bash"),activity.isCompacting&&signals.push("compaction"),activity.hasSessionWork&&signals.push("session_work"),signals.length===0&&isHandoffBusy(activity)&&signals.push("activity"),port.otherRequests(sessionId)>0&&signals.push("request"),signals}function busyData(signals){return signals.includes("queued")?{busy:signals,retry_with:{interrupt:!0},hint:RELEASE_QUEUED_HINT}:{busy:signals}}function busyCode(signals){return signals.some(signal=>signal==="turn"||signal==="prompt"||signal==="queued"||signal==="delivery")?RPC_ERROR_TURN_ACTIVE:RPC_ERROR_SESSION_BUSY}function releasable(port,command,taken){let refuse2=(code,data)=>refusal2(command.id,code,data||taken?{...data,...taken}:void 0),entry;try{entry=port.lookup(command.sessionId)}catch(cause){return refuse2(port.code(cause))}if(entry.state!=="open")return refuse2(RPC_ERROR_SESSION_CLOSING);let session=entry.runtime?.session;if(session===void 0)return refuse2(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"worker_runtime"});let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?refuse2(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"no_session_file"}):entry.attachments>0&&command.force!==!0?refuse2(RPC_ERROR_ATTACHED,{attachments:entry.attachments}):{session,sessionPath,attachments:entry.attachments}}function refusal2(id,code,data){return{id,type:"response",command:"release_session",success:!1,error:code,...data&&{errorCode:code,errorData:data}}}function liveStatus(runtime,fanout){return fanout.pendingQuestions>0||runtime.pendingQuestions>0?"waiting_input":runtime.isCompacting?"compacting":runtime.isStreaming?"running":"idle"}function statusOf(entry,runtime,fanout,terminal){if(terminal!==void 0)return terminal.status;switch(entry.state){case"opening":return"opening";case"closing":case"quarantined":case"closed":return"closed";case"open":return runtime===void 0?"opening":liveStatus(runtime,fanout);default:{let exhaustive=entry.state;throw new Error(`unexpected session state ${String(exhaustive)}`)}}}function deriveSessionStatus(entry,runtime,fanout,terminal,cause){let status=statusOf(entry,runtime,fanout,terminal),reason=terminal?.reason??(status==="idle"&&cause==="abort"?"aborted":void 0);return{status,...reason!==void 0?{reason}:{},kind:entry.kind,cwd:entry.cwd,attachments:Math.max(0,entry.attachments),...entry.durableSessionId!==void 0?{durableSessionId:entry.durableSessionId}:{},...entry.sessionPath!==void 0?{sessionPath:entry.sessionPath}:{},...entry.name!==void 0?{name:entry.name}:{},...runtime?.model!==void 0?{model:{provider:runtime.model.provider,id:runtime.model.id}}:{},...runtime?.thinkingLevel!==void 0?{thinkingLevel:runtime.thinkingLevel}:{},pendingQueue:{steering:runtime?.steering??0,followUp:runtime?.followUp??0},context:entry.context}}function terminalOfLifecycle(record){let reason=typeof record.reason=="string"?record.reason:void 0;if(record.type==="session_parked")return{status:"unloaded",reason:reason==="unloaded"?"unload_session":"idle"};if(record.type==="session_closed")return reason==="handoff_parked"?{status:"unloaded",reason:"handoff"}:reason===void 0?{status:"closed"}:{status:"closed",reason}}function causeOfRecord(record){switch(record.type){case"agent_start":return"prompt";case"agent_end":return"agent_end";case"agent_idle":return"agent_idle";case"session_abort":return"abort";case"queue_update":return"queue";case"model_changed":case"thinking_level_changed":return"set_model";case"session_replaced":return"replace";case"session_parked":return"park";case"session_closed":return"close";case"question_resolved":return"question";case"extension_ui_request":return record.method==="question"?"question":void 0;case"compaction_start":case"compaction_end":return"compaction";default:return}}var RECORD_TYPE_PATTERN=/^[a-z][a-z0-9_]{0,63}$/;function refusal3(reason,action){return{refusal:{reason,action}}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseSelector(value){if(value===void 0||value==="all")return{selector:{kind:"all"}};let action='send sessions: "all", { ids: [<sessionId | durableSessionId | sessionPath>] } or { childrenOf: <durableSessionId> }';if(!isRecord2(value))return refusal3('sessions must be "all" or an object',action);if("ids"in value&&!("childrenOf"in value)){let ids=value.ids;return!Array.isArray(ids)||ids.length===0||ids.length>1024?refusal3("sessions.ids must be a non-empty array of at most 1024 strings",action):ids.every(id=>typeof id=="string"&&id.length>0)?{selector:{kind:"ids",ids:new Set(ids)}}:refusal3("every sessions.ids entry must be a non-empty string",action)}if("childrenOf"in value&&!("ids"in value)){let parent=value.childrenOf;return typeof parent!="string"||parent.length===0?refusal3("sessions.childrenOf must be a non-empty durable session id",action):{selector:{kind:"childrenOf",parent}}}return refusal3("sessions must name exactly one of ids or childrenOf",action)}function parseMirror(value){if(value===void 0||value==="none")return{mirror:{kind:"none"}};if(value==="all")return{mirror:{kind:"all"}};let action='send mirror: "none", "all" or an array of record types such as ["message_update"]';return!Array.isArray(value)||value.length===0||value.length>64?refusal3('mirror must be "none", "all" or a non-empty array of at most 64 record types',action):value.every(type=>typeof type=="string"&&RECORD_TYPE_PATTERN.test(type))?{mirror:{kind:"types",types:new Set(value)}}:refusal3(`every mirror entry must be a record type matching ${RECORD_TYPE_PATTERN.source}`,action)}function optionalBoolean(value,field){return value===void 0||typeof value=="boolean"?value:{reason:`${field} must be a boolean`,action:`send ${field}: true or false, or omit it`}}function parseSubscription(request){let selector=parseSelector(request.sessions);if("refusal"in selector)return selector;let mirror=parseMirror(request.mirror);if("refusal"in mirror)return mirror;let includeWorkers=optionalBoolean(request.include_workers,"include_workers");if(typeof includeWorkers=="object")return{refusal:includeWorkers};let includeContext=optionalBoolean(request.include_context,"include_context");if(typeof includeContext=="object")return{refusal:includeContext};let effects=optionalBoolean(request.effects,"effects");return typeof effects=="object"?{refusal:effects}:{options:{selector:selector.selector,includeWorkers:includeWorkers??selector.selector.kind==="childrenOf",includeContext:includeContext??!1,mirror:mirror.mirror,effects:effects??selector.selector.kind==="childrenOf"}}}function subscriptionMatches(options,sessionId,entry){if(entry.kind==="worker"&&!options.includeWorkers)return!1;let selector=options.selector;switch(selector.kind){case"all":return!0;case"ids":return selector.ids.has(sessionId)||entry.durableSessionId!==void 0&&selector.ids.has(entry.durableSessionId)||entry.sessionPath!==void 0&&selector.ids.has(entry.sessionPath);case"childrenOf":{let lineage=entry.openContext??entry.context;return(lineage.parent_session_id??lineage.root_session_id)===selector.parent}default:{let exhaustive=selector;throw new Error(`unexpected selector ${String(exhaustive)}`)}}}function mirrorsRecord(mirror,recordType){switch(mirror.kind){case"none":return!1;case"all":return!0;case"types":return mirror.types.has(recordType);default:{let exhaustive=mirror;throw new Error(`unexpected mirror ${String(exhaustive)}`)}}}var MAX_SUBSCRIPTIONS_PER_CONNECTION=64,SessionStatusStream=class{constructor(delivery){this.subscriptions=new Map,this.pendings=new Map,this.terminals=new Map,this.lastViews=new Map,this.lastChanges=new Map,this.nextSubscription=0,this.delivery=delivery}setSource(source){this.source=source}setLastEffectProvider(provider){this.lastEffect=provider}get size(){return this.subscriptions.size}connectionSize(connectionId){let count=0;for(let pending of this.pendings.values())pending.connectionId===connectionId&&count++;for(let subscription of this.subscriptions.values())subscription.connectionId===connectionId&&count++;return count}subscribe(connectionId,options){let pending={id:`sub-${++this.nextSubscription}`,connectionId,options,seq:0,lines:[]};this.pendings.set(pending.id,pending);let snapshot=[];for(let sessionId of this.source?.sessionIds()??[]){let view=this.currentView(sessionId);if(view===void 0||!subscriptionMatches(options,sessionId,view.entry))continue;let derived=this.derive(sessionId,view);snapshot.push(this.recordFor(pending,sessionId,derived,this.lastChangeOf(sessionId)))}return{subscriptionId:pending.id,snapshot,seq:pending.seq}}activate(subscriptionId){let pending=this.pendings.get(subscriptionId);if(pending===void 0)return;this.pendings.delete(subscriptionId);let subscription={id:pending.id,connectionId:pending.connectionId,options:pending.options,seq:pending.seq};this.subscriptions.set(subscription.id,subscription);for(let line of pending.lines)this.delivery.enqueue(subscription.connectionId,line);pending.lines.length=0}unsubscribe(connectionId,subscriptionId){let pending=this.pendings.get(subscriptionId);return pending!==void 0?pending.connectionId!==connectionId?!1:(this.pendings.delete(subscriptionId),!0):this.subscriptions.get(subscriptionId)?.connectionId!==connectionId?!1:(this.subscriptions.delete(subscriptionId),!0)}dropConnection(connectionId){for(let[id,pending]of this.pendings)pending.connectionId===connectionId&&this.pendings.delete(id);for(let[id,subscription]of this.subscriptions)subscription.connectionId===connectionId&&this.subscriptions.delete(id)}publish(sessionId,cause,by,contextOnly=!1){let change={at:(this.delivery.now?.()??new Date).toISOString(),cause,by};if(this.lastChanges.set(sessionId,change),this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let derived=this.derive(sessionId,view,cause);for(let pending of this.pendings.values())contextOnly&&!pending.options.includeContext||subscriptionMatches(pending.options,sessionId,view.entry)&&(pending.seq+=1,pending.lines.push(serializeJsonLine(this.recordFor(pending,sessionId,derived,change))));for(let subscription of this.subscriptions.values()){if(contextOnly&&!subscription.options.includeContext||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let record=this.recordFor(subscription,sessionId,derived,change);this.delivery.enqueue(subscription.connectionId,serializeJsonLine(record))||this.subscriptions.delete(subscription.id)}}publishEffect(sessionId,status){if(this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let at=status.updatedAt??status.acceptedAt??(this.delivery.now?.()??new Date).toISOString();for(let pending of this.pendings.values())!pending.options.effects||!subscriptionMatches(pending.options,sessionId,view.entry)||(pending.seq+=1,pending.lines.push(serializeJsonLine(effectStatusRecord(pending,sessionId,status,at))));for(let subscription of this.subscriptions.values()){if(!subscription.options.effects||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let line=serializeJsonLine(effectStatusRecord(subscription,sessionId,status,at));this.delivery.enqueue(subscription.connectionId,line)||this.subscriptions.delete(subscription.id)}}seal(sessionId,terminal,cause,by){this.terminals.set(sessionId,terminal),this.publish(sessionId,cause,by)}forget(sessionId){this.terminals.delete(sessionId),this.lastViews.delete(sessionId),this.lastChanges.delete(sessionId)}mirrorTargets(sessionId,recordType){let subscriptions=[...this.pendings.values(),...this.subscriptions.values()].filter(subscription=>mirrorsRecord(subscription.options.mirror,recordType));if(subscriptions.length===0)return[];let entry=this.source?.entryView(sessionId)??this.lastViews.get(sessionId)?.entry;if(entry===void 0)return[];let targets=new Set;for(let subscription of subscriptions)subscriptionMatches(subscription.options,sessionId,entry)&&targets.add(subscription.connectionId);return[...targets]}matchingConnections(sessionId){let view=this.currentView(sessionId),matches=new Map;if(view===void 0)return matches;for(let subscription of this.subscriptions.values())subscriptionMatches(subscription.options,sessionId,view.entry)&&matches.set(subscription.connectionId,(matches.get(subscription.connectionId)??!1)||subscription.options.includeContext);return matches}currentView(sessionId){let live=this.source?.view(sessionId);return live!==void 0&&this.lastViews.set(sessionId,live),live??this.lastViews.get(sessionId)}derive(sessionId,view,cause){return deriveSessionStatus(view.entry,view.runtime,{pendingQuestions:this.delivery.pendingQuestions(sessionId)},this.terminals.get(sessionId),cause)}lastChangeOf(sessionId){return this.lastChanges.get(sessionId)??{at:(this.delivery.now?.()??new Date).toISOString(),cause:"open",by:"host"}}recordFor(subscription,sessionId,derived,lastChange){let{context,...rest}=derived,lastEffect=this.lastEffect?.(sessionId);return{type:"session_status",subscriptionId:subscription.id,seq:subscription.seq,sessionId,...rest,...subscription.options.includeContext?{context}:{},...lastEffect!==void 0?{lastEffect}:{},lastChange}}};function refusal4(id,command,code,detail){return{id,type:"response",command,success:!1,error:`${code}: ${detail.reason}`,errorCode:code,errorData:{reason:detail.reason,action:detail.action}}}function answerSubscribeSessions(command,connectionId,stream){if(connectionId===void 0)return{answer:refusal4(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity to deliver a subscription to",action:"connect to the host socket (senpi --mode rpc --listen) and subscribe there"})};if(stream.connectionSize(connectionId)>=MAX_SUBSCRIPTIONS_PER_CONNECTION)return{answer:refusal4(command.id,command.type,RPC_ERROR_SUBSCRIPTION_LIMIT,{reason:`this connection already holds ${MAX_SUBSCRIPTIONS_PER_CONNECTION} subscriptions`,action:"unsubscribe_sessions the ones you no longer read, then subscribe again"})};let parsed=parseSubscription(command);if("refusal"in parsed)return{answer:refusal4(command.id,command.type,RPC_ERROR_INVALID_SUBSCRIPTION,parsed.refusal)};let subscribed=stream.subscribe(connectionId,parsed.options);return{answer:{id:command.id,type:"response",command:"subscribe_sessions",success:!0,data:{subscriptionId:subscribed.subscriptionId,snapshot:subscribed.snapshot,seq:subscribed.seq,hostGeneration:String(hostGeneration(process.env)),hostInstanceId:hostInstanceId()}},activate:subscribed.subscriptionId}}function answerUnsubscribeSessions(command,connectionId,stream){return connectionId===void 0?refusal4(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity holding any subscription",action:"connect to the host socket (senpi --mode rpc --listen) and manage subscriptions there"}):typeof command.subscriptionId=="string"&&stream.unsubscribe(connectionId,command.subscriptionId)?{id:command.id,type:"response",command:"unsubscribe_sessions",success:!0}:refusal4(command.id,command.type,RPC_ERROR_UNKNOWN_SUBSCRIPTION,{reason:"this connection holds no subscription with that id",action:"send the subscriptionId your subscribe_sessions answer returned, on the same connection"})}function notAttachedRefusal(command){return refusal4(command.id,command.type,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this connection is not attached to that session",action:"attach first with open_session { sessionPath }, then patch its context"})}function answerSetSessionContext(command,entry,stream){let applied=applyContextPatch(entry.contextOverlay,command.patch);return"refusal"in applied?refusal4(command.id,command.type,RPC_ERROR_INVALID_SESSION_CONTEXT,applied.refusal):(entry.contextOverlay=applied.overlay,stream.publish(command.sessionId,"context","client",!0),{id:command.id,type:"response",command:"set_session_context",success:!0,data:{context:publishedSessionContext(entry.context,entry.contextOverlay)}})}function modelOf(model){return model===void 0?void 0:{provider:model.provider,id:model.id}}function runtimeView(entry){let session=entry.runtime?.session;if(session!==void 0){let model2=modelOf(session.model);return{isStreaming:session.isStreaming===!0,isCompacting:session.isCompacting===!0,...model2!==void 0?{model:model2}:{},...session.thinkingLevel!==void 0?{thinkingLevel:session.thinkingLevel}:{},steering:typeof session.getSteeringMessages=="function"?session.getSteeringMessages().length:0,followUp:typeof session.getFollowUpMessages=="function"?session.getFollowUpMessages().length:0,pendingQuestions:sessionQuestionBridges.get(session)?.pendingQuestions()?.length??0}}let state=entry.worker?.snapshot?.state;if(state===void 0)return;let model=modelOf(state.model??void 0);return{isStreaming:state.isStreaming,isCompacting:state.isCompacting,...model!==void 0?{model}:{},...state.thinkingLevel!==void 0?{thinkingLevel:state.thinkingLevel}:{},steering:state.steering.length,followUp:state.followUp.length,pendingQuestions:state.pendingQuestions?.length??0}}function entryView(entry){let session=entry.runtime?.session,state=entry.worker?.snapshot?.state,durableSessionId=session?.sessionId??state?.sessionId??entry.durableSessionId,sessionPath=session?.sessionFile??state?.sessionFile??entry.sessionPath,name=session?.sessionManager.getSessionName()??state?.sessionName;return{state:entry.state,kind:entry.kind,cwd:entry.cwd,attachments:entry.attachments,...durableSessionId!==void 0?{durableSessionId}:{},...sessionPath!==void 0?{sessionPath}:{},...name!==void 0?{name}:{},context:publishedSessionContext(entry.context,entry.contextOverlay),openContext:entry.context}}function registryStatusSource(registry){return{sessionIds:()=>registry.list().map(row=>row.sessionId),entryView:sessionId=>{let entry=registry.peek(sessionId);return entry===void 0?void 0:entryView(entry)},view:sessionId=>{let entry=registry.peek(sessionId);if(entry===void 0)return;let runtime=runtimeView(entry);return runtime===void 0?{entry:entryView(entry)}:{entry:entryView(entry),runtime}}}}var DETACHED_RETIREMENT_GRACE_MS=5e3;function selectSweepEvictions(registry,now,idleEvictionMs,hasPendingRequest=()=>!1){let idle=[],orphaned=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open")continue;let entry=registry.peek(sessionId);if(!entry)continue;if(entry.attachments===0&&sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)){orphaned.push(sessionId);continue}if(!Number.isFinite(idleEvictionMs)||hasPendingRequest(sessionId))continue;let session=entry.runtime?.session;if(entry.worker?.busy||session?.isSessionBusy){entry.lastCommandAt=now;continue}if(entry.attachments>0){now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId);continue}if(entry.kind==="worker"&&entry.retainOnDisconnect&&session?.sessionManager.isTranscriptFlushed()){if(session.pendingMessageCount>0||session.externalAdmission.list().pending.length>0)continue;if(entry.detachedAt!==void 0){if(now-entry.detachedAt<DETACHED_RETIREMENT_GRACE_MS)continue;idle.push(sessionId);continue}}now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId)}return{idle,orphaned}}var CHILD_TASK_SOURCE=/^senpi-task/,ACTIONS={extension_work:"let the named work finish, or unload with force: true (it is stopped, not resumed on reopen)",turn_active:"wait for the turn to end, or unload with interrupt: true to stop it first",work_pending:"wait for the work to finish, or unload with interrupt: true",children_live:'wait for the child tasks, or unload with children: "detach" to leave them running',attached:"ask the other clients to detach, or unload with force: true (they receive session_parked)"};async function unloadSession(port,command){if(port.draining())return answer(command,refused({reason:"host_draining",detail:"this host is draining and parks every session itself"}));let first=loaded(port,command.sessionId);if("reason"in first)return answer(command,refused(first));let{effectId}=command;if(effectId!==void 0){let begun=await beginEffect({session:first.session,by:port.by,sessionId:command.sessionId},"unload",{...command,effectId});if(!isEffectBegin(begun))return begun;if("replay"in begun)return answer(command,{outcome:begun.replay.state==="failed"?"refused":"unloaded",...refusalFields(begun.replay.outcome),...effectAnswer(begun.replay,command.sessionId,!0)})}let blocked=blockers(port,command,first.session,first.durableSessionId),standing=blocked.find(refusal5=>!interruptible(refusal5)||command.interrupt!==!0);return standing!==void 0?fail(command,first.session,standing):(blocked.length>0&&await abortAndSettle(port,command.sessionId,first.session),claimAndUnload(port,command))}async function claimAndUnload(port,command){let ready=loaded(port,command.sessionId);if("reason"in ready)return answer(command,refused(ready));let stillBlocked=blockers(port,command,ready.session,ready.durableSessionId);if(stillBlocked.length>0)return fail(command,ready.session,stillBlocked[0]);command.clearQueue===!0&&ready.session.clearQueue();let effect=command.effectId===void 0?void 0:EffectLedger.forSession(ready.session).transition(command.effectId,"done",{disposition:"unloaded"});return await port.tearDown(command.sessionId,ready.sessionPath)?answer(command,{outcome:"unloaded",sessionPath:ready.sessionPath,...effect===void 0?{}:effectAnswer(effect,command.sessionId)}):answer(command,{outcome:"refused",reason:"session_closing",detail:"another close of this session finished first"})}function interruptible(refusal5){return refusal5.reason==="turn_active"||refusal5.reason==="work_pending"}function blockers(port,command,session,durableSessionId){let found=[],activity=session.activitySnapshot,running=[activity.isStreaming&&"an agent run",port.pendingPrompts(command.sessionId).length>0&&"a prompt about to start",activity.isCompacting&&"compaction",activity.hasSessionWork&&"session work"].filter(label=>typeof label=="string");running.length>0&&found.push({reason:"turn_active",detail:running.join(", "),action:ACTIONS.turn_active});let pending=[activity.isBashRunning&&"a bash command",session.externalAdmission.list().pending.length>0&&"an admitted delivery not yet written",port.otherRequests(command.sessionId)>0&&"another request for this session"].filter(label=>typeof label=="string");pending.length>0&&found.push({reason:"work_pending",detail:pending.join(", "),action:ACTIONS.work_pending});let sources=session.activeWakeSources,childSources=sources.filter(source=>CHILD_TASK_SOURCE.test(source)),otherSources=sources.filter(source=>!CHILD_TASK_SOURCE.test(source));otherSources.length>0&&command.force!==!0&&found.push({reason:"extension_work",detail:`work published by ${otherSources.join(", ")}`,action:ACTIONS.extension_work});let childSessions=port.openChildSessions(durableSessionId);if(command.children!=="detach"&&(childSources.length>0||childSessions>0)){let what=childSessions>0?`${childSessions} child session(s) open on this host`:"child tasks still working";found.push({reason:"children_live",detail:what,action:ACTIONS.children_live})}let others=port.otherAttachments(command.sessionId);return others>0&&command.force!==!0&&found.push({reason:"attached",detail:`${others} other client(s) attached`,action:ACTIONS.attached}),found}function loaded(port,sessionId){let entry;try{entry=port.lookup(sessionId)}catch(cause){return{reason:"unsupported",detail:port.code(cause)}}if(entry.state!=="open")return{reason:"session_closing",detail:"the session is already closing"};let session=entry.runtime?.session;if(session===void 0)return{reason:"unsupported",detail:"a worker isolate owns this session's runtime"};let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?{reason:"unsupported",detail:"the session has no file to reopen it by",action:"send a prompt first so the session is written, or close it instead"}:{session,sessionPath,durableSessionId:session.sessionManager.getSessionId()}}function fail(command,session,refusal5){if(command.effectId===void 0)return answer(command,refused(refusal5));let status=EffectLedger.forSession(session).transition(command.effectId,"failed",{outcome:{kind:"refused",reason:refusal5.reason,detail:refusal5.detail,...refusal5.action===void 0?{}:{action:refusal5.action}}});return answer(command,{...refused(refusal5),...effectAnswer(status,command.sessionId)})}function refusalFields(outcome){return outcome?.reason===void 0?{}:{reason:outcome.reason,...outcome.detail===void 0?{}:{detail:outcome.detail},...outcome.action===void 0?{}:{action:outcome.action}}}function refused(refusal5){return{outcome:"refused",reason:refusal5.reason,detail:refusal5.detail,...refusal5.action===void 0?{}:{action:refusal5.action}}}function answer(command,data){return{id:command.id,type:"response",command:"unload_session",success:!0,data}}var DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>this.routingIdOf(session)!==void 0,flush:(session,statuses)=>{let sessionId=this.routingIdOf(session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}setHostMemoryView(view){this.hostMemoryView=view}sessionMemory(sessionId){let view=this.hostMemoryView;if(view===void 0)return{main_heap_bytes:0,kernel_heap_bytes:0,kernel_count:0};let kernels=view.kernels().filter(kernel=>kernel.sessionId===sessionId),kernelHeapBytes=0;for(let kernel of kernels)kernelHeapBytes+=kernel.liveBytes;return{main_heap_bytes:view.mainHeapBytes(),kernel_heap_bytes:kernelHeapBytes,kernel_count:kernels.length}}beginDrain(){this.draining=!0,this.stopSweep(),this.drainTimer===void 0&&!this.drainExitRequested&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()),this.sweepDrain()}sweepDrain(){if(this.activeRequests.has(void 0))return;let verdicts=readDrainVerdicts(this.registry,sessionId=>this.activeRequests.has(sessionId));if(verdicts){for(let sessionId of verdicts.gone)this.parkForHandoff(sessionId,"session_dir_removed");for(let sessionId of verdicts.park)this.parkForHandoff(sessionId,"handoff_parked");this.registry.size>0||this.handoffParks>0||this.finalizations.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),!this.drainExitRequested&&(this.drainExitRequested=!0,this.onEmptyExit?.()))}}parkForHandoff(sessionId,reason){this.handoffClosed.add(sessionId),this.handoffParks++,this.evictIdleSession(sessionId,reason).catch(cause=>{process.stderr.write(`senpi rpc handoff park ${sessionId} failed: ${String(cause)}
16
+ `)){let row=/^\s*(\d+)\s+(.+)$/.exec(line);if(!row)continue;let start=processStartTimeMs(row[2]);start!==void 0&&starts.set(Number(row[1]),start)}resolve(starts)})})}function sessionHeldCheck(resolveDaemonPids){let daemonPids,processStarts,pidStarts=new Map,observedStarts=new Map;return async(sessionFile,sessionId)=>{let holders=await foreignSessionHolders(sessionFile,sessionId,{readProcessStartMs:pid=>{let probe=pidStarts.get(pid);return probe||(probe=(async()=>{process.platform!=="linux"&&(processStarts??=readProcessStarts());let start=(await processStarts)?.get(pid)??await readProcessStartMs(pid);return observedStarts.set(pid,start),start})(),pidStarts.set(pid,probe)),probe}});if(holders.length===0)return;daemonPids??=resolveDaemonPids?.(observedStarts)??Promise.resolve([]);let family=await daemonPids,foreign=holders.filter(holder=>!family.includes(holder.pid));if(foreign.length>0)throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD,void 0,{holders:foreign.map(({pid,cwd,host_socket,host_instance})=>({pid,...cwd===void 0?{}:{cwd},...host_socket===void 0?{}:{host_socket},...host_instance===void 0?{}:{host_instance}}))})}}async function dispatchSessionBinding(command,entry,binding,acknowledgePrompt,daemonPids){if(!binding)throw new RpcSessionRegistryError("unknown_session");if(!READ_ONLY_OR_CONTROL.has(command.type)){let assertSessionNotHeld=sessionHeldCheck(daemonPids),state=entry.worker?.snapshot?.state;await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),"sessionPath"in command&&await assertSessionNotHeld(command.sessionPath)}command.type==="prompt"&&acknowledgePrompt(),await binding.handle(command)}var NOTHING_DROPPED={deliveries:[],user_messages:[]};function takeQueuedInput(session){let admittedBefore=session.externalAdmission.list().pending,cleared=session.clearQueue({abortWillFollow:!0}),stillAdmitted=new Set(session.externalAdmission.list().pending);return{deliveries:admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId)),user_messages:cleared.ordered.map(queued=>queued.text)}}async function abortAndSettle(port,sessionId,session){session.abortBash();let stopStarts=session.subscribe(event=>{event.type==="agent_start"&&session.abort()}),deadline,expired=new Promise(resolve=>{deadline=setTimeout(resolve,1e4)});try{await Promise.race([Promise.allSettled([session.abort().then(()=>session.waitForIdle()),port.otherRequestsSettled(sessionId),...port.pendingPrompts(sessionId)]),expired])}finally{clearTimeout(deadline),stopStarts()}}var SESSION_RELEASED_ENTRY_TYPE="session_released",RELEASED_ADMISSION_CLOSED="release_session handed this session to another runtime; deliver there instead (admission is closed here)",RELEASE_QUEUED_HINT="queued user input is still owed a turn; release with interrupt: true to take it out and receive it in dropped.user_messages";async function releaseSession(port,command){if(command.reason!=="takeover")return refusal2(command.id,RPC_ERROR_INVALID_RELEASE_REASON);if(port.draining())return refusal2(command.id,RPC_ERROR_HOST_DRAINING);let first=releasable(port,command,void 0);if(!("session"in first))return first;let busy=busySignals(port,command.sessionId,first.session),interrupted=busy.length>0;if(interrupted&&command.interrupt!==!0)return refusal2(command.id,busyCode(busy),{attachments:first.attachments,...busyData(busy)});let admission=first.session.externalAdmission,dropped=NOTHING_DROPPED,answer2;try{interrupted&&(admission.close(RELEASED_ADMISSION_CLOSED),dropped=takeQueuedInput(first.session),await abortAndSettle(port,command.sessionId,first.session));let manager=first.session.sessionManager;return manager.isTranscriptFlushed()||await manager.persistHeaderNow(),answer2=await claimAndRelease(port,command,interrupted,dropped),answer2}catch(cause){return answer2=refusal2(command.id,RPC_ERROR_RELEASE_FAILED,{detail:cause instanceof Error?cause.message:String(cause),...interrupted?{interrupted:!0,dropped}:{}}),answer2}finally{answer2?.success!==!0&&admission.reopen()}}async function claimAndRelease(port,command,interrupted,dropped){let taken=interrupted?{interrupted:!0,dropped}:void 0,ready=releasable(port,command,taken);if(!("session"in ready))return ready;let stillBusy=busySignals(port,command.sessionId,ready.session);if(stillBusy.length>0)return refusal2(command.id,busyCode(stillBusy),{attachments:ready.attachments,...busyData(stillBusy),interrupted,...taken});let admission=ready.session.externalAdmission;admission.close(RELEASED_ADMISSION_CLOSED);try{ready.session.sessionManager.appendCustomEntry(SESSION_RELEASED_ENTRY_TYPE,{reason:command.reason,interrupted,attachments:ready.attachments,host_instance:port.hostInstance??null,released_at:new Date().toISOString()})}catch(cause){throw admission.reopen(),cause}return await port.tearDown(command.sessionId,ready.sessionPath)?{id:command.id,type:"response",command:"release_session",success:!0,data:{released:!0,session_path:ready.sessionPath,attachments:ready.attachments,dropped}}:refusal2(command.id,RPC_ERROR_SESSION_CLOSING,taken)}function busySignals(port,sessionId,session){let activity=session.activitySnapshot,signals=[];return activity.isStreaming&&signals.push("turn"),port.pendingPrompts(sessionId).length>0&&signals.push("prompt"),session.pendingMessageCount>0&&signals.push("queued"),session.externalAdmission.list().pending.length>0&&signals.push("delivery"),activity.isBashRunning&&signals.push("bash"),activity.isCompacting&&signals.push("compaction"),activity.hasSessionWork&&signals.push("session_work"),signals.length===0&&isHandoffBusy(activity)&&signals.push("activity"),port.otherRequests(sessionId)>0&&signals.push("request"),signals}function busyData(signals){return signals.includes("queued")?{busy:signals,retry_with:{interrupt:!0},hint:RELEASE_QUEUED_HINT}:{busy:signals}}function busyCode(signals){return signals.some(signal=>signal==="turn"||signal==="prompt"||signal==="queued"||signal==="delivery")?RPC_ERROR_TURN_ACTIVE:RPC_ERROR_SESSION_BUSY}function releasable(port,command,taken){let refuse2=(code,data)=>refusal2(command.id,code,data||taken?{...data,...taken}:void 0),entry;try{entry=port.lookup(command.sessionId)}catch(cause){return refuse2(port.code(cause))}if(entry.state!=="open")return refuse2(RPC_ERROR_SESSION_CLOSING);let session=entry.runtime?.session;if(session===void 0)return refuse2(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"worker_runtime"});let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?refuse2(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"no_session_file"}):entry.attachments>0&&command.force!==!0?refuse2(RPC_ERROR_ATTACHED,{attachments:entry.attachments}):{session,sessionPath,attachments:entry.attachments}}function refusal2(id,code,data){return{id,type:"response",command:"release_session",success:!1,error:code,...data&&{errorCode:code,errorData:data}}}function liveStatus(runtime,fanout){return fanout.pendingQuestions>0||runtime.pendingQuestions>0?"waiting_input":runtime.isCompacting?"compacting":runtime.isStreaming?"running":"idle"}function statusOf(entry,runtime,fanout,terminal){if(terminal!==void 0)return terminal.status;switch(entry.state){case"opening":return"opening";case"closing":case"quarantined":case"closed":return"closed";case"open":return runtime===void 0?"opening":liveStatus(runtime,fanout);default:{let exhaustive=entry.state;throw new Error(`unexpected session state ${String(exhaustive)}`)}}}function deriveSessionStatus(entry,runtime,fanout,terminal,cause){let status=statusOf(entry,runtime,fanout,terminal),reason=terminal?.reason??(status==="idle"&&cause==="abort"?"aborted":void 0);return{status,...reason!==void 0?{reason}:{},kind:entry.kind,cwd:entry.cwd,attachments:Math.max(0,entry.attachments),...entry.durableSessionId!==void 0?{durableSessionId:entry.durableSessionId}:{},...entry.sessionPath!==void 0?{sessionPath:entry.sessionPath}:{},...entry.name!==void 0?{name:entry.name}:{},...runtime?.model!==void 0?{model:{provider:runtime.model.provider,id:runtime.model.id}}:{},...runtime?.thinkingLevel!==void 0?{thinkingLevel:runtime.thinkingLevel}:{},pendingQueue:{steering:runtime?.steering??0,followUp:runtime?.followUp??0},context:entry.context}}function terminalOfLifecycle(record){let reason=typeof record.reason=="string"?record.reason:void 0;if(record.type==="session_parked")return{status:"unloaded",reason:reason==="unloaded"?"unload_session":"idle"};if(record.type==="session_closed")return reason==="handoff_parked"?{status:"unloaded",reason:"handoff"}:reason===void 0?{status:"closed"}:{status:"closed",reason}}function causeOfRecord(record){switch(record.type){case"agent_start":return"prompt";case"agent_end":return"agent_end";case"agent_idle":return"agent_idle";case"session_abort":return"abort";case"queue_update":return"queue";case"model_changed":case"thinking_level_changed":return"set_model";case"session_replaced":return"replace";case"session_parked":return"park";case"session_closed":return"close";case"question_resolved":return"question";case"extension_ui_request":return record.method==="question"?"question":void 0;case"compaction_start":case"compaction_end":return"compaction";default:return}}var RECORD_TYPE_PATTERN=/^[a-z][a-z0-9_]{0,63}$/;function refusal3(reason,action){return{refusal:{reason,action}}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseSelector(value){if(value===void 0||value==="all")return{selector:{kind:"all"}};let action='send sessions: "all", { ids: [<sessionId | durableSessionId | sessionPath>] } or { childrenOf: <durableSessionId> }';if(!isRecord2(value))return refusal3('sessions must be "all" or an object',action);if("ids"in value&&!("childrenOf"in value)){let ids=value.ids;return!Array.isArray(ids)||ids.length===0||ids.length>1024?refusal3("sessions.ids must be a non-empty array of at most 1024 strings",action):ids.every(id=>typeof id=="string"&&id.length>0)?{selector:{kind:"ids",ids:new Set(ids)}}:refusal3("every sessions.ids entry must be a non-empty string",action)}if("childrenOf"in value&&!("ids"in value)){let parent=value.childrenOf;return typeof parent!="string"||parent.length===0?refusal3("sessions.childrenOf must be a non-empty durable session id",action):{selector:{kind:"childrenOf",parent}}}return refusal3("sessions must name exactly one of ids or childrenOf",action)}function parseMirror(value){if(value===void 0||value==="none")return{mirror:{kind:"none"}};if(value==="all")return{mirror:{kind:"all"}};let action='send mirror: "none", "all" or an array of record types such as ["message_update"]';return!Array.isArray(value)||value.length===0||value.length>64?refusal3('mirror must be "none", "all" or a non-empty array of at most 64 record types',action):value.every(type=>typeof type=="string"&&RECORD_TYPE_PATTERN.test(type))?{mirror:{kind:"types",types:new Set(value)}}:refusal3(`every mirror entry must be a record type matching ${RECORD_TYPE_PATTERN.source}`,action)}function optionalBoolean(value,field){return value===void 0||typeof value=="boolean"?value:{reason:`${field} must be a boolean`,action:`send ${field}: true or false, or omit it`}}function parseSubscription(request){let selector=parseSelector(request.sessions);if("refusal"in selector)return selector;let mirror=parseMirror(request.mirror);if("refusal"in mirror)return mirror;let includeWorkers=optionalBoolean(request.include_workers,"include_workers");if(typeof includeWorkers=="object")return{refusal:includeWorkers};let includeContext=optionalBoolean(request.include_context,"include_context");if(typeof includeContext=="object")return{refusal:includeContext};let effects=optionalBoolean(request.effects,"effects");return typeof effects=="object"?{refusal:effects}:{options:{selector:selector.selector,includeWorkers:includeWorkers??selector.selector.kind==="childrenOf",includeContext:includeContext??!1,mirror:mirror.mirror,effects:effects??selector.selector.kind==="childrenOf"}}}function subscriptionMatches(options,sessionId,entry){if(entry.kind==="worker"&&!options.includeWorkers)return!1;let selector=options.selector;switch(selector.kind){case"all":return!0;case"ids":return selector.ids.has(sessionId)||entry.durableSessionId!==void 0&&selector.ids.has(entry.durableSessionId)||entry.sessionPath!==void 0&&selector.ids.has(entry.sessionPath);case"childrenOf":{let lineage=entry.openContext??entry.context;return(lineage.parent_session_id??lineage.root_session_id)===selector.parent}default:{let exhaustive=selector;throw new Error(`unexpected selector ${String(exhaustive)}`)}}}function mirrorsRecord(mirror,recordType){switch(mirror.kind){case"none":return!1;case"all":return!0;case"types":return mirror.types.has(recordType);default:{let exhaustive=mirror;throw new Error(`unexpected mirror ${String(exhaustive)}`)}}}var MAX_SUBSCRIPTIONS_PER_CONNECTION=64,SessionStatusStream=class{constructor(delivery){this.subscriptions=new Map,this.pendings=new Map,this.terminals=new Map,this.lastViews=new Map,this.lastChanges=new Map,this.nextSubscription=0,this.delivery=delivery}setSource(source){this.source=source}setLastEffectProvider(provider){this.lastEffect=provider}get size(){return this.subscriptions.size}connectionSize(connectionId){let count=0;for(let pending of this.pendings.values())pending.connectionId===connectionId&&count++;for(let subscription of this.subscriptions.values())subscription.connectionId===connectionId&&count++;return count}subscribe(connectionId,options){let pending={id:`sub-${++this.nextSubscription}`,connectionId,options,seq:0,lines:[]};this.pendings.set(pending.id,pending);let snapshot=[];for(let sessionId of this.source?.sessionIds()??[]){let view=this.currentView(sessionId);if(view===void 0||!subscriptionMatches(options,sessionId,view.entry))continue;let derived=this.derive(sessionId,view);snapshot.push(this.recordFor(pending,sessionId,derived,this.lastChangeOf(sessionId)))}return{subscriptionId:pending.id,snapshot,seq:pending.seq}}activate(subscriptionId){let pending=this.pendings.get(subscriptionId);if(pending===void 0)return;this.pendings.delete(subscriptionId);let subscription={id:pending.id,connectionId:pending.connectionId,options:pending.options,seq:pending.seq};this.subscriptions.set(subscription.id,subscription);for(let line of pending.lines)this.delivery.enqueue(subscription.connectionId,line);pending.lines.length=0}unsubscribe(connectionId,subscriptionId){let pending=this.pendings.get(subscriptionId);return pending!==void 0?pending.connectionId!==connectionId?!1:(this.pendings.delete(subscriptionId),!0):this.subscriptions.get(subscriptionId)?.connectionId!==connectionId?!1:(this.subscriptions.delete(subscriptionId),!0)}dropConnection(connectionId){for(let[id,pending]of this.pendings)pending.connectionId===connectionId&&this.pendings.delete(id);for(let[id,subscription]of this.subscriptions)subscription.connectionId===connectionId&&this.subscriptions.delete(id)}publish(sessionId,cause,by,contextOnly=!1){let change={at:(this.delivery.now?.()??new Date).toISOString(),cause,by};if(this.lastChanges.set(sessionId,change),this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let derived=this.derive(sessionId,view,cause);for(let pending of this.pendings.values())contextOnly&&!pending.options.includeContext||subscriptionMatches(pending.options,sessionId,view.entry)&&(pending.seq+=1,pending.lines.push(serializeJsonLine(this.recordFor(pending,sessionId,derived,change))));for(let subscription of this.subscriptions.values()){if(contextOnly&&!subscription.options.includeContext||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let record=this.recordFor(subscription,sessionId,derived,change);this.delivery.enqueue(subscription.connectionId,serializeJsonLine(record))||this.subscriptions.delete(subscription.id)}}publishEffect(sessionId,status){if(this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let at=status.updatedAt??status.acceptedAt??(this.delivery.now?.()??new Date).toISOString();for(let pending of this.pendings.values())!pending.options.effects||!subscriptionMatches(pending.options,sessionId,view.entry)||(pending.seq+=1,pending.lines.push(serializeJsonLine(effectStatusRecord(pending,sessionId,status,at))));for(let subscription of this.subscriptions.values()){if(!subscription.options.effects||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let line=serializeJsonLine(effectStatusRecord(subscription,sessionId,status,at));this.delivery.enqueue(subscription.connectionId,line)||this.subscriptions.delete(subscription.id)}}seal(sessionId,terminal,cause,by){this.terminals.set(sessionId,terminal),this.publish(sessionId,cause,by)}forget(sessionId){this.terminals.delete(sessionId),this.lastViews.delete(sessionId),this.lastChanges.delete(sessionId)}mirrorTargets(sessionId,recordType){let subscriptions=[...this.pendings.values(),...this.subscriptions.values()].filter(subscription=>mirrorsRecord(subscription.options.mirror,recordType));if(subscriptions.length===0)return[];let entry=this.source?.entryView(sessionId)??this.lastViews.get(sessionId)?.entry;if(entry===void 0)return[];let targets=new Set;for(let subscription of subscriptions)subscriptionMatches(subscription.options,sessionId,entry)&&targets.add(subscription.connectionId);return[...targets]}matchingConnections(sessionId){let view=this.currentView(sessionId),matches=new Map;if(view===void 0)return matches;for(let subscription of this.subscriptions.values())subscriptionMatches(subscription.options,sessionId,view.entry)&&matches.set(subscription.connectionId,(matches.get(subscription.connectionId)??!1)||subscription.options.includeContext);return matches}currentView(sessionId){let live=this.source?.view(sessionId);return live!==void 0&&this.lastViews.set(sessionId,live),live??this.lastViews.get(sessionId)}derive(sessionId,view,cause){return deriveSessionStatus(view.entry,view.runtime,{pendingQuestions:this.delivery.pendingQuestions(sessionId)},this.terminals.get(sessionId),cause)}lastChangeOf(sessionId){return this.lastChanges.get(sessionId)??{at:(this.delivery.now?.()??new Date).toISOString(),cause:"open",by:"host"}}recordFor(subscription,sessionId,derived,lastChange){let{context,...rest}=derived,lastEffect=this.lastEffect?.(sessionId);return{type:"session_status",subscriptionId:subscription.id,seq:subscription.seq,sessionId,...rest,...subscription.options.includeContext?{context}:{},...lastEffect!==void 0?{lastEffect}:{},lastChange}}};function refusal4(id,command,code,detail){return{id,type:"response",command,success:!1,error:`${code}: ${detail.reason}`,errorCode:code,errorData:{reason:detail.reason,action:detail.action}}}function answerSubscribeSessions(command,connectionId,stream){if(connectionId===void 0)return{answer:refusal4(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity to deliver a subscription to",action:"connect to the host socket (senpi --mode rpc --listen) and subscribe there"})};if(stream.connectionSize(connectionId)>=MAX_SUBSCRIPTIONS_PER_CONNECTION)return{answer:refusal4(command.id,command.type,RPC_ERROR_SUBSCRIPTION_LIMIT,{reason:`this connection already holds ${MAX_SUBSCRIPTIONS_PER_CONNECTION} subscriptions`,action:"unsubscribe_sessions the ones you no longer read, then subscribe again"})};let parsed=parseSubscription(command);if("refusal"in parsed)return{answer:refusal4(command.id,command.type,RPC_ERROR_INVALID_SUBSCRIPTION,parsed.refusal)};let subscribed=stream.subscribe(connectionId,parsed.options);return{answer:{id:command.id,type:"response",command:"subscribe_sessions",success:!0,data:{subscriptionId:subscribed.subscriptionId,snapshot:subscribed.snapshot,seq:subscribed.seq,hostGeneration:String(hostGeneration(process.env)),hostInstanceId:hostInstanceId()}},activate:subscribed.subscriptionId}}function answerUnsubscribeSessions(command,connectionId,stream){return connectionId===void 0?refusal4(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity holding any subscription",action:"connect to the host socket (senpi --mode rpc --listen) and manage subscriptions there"}):typeof command.subscriptionId=="string"&&stream.unsubscribe(connectionId,command.subscriptionId)?{id:command.id,type:"response",command:"unsubscribe_sessions",success:!0}:refusal4(command.id,command.type,RPC_ERROR_UNKNOWN_SUBSCRIPTION,{reason:"this connection holds no subscription with that id",action:"send the subscriptionId your subscribe_sessions answer returned, on the same connection"})}function notAttachedRefusal(command){return refusal4(command.id,command.type,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this connection is not attached to that session",action:"attach first with open_session { sessionPath }, then patch its context"})}function answerSetSessionContext(command,entry,stream){let applied=applyContextPatch(entry.contextOverlay,command.patch);return"refusal"in applied?refusal4(command.id,command.type,RPC_ERROR_INVALID_SESSION_CONTEXT,applied.refusal):(entry.contextOverlay=applied.overlay,stream.publish(command.sessionId,"context","client",!0),{id:command.id,type:"response",command:"set_session_context",success:!0,data:{context:publishedSessionContext(entry.context,entry.contextOverlay)}})}function modelOf(model){return model===void 0?void 0:{provider:model.provider,id:model.id}}function runtimeView(entry){let session=entry.runtime?.session;if(session!==void 0){let model2=modelOf(session.model);return{isStreaming:session.isStreaming===!0,isCompacting:session.isCompacting===!0,...model2!==void 0?{model:model2}:{},...session.thinkingLevel!==void 0?{thinkingLevel:session.thinkingLevel}:{},steering:typeof session.getSteeringMessages=="function"?session.getSteeringMessages().length:0,followUp:typeof session.getFollowUpMessages=="function"?session.getFollowUpMessages().length:0,pendingQuestions:sessionQuestionBridges.get(session)?.pendingQuestions()?.length??0}}let state=entry.worker?.snapshot?.state;if(state===void 0)return;let model=modelOf(state.model??void 0);return{isStreaming:state.isStreaming,isCompacting:state.isCompacting,...model!==void 0?{model}:{},...state.thinkingLevel!==void 0?{thinkingLevel:state.thinkingLevel}:{},steering:state.steering.length,followUp:state.followUp.length,pendingQuestions:state.pendingQuestions?.length??0}}function entryView(entry){let session=entry.runtime?.session,state=entry.worker?.snapshot?.state,durableSessionId=session?.sessionId??state?.sessionId??entry.durableSessionId,sessionPath=session?.sessionFile??state?.sessionFile??entry.sessionPath,name=session?.sessionManager.getSessionName()??state?.sessionName;return{state:entry.state,kind:entry.kind,cwd:entry.cwd,attachments:entry.attachments,...durableSessionId!==void 0?{durableSessionId}:{},...sessionPath!==void 0?{sessionPath}:{},...name!==void 0?{name}:{},context:publishedSessionContext(entry.context,entry.contextOverlay),openContext:entry.context}}function registryStatusSource(registry){return{sessionIds:()=>registry.list().map(row=>row.sessionId),entryView:sessionId=>{let entry=registry.peek(sessionId);return entry===void 0?void 0:entryView(entry)},view:sessionId=>{let entry=registry.peek(sessionId);if(entry===void 0)return;let runtime=runtimeView(entry);return runtime===void 0?{entry:entryView(entry)}:{entry:entryView(entry),runtime}}}}var DETACHED_RETIREMENT_GRACE_MS=5e3;function selectSweepEvictions(registry,now,idleEvictionMs,hasPendingRequest=()=>!1){let idle=[],orphaned=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open")continue;let entry=registry.peek(sessionId);if(!entry)continue;if(entry.attachments===0&&sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)){orphaned.push(sessionId);continue}if(!Number.isFinite(idleEvictionMs)||hasPendingRequest(sessionId))continue;let session=entry.runtime?.session;if(entry.worker?.busy||session?.isSessionBusy){entry.lastCommandAt=now;continue}if(entry.attachments>0){now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId);continue}if(entry.kind==="worker"&&entry.retainOnDisconnect&&session?.sessionManager.isTranscriptFlushed()){if(session.pendingMessageCount>0||session.externalAdmission.list().pending.length>0)continue;if(entry.detachedAt!==void 0){if(now-entry.detachedAt<DETACHED_RETIREMENT_GRACE_MS)continue;idle.push(sessionId);continue}}now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId)}return{idle,orphaned}}var CHILD_TASK_SOURCE=/^senpi-task/,ACTIONS={extension_work:"let the named work finish, or unload with force: true (it is stopped, not resumed on reopen)",turn_active:"wait for the turn to end, or unload with interrupt: true to stop it first",work_pending:"wait for the work to finish, or unload with interrupt: true",children_live:'wait for the child tasks, or unload with children: "detach" to leave them running',attached:"ask the other clients to detach, or unload with force: true (they receive session_parked)"};async function unloadSession(port,command){if(port.draining())return answer(command,refused({reason:"host_draining",detail:"this host is draining and parks every session itself"}));let first=loaded(port,command.sessionId);if("reason"in first)return answer(command,refused(first));let{effectId}=command;if(effectId!==void 0){let begun=await beginEffect({session:first.session,by:port.by,sessionId:command.sessionId},"unload",{...command,effectId});if(!isEffectBegin(begun))return begun;if("replay"in begun)return answer(command,{outcome:begun.replay.state==="failed"?"refused":"unloaded",...refusalFields(begun.replay.outcome),...effectAnswer(begun.replay,command.sessionId,!0)})}let blocked=blockers(port,command,first.session,first.durableSessionId),standing=blocked.find(refusal5=>!interruptible(refusal5)||command.interrupt!==!0);return standing!==void 0?fail(command,first.session,standing):(blocked.length>0&&await abortAndSettle(port,command.sessionId,first.session),claimAndUnload(port,command))}async function claimAndUnload(port,command){let ready=loaded(port,command.sessionId);if("reason"in ready)return answer(command,refused(ready));let stillBlocked=blockers(port,command,ready.session,ready.durableSessionId);if(stillBlocked.length>0)return fail(command,ready.session,stillBlocked[0]);command.clearQueue===!0&&(ClientAdmissions.clearQueuedFor(ready.session),ready.session.clearQueue());let effect=command.effectId===void 0?void 0:EffectLedger.forSession(ready.session).transition(command.effectId,"done",{disposition:"unloaded"});return await port.tearDown(command.sessionId,ready.sessionPath)?answer(command,{outcome:"unloaded",sessionPath:ready.sessionPath,...effect===void 0?{}:effectAnswer(effect,command.sessionId)}):answer(command,{outcome:"refused",reason:"session_closing",detail:"another close of this session finished first"})}function interruptible(refusal5){return refusal5.reason==="turn_active"||refusal5.reason==="work_pending"}function blockers(port,command,session,durableSessionId){let found=[],activity=session.activitySnapshot,running=[activity.isStreaming&&"an agent run",port.pendingPrompts(command.sessionId).length>0&&"a prompt about to start",activity.isCompacting&&"compaction",activity.hasSessionWork&&"session work"].filter(label=>typeof label=="string");running.length>0&&found.push({reason:"turn_active",detail:running.join(", "),action:ACTIONS.turn_active});let pending=[activity.isBashRunning&&"a bash command",session.externalAdmission.list().pending.length>0&&"an admitted delivery not yet written",port.otherRequests(command.sessionId)>0&&"another request for this session"].filter(label=>typeof label=="string");pending.length>0&&found.push({reason:"work_pending",detail:pending.join(", "),action:ACTIONS.work_pending});let sources=session.activeWakeSources,childSources=sources.filter(source=>CHILD_TASK_SOURCE.test(source)),otherSources=sources.filter(source=>!CHILD_TASK_SOURCE.test(source));otherSources.length>0&&command.force!==!0&&found.push({reason:"extension_work",detail:`work published by ${otherSources.join(", ")}`,action:ACTIONS.extension_work});let childSessions=port.openChildSessions(durableSessionId);if(command.children!=="detach"&&(childSources.length>0||childSessions>0)){let what=childSessions>0?`${childSessions} child session(s) open on this host`:"child tasks still working";found.push({reason:"children_live",detail:what,action:ACTIONS.children_live})}let others=port.otherAttachments(command.sessionId);return others>0&&command.force!==!0&&found.push({reason:"attached",detail:`${others} other client(s) attached`,action:ACTIONS.attached}),found}function loaded(port,sessionId){let entry;try{entry=port.lookup(sessionId)}catch(cause){return{reason:"unsupported",detail:port.code(cause)}}if(entry.state!=="open")return{reason:"session_closing",detail:"the session is already closing"};let session=entry.runtime?.session;if(session===void 0)return{reason:"unsupported",detail:"a worker isolate owns this session's runtime"};let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?{reason:"unsupported",detail:"the session has no file to reopen it by",action:"send a prompt first so the session is written, or close it instead"}:{session,sessionPath,durableSessionId:session.sessionManager.getSessionId()}}function fail(command,session,refusal5){if(command.effectId===void 0)return answer(command,refused(refusal5));let status=EffectLedger.forSession(session).transition(command.effectId,"failed",{outcome:{kind:"refused",reason:refusal5.reason,detail:refusal5.detail,...refusal5.action===void 0?{}:{action:refusal5.action}}});return answer(command,{...refused(refusal5),...effectAnswer(status,command.sessionId)})}function refusalFields(outcome){return outcome?.reason===void 0?{}:{reason:outcome.reason,...outcome.detail===void 0?{}:{detail:outcome.detail},...outcome.action===void 0?{}:{action:outcome.action}}}function refused(refusal5){return{outcome:"refused",reason:refusal5.reason,detail:refusal5.detail,...refusal5.action===void 0?{}:{action:refusal5.action}}}function answer(command,data){return{id:command.id,type:"response",command:"unload_session",success:!0,data}}var DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>this.routingIdOf(session)!==void 0,flush:(session,statuses)=>{let sessionId=this.routingIdOf(session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}setHostMemoryView(view){this.hostMemoryView=view}sessionMemory(sessionId){let view=this.hostMemoryView;if(view===void 0)return{main_heap_bytes:0,kernel_heap_bytes:0,kernel_count:0};let kernels=view.kernels().filter(kernel=>kernel.sessionId===sessionId),kernelHeapBytes=0;for(let kernel of kernels)kernelHeapBytes+=kernel.liveBytes;return{main_heap_bytes:view.mainHeapBytes(),kernel_heap_bytes:kernelHeapBytes,kernel_count:kernels.length}}beginDrain(){this.draining=!0,this.stopSweep(),this.drainTimer===void 0&&!this.drainExitRequested&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()),this.sweepDrain()}sweepDrain(){if(this.activeRequests.has(void 0))return;let verdicts=readDrainVerdicts(this.registry,sessionId=>this.activeRequests.has(sessionId));if(verdicts){for(let sessionId of verdicts.gone)this.parkForHandoff(sessionId,"session_dir_removed");for(let sessionId of verdicts.park)this.parkForHandoff(sessionId,"handoff_parked");this.registry.size>0||this.handoffParks>0||this.finalizations.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),!this.drainExitRequested&&(this.drainExitRequested=!0,this.onEmptyExit?.()))}}parkForHandoff(sessionId,reason){this.handoffClosed.add(sessionId),this.handoffParks++,this.evictIdleSession(sessionId,reason).catch(cause=>{process.stderr.write(`senpi rpc handoff park ${sessionId} failed: ${String(cause)}
17
17
  `)}).finally(()=>{this.handoffParks--,this.sweepDrain()})}setMemoryPressure(pressure){this.memoryPressure=pressure}handle(command){let sessionId="sessionId"in command?command.sessionId:void 0;return this.draining&&sessionId!==void 0&&this.handoffClosed.has(sessionId)?Promise.resolve(void 0):this.draining&&command.type==="open_session"?Promise.resolve(error(command.id,command.type,"host_draining")):command.type==="warm"?answerWarm(command,{draining:this.draining,warm:this.registry.warm,cwd:this.defaults.cwd,hostContext:this.defaults.hostContext}):(this.activeRequests.set(sessionId,(this.activeRequests.get(sessionId)??0)+1),runWithSessionAttribution({sessionId},()=>this.dispatch(command)).finally(()=>{let remaining=(this.activeRequests.get(sessionId)??1)-1;if(remaining>0?this.activeRequests.set(sessionId,remaining):this.activeRequests.delete(sessionId),sessionId!==void 0)for(let listener of this.requestSettledListeners.get(sessionId)??[])listener();this.draining&&this.sweepDrain()}))}async dispatch(command){if(command.type==="get_protocol_info"){let capabilities=multiSessionHostCapabilities({warm:this.registry.warm!==void 0,negotiated:this.connectionOptions?.capabilities??[]});return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities,mode:"multi",...protocolIdentity(),memory_pressure:this.memoryPressure}}}if(command.type==="get_subscription_limits")return{id:command.id,type:"response",command:"get_subscription_limits",success:!0,data:{accounts:subscriptionLimits.snapshot()}};if(command.type==="list_sessions"){let withMemory=this.registry.list().map(row=>({...row,memory:this.sessionMemory(row.sessionId)})),sessions=command.include_workers===!0?withMemory:withMemory.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="detach_connection")return detachConnection(command,this.writer.currentConnection(),id=>this.releaseConnection(id));if(command.type==="open_session")return this.openWithBarrier(command);if(command.type==="close_session")return this.close(command);if(command.type==="release_session")return releaseSession({draining:()=>this.draining,hostInstance:this.defaults.hostContext?.host_instance,lookup:sessionId2=>this.registry.getForCommand(sessionId2,"release_session"),code:cause=>this.code(cause),otherRequests:sessionId2=>Math.max(0,(this.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>this.otherRequestsSettled(sessionId2),pendingPrompts:sessionId2=>this.bindings.get(sessionId2)?.pendingPrompts?.()??[],tearDown:(sessionId2,sessionPath)=>this.tearDownReleased(sessionId2,sessionPath)},command);if(command.type==="unload_session"){let caller=this.writer.currentConnection();return unloadSession({draining:()=>this.draining,by:{connectionId:caller??"host"},lookup:sessionId2=>this.registry.getForCommand(sessionId2,"unload_session"),code:cause=>this.code(cause),otherRequests:sessionId2=>Math.max(0,(this.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>this.otherRequestsSettled(sessionId2),pendingPrompts:sessionId2=>this.bindings.get(sessionId2)?.pendingPrompts?.()??[],otherAttachments:sessionId2=>{let attachments=Math.max(0,this.registry.peek(sessionId2)?.attachments??0);return caller!==void 0&&this.sessionsByConnection.get(caller)?.has(sessionId2)===!0?Math.max(0,attachments-1):attachments},openChildSessions:durableSessionId=>this.registry.list().filter(row=>row.durableSessionId!==durableSessionId&&(row.context?.parent_session_id===durableSessionId||row.context?.root_session_id===durableSessionId)).length,tearDown:(sessionId2,sessionPath)=>this.tearDownUnloaded(sessionId2,sessionPath)},command)}if(command.type==="set_client_info"&&!command.sessionId){let connection=this.writer.currentConnection();return connection!==void 0&&(this.pendingCapabilities.set(connection,command.capabilities??[]),this.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0}}if(command.type==="subscribe_sessions"){let connection=this.writer.currentConnection(),{answer:answer2,activate}=answerSubscribeSessions(command,connection,this.writer.status);if(activate!==void 0&&connection!==void 0){(async()=>{await this.writer.enqueueControl(answer2,connection),await new Promise(resolve=>queueMicrotask(resolve));try{this.writer.hasConnection(connection)?this.writer.status.activate(activate):this.writer.status.unsubscribe(connection,activate)}catch(cause){process.stderr.write(`senpi rpc subscription activation failed: ${String(cause)}
18
18
  `)}})().catch(cause=>{this.writer.status.unsubscribe(connection,activate),process.stderr.write(`senpi rpc subscribe answer could not be delivered: ${String(cause)}
19
19
  `)});return}return answer2}if(command.type==="unsubscribe_sessions")return answerUnsubscribeSessions(command,this.writer.currentConnection(),this.writer.status);if(command.type==="get_effect_status"&&!command.sessionId&&command.sessionPath!==void 0)return answerEffectFromTranscript(command.id,command.sessionPath,command.effectId);if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);let sessionId=command.sessionId;if(command.type==="set_session_context")return this.setSessionContext(command);try{let entry=this.registry.getForCommand(sessionId,command.type);await dispatchSessionBinding(command,entry,this.bindings.get(sessionId),()=>this.acknowledgePrompt(command.id,sessionId),observedStarts=>this.registry.holderPids?.(observedStarts)??Promise.resolve([]));return}catch(cause){return error(command.id,command.type,this.code(cause),this.detail(cause))}}setSessionContext(command){let owner=this.writer.currentConnection();if(owner!==void 0&&this.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return notAttachedRefusal(command);try{let entry=this.registry.getForCommand(command.sessionId,command.type);return answerSetSessionContext(command,entry,this.writer.status)}catch(cause){return error(command.id,command.type,this.code(cause),this.detail(cause))}}async dispose(){this.stopLimitBroadcast(),this.drainExitRequested=!0,this.stopSweep(),this.drainTimer!==void 0&&clearInterval(this.drainTimer),await Promise.all([...this.bindings.entries()].map(async([sessionId,binding])=>{let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId))})),this.bindings.clear(),this.uninstallEffectSink?.(),this.uninstallEffectSink=void 0}sweepIdleSessions(){let now=this.idleNow(),idleEvictionMs=this.memoryPressure?this.idleEvictionMs/2:this.idleEvictionMs,verdicts=selectSweepEvictions(this.registry,now,idleEvictionMs,sessionId=>this.activeRequests.has(sessionId)||(this.bindings.get(sessionId)?.pendingPrompts?.().length??0)>0);for(let sessionId of verdicts.orphaned)this.evictIdleSession(sessionId,"session_dir_removed");for(let sessionId of verdicts.idle)this.evictIdleSession(sessionId);Number.isFinite(this.emptyExitMs)&&(this.registry.size===0&&(this.canExitWhenEmpty?.()??!0)?this.emptySince===void 0?this.emptySince=now:now-this.emptySince>=this.emptyExitMs&&(this.stopSweep(),this.onEmptyExit?.()):this.emptySince=void 0)}async evictIdleSession(sessionId,reason){let retained=this.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0||reason==="handoff_parked"?retained?.sessionPath:void 0,handoff=reason==="handoff_parked"||reason==="session_dir_removed"&&this.draining,owners=handoff?[...this.sessionsByConnection].filter(([,owned])=>owned.has(sessionId)).map(([connection])=>connection):[],claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return;this.handoverParkedDir!==void 0&&parkedPath!==void 0&&retained?.retainOnDisconnect===!0&&retained.sessionPath!==void 0&&await recordHandoverParkedSession(this.handoverParkedDir,parkedEntryFromProfile({sessionPath:retained.sessionPath,...retained.durableSessionId!==void 0?{durableSessionId:retained.durableSessionId}:{}},retained.profile,Object.keys(this.defaults.hostContext??{}))).catch(cause=>{process.stderr.write(`senpi rpc handover park record ${sessionId} failed: ${String(cause)}