@code-yeongyu/senpi 2026.10.7 → 2026.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/bundle/chunks/{anthropic-messages-4MNFPQ66.js → anthropic-messages-CVXI6CLT.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-SO5RJ2N7.js → app-server-command-MJOYE5ZS.js} +1 -1
- package/dist/bundle/chunks/{chunk-BE66QJ3Z.js → chunk-4GUQVY4Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-EUU6W5B3.js → chunk-5MG76BCM.js} +9 -9
- package/dist/bundle/chunks/{chunk-ESSQUSRC.js → chunk-BTYFICUC.js} +1 -1
- package/dist/bundle/chunks/{chunk-JJNIU2A2.js → chunk-CB77NQMN.js} +1 -1
- package/dist/bundle/chunks/{chunk-D2W3MXRF.js → chunk-LSE7KE2C.js} +1 -1
- package/dist/bundle/chunks/{chunk-HY4AOLON.js → chunk-MJGHZT4N.js} +3 -3
- package/dist/bundle/chunks/{chunk-7A3WRAKP.js → chunk-Q2ZTPMWD.js} +1 -1
- package/dist/bundle/chunks/{chunk-7SMFF2QJ.js → chunk-X6UDRO7J.js} +3 -3
- package/dist/bundle/chunks/{cli-main-XBQN73O2.js → cli-main-GWVLFOIP.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-FUMH5NSA.js → help-fast-path-JBQLYO7W.js} +1 -1
- package/dist/bundle/chunks/{host-command-YXQAXNKK.js → host-command-HTYYQBSG.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-L4XQIATP.js → host-lifecycle-XZF6IKKO.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +3 -3
- package/dist/bundle/chunks/{interactive-mode-ROO5W56P.js → interactive-mode-YLM2U7IX.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-5WTKAQJM.js → multi-session-host-KMCBBPTV.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-NCD5FQGV.js → package-manager-cli-3UIJ4RXY.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-7E37KOCX.js → rotation-stream-ZJQ6I2RZ.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-MWURKCP2.js → rpc-mode-PUYBZG27.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-UTXB465F.js → schedule-command-CVAPK2WQ.js} +1 -1
- package/dist/bundle/chunks/{sdk-EO76I33H.js → sdk-U52J75K2.js} +50 -50
- package/dist/bundle/chunks/{session-control-endpoint-J6RHZXWB.js → session-control-endpoint-THEF3K7M.js} +1 -1
- package/dist/bundle/chunks/{session-picker-VTTRFGE7.js → session-picker-N463VCDI.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +67 -67
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session.d.ts +7 -2
- package/dist/core/agent-session.js +31 -5
- package/dist/core/continue-from-leaf.d.ts +21 -0
- package/dist/core/continue-from-leaf.js +39 -0
- package/dist/modes/rpc/host-lifecycle.js +5 -28
- package/dist/modes/rpc/host-run-activity.d.ts +13 -0
- package/dist/modes/rpc/host-run-activity.js +39 -0
- package/package.json +7 -7
|
@@ -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-F73COJ7R.js";import{main}from"./chunk-
|
|
3
|
+
import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-5MG76BCM.js";import"./chunk-X6UDRO7J.js";import"./chunk-QNAG7FYM.js";import"./chunk-4GUQVY4Z.js";import{configureHttpDispatcher}from"./chunk-BTYFICUC.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-6EH7QXOG.js";import"./chunk-JABBHOD5.js";import"./chunk-CB77NQMN.js";import"./chunk-VJJ53ORU.js";import"./chunk-QMRJYMNH.js";import"./chunk-CM5QTRC2.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-Q2ZTPMWD.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import"./chunk-LUWWM7GA.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-
|
|
2
|
+
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-6WCOSBI7.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
|
|
@@ -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{parseHostArgs,runHostCommand}from"./chunk-
|
|
2
|
+
import{parseHostArgs,runHostCommand}from"./chunk-CB77NQMN.js";import"./chunk-VJJ53ORU.js";import"./chunk-QMRJYMNH.js";import"./chunk-CM5QTRC2.js";import"./chunk-ZJHRDQCH.js";import"./chunk-KUPQO7MC.js";import"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import"./chunk-LUWWM7GA.js";import"./chunk-YI7SPFDN.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-6WCOSBI7.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,runHostCommand};
|
|
@@ -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{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch}from"./chunk-
|
|
3
|
+
import{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch}from"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import"./chunk-LUWWM7GA.js";import"./chunk-YI7SPFDN.js";import"./chunk-U3VOXCGP.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";export{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch};
|
|
@@ -16,9 +16,9 @@ renameSync(temporary, launcher);
|
|
|
16
16
|
`,{mode:CRASH_RECORD_FILE_MODE}),pruneHostCrashRecords(daemonDir)}catch{}}function readHostCrashRecords(daemonDir){let raw;try{raw=readFileSync2(hostCrashRecordFile(daemonDir),"utf8")}catch{return[]}let records=[];for(let line of raw.split(`
|
|
17
17
|
`))if(line.trim()!=="")try{let value=JSON.parse(line);typeof value=="object"&&value!==null&&typeof Reflect.get(value,"at")=="string"&&records.push(value)}catch{}return records}function pruneHostCrashRecords(daemonDir){let records=readHostCrashRecords(daemonDir);if(records.length<=HOST_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-HOST_CRASH_RECORD_LIMIT);writeFileSync(hostCrashRecordFile(daemonDir),`${kept.map(r=>JSON.stringify(r)).join(`
|
|
18
18
|
`)}
|
|
19
|
-
`,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}function noteChildExit(daemonDir,code,signal,childStartedAt,now=Date.now()){classifyChildExit(code,signal).exitCode!==0&&recordHostCrash(daemonDir,{at:new Date(now).toISOString(),...signal===null?{code:code??void 0}:{signal},uptimeMs:Math.max(0,now-childStartedAt),kind:"rpc-host",detection:"supervisor",...crashingRuntimeVersions()})}var OBSERVE_REQUEST_FIELD="observe",OBSERVING_COMMANDS=new Set(["get_protocol_info","list_sessions"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.onAttach=onAttach}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size}admit(client){this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};client.on("data",classify)}release(client){this.clients.delete(client),this.observers.delete(client),this.attached.delete(client)}destroyAll(){for(let client of this.clients)client.destroy()}};function rpcHostExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}var HOST_COLD_START_ENV="SENPI_RPC_HOST_COLD_START",HOST_IDLE_EXIT_MS_ENV="SENPI_RPC_HOST_IDLE_EXIT_MS",DEFAULT_HOST_IDLE_EXIT_MS=9e5,HANDOFF_GRACE_MS_ENV="SENPI_RPC_HANDOFF_GRACE_MS",DEFAULT_HANDOFF_GRACE_MS=6e5;function parseColdStart(value){return value==="transient"||value==="persistent"?value:void 0}function parseIdleExitMs(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveHostPolicy(settings,env){let record=isRecord2(settings)?settings:{},coldStart=parseColdStart(env[HOST_COLD_START_ENV])??parseColdStart(asOptionalString(record.coldStart))??"transient",idleExitMs=parseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV])??parseIdleExitMs(asOptionalString(record.idleExitMs))??9e5;return{coldStart,idleExitMs}}var IdleExitDecider=class{constructor(idleExitMs,now=Date.now){this.idleExitMs=idleExitMs,this.now=now}update(activity){return activity.connections>0||activity.activeTurns>0?(this.idleSince=void 0,"active"):this.idleExitMs===Number.POSITIVE_INFINITY?"idle":this.idleSince===void 0?(this.idleSince=this.now(),"idle"):this.now()-this.idleSince>=this.idleExitMs?"exit":"idle"}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function asOptionalString(value){return typeof value=="string"?value:typeof value=="number"?String(value):void 0}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{createHash,randomUUID}from"node:crypto";import{basename as basename3,dirname as dirname4,join as join6,win32 as win322}from"node:path";import{existsSync as existsSync2,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname3,join as join5,resolve as resolve2}from"node:path";function canonicalSessionPath(path){let absolutePath=resolve2(path),missing=[],existing=absolutePath;for(;!existsSync2(existing);){let parent=dirname3(existing);if(parent===existing)return absolutePath;missing.unshift(basename2(existing)),existing=parent}try{return join5(realpathSync2(existing),...missing)}catch{return absolutePath}}var HOST_DAEMON_DIR_ENV="SENPI_RPC_HOST_DAEMON_DIR";function canonicalEndpointPath(socket,platform=process.platform){return platform==="win32"?win322.normalize(socket).toLowerCase():socket.startsWith("\0")?socket:join6(canonicalSessionPath(dirname4(socket)),basename3(socket))}function daemonDirectoryName(socket,platform=process.platform){return directoryNameOf(canonicalEndpointPath(socket,platform))}function directoryNameOf(endpoint){return createHash("sha256").update(endpoint,"utf8").digest("hex").slice(0,16)}function createHostDaemonPaths(target){let flatDir=join6(target.agentDir??getAgentDir(),"rpc-host-daemon");return{socket:target.socket,flatDir,layoutMarker:join6(flatDir,"layout.json"),legacyPidFile:join6(flatDir,"host.pid"),...hostDaemonDirectoryPaths(join6(flatDir,daemonDirectoryName(target.socket)))}}function hostDaemonDirectoryPaths(dir){return{dir,endpointFile:join6(dir,"endpoint.json"),pointerFile:join6(dir,"host.pid"),lockFile:join6(dir,"daemon.lock"),settingsFile:join6(dir,"settings.json"),stderrLog:join6(dir,"stderr.log"),generationsDir:join6(dir,"generations"),reservationsDir:join6(dir,"reservations")}}function generationPaths(paths,instanceId){let dir=join6(paths.generationsDir,instanceId);return{dir,relativeDir:`generations/${instanceId}`,pidFile:join6(dir,"host.pid"),settingsFile:join6(dir,"settings.json"),scratchDir:join6(dir,"scratch")}}import{rename,rm}from"node:fs/promises";import{readFile,writeFile}from"node:fs/promises";async function readFileOrUndefined(path){try{return await readFile(path,"utf8")}catch(error){if(isNodeErrorCode2(error,"ENOENT")||isNodeErrorCode2(error,"ENOTDIR"))return;throw error}}function parseJson(text){if(text!==void 0)try{let parsed=JSON.parse(text);return isRecord3(parsed)?parsed:void 0}catch{return}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode2(error,code){return error instanceof Error&&"code"in error&&error.code===code}var TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId),record=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record!==void 0&&record.pid!==owner.pid)return;if(owner.superseded===!0){await rm(generation.dir,{recursive:!0,force:!0});return}let ownsPointer=parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId;ownsPointer&&await rm(paths.settingsFile,{force:!0}),await rm(generation.dir,{recursive:!0,force:!0}),ownsPointer&&await rm(paths.pointerFile,{force:!0})}var HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID";import{mkdir,readFile as readFile2,rename as rename2,stat,unlink,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname5}from"node:path";var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner";var MAX_SOCKET_PATH_BYTES=103;function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}async function statSocketIdentity(socketPath){try{let{dev,ino}=await stat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function writeSocketIdentityFile(path,identity){await mkdir(dirname5(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile2(tmpPath,`${JSON.stringify(identity)}
|
|
19
|
+
`,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}function noteChildExit(daemonDir,code,signal,childStartedAt,now=Date.now()){classifyChildExit(code,signal).exitCode!==0&&recordHostCrash(daemonDir,{at:new Date(now).toISOString(),...signal===null?{code:code??void 0}:{signal},uptimeMs:Math.max(0,now-childStartedAt),kind:"rpc-host",detection:"supervisor",...crashingRuntimeVersions()})}var OBSERVE_REQUEST_FIELD="observe",OBSERVING_COMMANDS=new Set(["get_protocol_info","list_sessions"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.onAttach=onAttach}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size}admit(client){this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};client.on("data",classify)}release(client){this.clients.delete(client),this.observers.delete(client),this.attached.delete(client)}destroyAll(){for(let client of this.clients)client.destroy()}};function rpcHostExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}var HOST_COLD_START_ENV="SENPI_RPC_HOST_COLD_START",HOST_IDLE_EXIT_MS_ENV="SENPI_RPC_HOST_IDLE_EXIT_MS",DEFAULT_HOST_IDLE_EXIT_MS=9e5,HANDOFF_GRACE_MS_ENV="SENPI_RPC_HANDOFF_GRACE_MS",DEFAULT_HANDOFF_GRACE_MS=6e5;function parseColdStart(value){return value==="transient"||value==="persistent"?value:void 0}function parseIdleExitMs(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveHostPolicy(settings,env){let record=isRecord2(settings)?settings:{},coldStart=parseColdStart(env[HOST_COLD_START_ENV])??parseColdStart(asOptionalString(record.coldStart))??"transient",idleExitMs=parseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV])??parseIdleExitMs(asOptionalString(record.idleExitMs))??9e5;return{coldStart,idleExitMs}}var IdleExitDecider=class{constructor(idleExitMs,now=Date.now){this.idleExitMs=idleExitMs,this.now=now}update(activity){return activity.connections>0||activity.activeTurns>0?(this.idleSince=void 0,"active"):this.idleExitMs===Number.POSITIVE_INFINITY?"idle":this.idleSince===void 0?(this.idleSince=this.now(),"idle"):this.now()-this.idleSince>=this.idleExitMs?"exit":"idle"}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function asOptionalString(value){return typeof value=="string"?value:typeof value=="number"?String(value):void 0}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{createHash,randomUUID}from"node:crypto";import{basename as basename3,dirname as dirname4,join as join6,win32 as win322}from"node:path";import{existsSync as existsSync2,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname3,join as join5,resolve as resolve2}from"node:path";function canonicalSessionPath(path){let absolutePath=resolve2(path),missing=[],existing=absolutePath;for(;!existsSync2(existing);){let parent=dirname3(existing);if(parent===existing)return absolutePath;missing.unshift(basename2(existing)),existing=parent}try{return join5(realpathSync2(existing),...missing)}catch{return absolutePath}}var HOST_DAEMON_DIR_ENV="SENPI_RPC_HOST_DAEMON_DIR";function canonicalEndpointPath(socket,platform=process.platform){return platform==="win32"?win322.normalize(socket).toLowerCase():socket.startsWith("\0")?socket:join6(canonicalSessionPath(dirname4(socket)),basename3(socket))}function daemonDirectoryName(socket,platform=process.platform){return directoryNameOf(canonicalEndpointPath(socket,platform))}function directoryNameOf(endpoint){return createHash("sha256").update(endpoint,"utf8").digest("hex").slice(0,16)}function createHostDaemonPaths(target){let flatDir=join6(target.agentDir??getAgentDir(),"rpc-host-daemon");return{socket:target.socket,flatDir,layoutMarker:join6(flatDir,"layout.json"),legacyPidFile:join6(flatDir,"host.pid"),...hostDaemonDirectoryPaths(join6(flatDir,daemonDirectoryName(target.socket)))}}function hostDaemonDirectoryPaths(dir){return{dir,endpointFile:join6(dir,"endpoint.json"),pointerFile:join6(dir,"host.pid"),lockFile:join6(dir,"daemon.lock"),settingsFile:join6(dir,"settings.json"),stderrLog:join6(dir,"stderr.log"),generationsDir:join6(dir,"generations"),reservationsDir:join6(dir,"reservations")}}function generationPaths(paths,instanceId){let dir=join6(paths.generationsDir,instanceId);return{dir,relativeDir:`generations/${instanceId}`,pidFile:join6(dir,"host.pid"),settingsFile:join6(dir,"settings.json"),scratchDir:join6(dir,"scratch")}}import{rename,rm}from"node:fs/promises";import{readFile,writeFile}from"node:fs/promises";async function readFileOrUndefined(path){try{return await readFile(path,"utf8")}catch(error){if(isNodeErrorCode2(error,"ENOENT")||isNodeErrorCode2(error,"ENOTDIR"))return;throw error}}function parseJson(text){if(text!==void 0)try{let parsed=JSON.parse(text);return isRecord3(parsed)?parsed:void 0}catch{return}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode2(error,code){return error instanceof Error&&"code"in error&&error.code===code}var TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId),record=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record!==void 0&&record.pid!==owner.pid)return;if(owner.superseded===!0){await rm(generation.dir,{recursive:!0,force:!0});return}let ownsPointer=parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId;ownsPointer&&await rm(paths.settingsFile,{force:!0}),await rm(generation.dir,{recursive:!0,force:!0}),ownsPointer&&await rm(paths.pointerFile,{force:!0})}var HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID";var SessionRunActivity=class{#running=new Set;observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId);else if(event.type==="agent_settled"||event.type==="session_closed")this.#running.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}};function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;return typeof sessionId=="string"?{type,sessionId}:void 0}import{mkdir,readFile as readFile2,rename as rename2,stat,unlink,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname5}from"node:path";var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner";var MAX_SOCKET_PATH_BYTES=103;function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}async function statSocketIdentity(socketPath){try{let{dev,ino}=await stat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function writeSocketIdentityFile(path,identity){await mkdir(dirname5(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile2(tmpPath,`${JSON.stringify(identity)}
|
|
20
20
|
`,{mode:384}),await rename2(tmpPath,path)}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink(socketPath)}catch(cause){isNodeErrorCode3(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename2(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename2(shieldPath,socketPath)}catch{}}}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode3(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0||process.platform==="win32")return()=>{};let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function ignore(){}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID";var HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";import{StringDecoder}from"node:string_decoder";var MAX_RPC_LINE_CHARACTERS=16*1024*1024;function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
|
|
21
21
|
`,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
|
|
22
|
-
`,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}import{createHash as createHash2,randomBytes,timingSafeEqual}from"node:crypto";import{chmod,mkdir as mkdir2,readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname6,win32 as win323}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile3(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode4(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir2(dirname6(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile3(path,secret,{mode:384}),await chmod(path,384),secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash2("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode4(error,code){return error instanceof Error&&"code"in error&&error.code===code}var CHILD_STOP_TIMEOUT_MS=5e3,WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3,CHILD_WATCH_FD=3;async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join7(baseDir,`internal-${randomUUID2()}`);return await mkdir3(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID2()}`,dir:dir2,secretPath:join7(dir2,"secret")}}let dir=join7(tmpdir(),`senpi-rpc-host-internal-${randomUUID2().slice(0,8)}`);return await mkdir3(dir,{recursive:!1,mode:448}),await writeFile4(join7(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join7(dir,"host.sock"),dir,secretPath:join7(dir,".secret")}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,bindSocket,replaceIdentity}}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveCliMainPath(modulePath=fileURLToPath3(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve3(dirname7(modulePath),"..","..",`cli-main${extension}`);return existsSync3(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname7(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve3(dir,"package.json");if(existsSync3(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve3(dir,candidate);if(existsSync3(entry))return entry}}catch{}return}let parent=dirname7(dir);if(parent===dir)return;dir=parent}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...rpcHostExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,clients=new ClientOccupancy(()=>decider.update(currentActivity())),busySessions=new Map,observerSocket,observerLink=createObserverLink({open:async()=>{let secret=internalSecret,next=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,secret));return secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),observerSocket=next,attachJsonlLineReader(next,observeHostEvent,{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{next.once("close",handler),next.once("error",handler)}}},settled:()=>shuttingDown,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}}),childExitWatchTimer,stopSupersessionWatch,shuttingDown=!1,draining=!1,endpointReplaced=!1,handoffGraceTimer,shutdownPromise,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:paths.dir,[HOST_INSTANCE_ID_ENV]:instanceId,[HOST_WATCH_FD_ENV]:String(CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internalSecretPath}:{},[HOST_CLEANUP_PATHS_ENV]:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:!!successor,platform:process.platform}).join(`
|
|
23
|
-
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:["ignore","ignore","inherit","pipe"],windowsHide:!0}),childStartedAt=Date.now();child.stdio[CHILD_WATCH_FD]?.on("error",()=>{}),child.once("exit",(code,signal)=>{if(shuttingDown)return;let{reason,exitCode}=classifyChildExit(code,signal);noteChildExit(paths.dir,code,signal,childStartedAt),shutdown(reason,exitCode)});let server=createServer(client=>{let accept=()=>{if(shuttingDown||draining){client.destroy();return}let internal2=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internalSecret&&sendSocketHandshake(internal2,internalSecret),clients.admit(client);let detach=()=>{clients.release(client),decider.update(currentActivity()),internal2.destroy(),client.destroy()};client.pipe(internal2),internal2.pipe(client),client.once("close",detach),client.once("error",detach),internal2.once("end",()=>client.end(()=>client.destroy())),internal2.once("close",()=>{internal2.readableEnded||detach()}),internal2.once("error",detach)};publicSecret?authenticateSocket(client,publicSecret,accept):accept()});server.once("error",cause=>{shuttingDown||shutdown(`public socket listener failed: ${errorMessage2(cause)}`,1)});let decider=new IdleExitDecider(policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs),tickIntervalMs=Math.max(20,Math.min(1e3,policy.idleExitMs/4)),ticker=setInterval(()=>{!draining&&decider.update(currentActivity())==="exit"&&clients.unclassifiedCount===0&&shutdown("idle",0)},tickIntervalMs);function currentActivity(){return{connections:clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:observerLink.healthy(),unhealthySince:observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:decider.idleExitMs,observedBusy:
|
|
22
|
+
`,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}import{createHash as createHash2,randomBytes,timingSafeEqual}from"node:crypto";import{chmod,mkdir as mkdir2,readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname6,win32 as win323}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile3(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode4(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir2(dirname6(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile3(path,secret,{mode:384}),await chmod(path,384),secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash2("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode4(error,code){return error instanceof Error&&"code"in error&&error.code===code}var CHILD_STOP_TIMEOUT_MS=5e3,WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3,CHILD_WATCH_FD=3;async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join7(baseDir,`internal-${randomUUID2()}`);return await mkdir3(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID2()}`,dir:dir2,secretPath:join7(dir2,"secret")}}let dir=join7(tmpdir(),`senpi-rpc-host-internal-${randomUUID2().slice(0,8)}`);return await mkdir3(dir,{recursive:!1,mode:448}),await writeFile4(join7(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join7(dir,"host.sock"),dir,secretPath:join7(dir,".secret")}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,bindSocket,replaceIdentity}}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveCliMainPath(modulePath=fileURLToPath3(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve3(dirname7(modulePath),"..","..",`cli-main${extension}`);return existsSync3(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname7(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve3(dir,"package.json");if(existsSync3(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve3(dir,candidate);if(existsSync3(entry))return entry}}catch{}return}let parent=dirname7(dir);if(parent===dir)return;dir=parent}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...rpcHostExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,clients=new ClientOccupancy(()=>decider.update(currentActivity())),runs=new SessionRunActivity,observerSocket,observerLink=createObserverLink({open:async()=>{let secret=internalSecret,next=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,secret));return secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),observerSocket=next,attachJsonlLineReader(next,observeHostEvent,{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{next.once("close",handler),next.once("error",handler)}}},settled:()=>shuttingDown,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}}),childExitWatchTimer,stopSupersessionWatch,shuttingDown=!1,draining=!1,endpointReplaced=!1,handoffGraceTimer,shutdownPromise,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:paths.dir,[HOST_INSTANCE_ID_ENV]:instanceId,[HOST_WATCH_FD_ENV]:String(CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internalSecretPath}:{},[HOST_CLEANUP_PATHS_ENV]:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:!!successor,platform:process.platform}).join(`
|
|
23
|
+
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:["ignore","ignore","inherit","pipe"],windowsHide:!0}),childStartedAt=Date.now();child.stdio[CHILD_WATCH_FD]?.on("error",()=>{}),child.once("exit",(code,signal)=>{if(shuttingDown)return;let{reason,exitCode}=classifyChildExit(code,signal);noteChildExit(paths.dir,code,signal,childStartedAt),shutdown(reason,exitCode)});let server=createServer(client=>{let accept=()=>{if(shuttingDown||draining){client.destroy();return}let internal2=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internalSecret&&sendSocketHandshake(internal2,internalSecret),clients.admit(client);let detach=()=>{clients.release(client),decider.update(currentActivity()),internal2.destroy(),client.destroy()};client.pipe(internal2),internal2.pipe(client),client.once("close",detach),client.once("error",detach),internal2.once("end",()=>client.end(()=>client.destroy())),internal2.once("close",()=>{internal2.readableEnded||detach()}),internal2.once("error",detach)};publicSecret?authenticateSocket(client,publicSecret,accept):accept()});server.once("error",cause=>{shuttingDown||shutdown(`public socket listener failed: ${errorMessage2(cause)}`,1)});let decider=new IdleExitDecider(policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs),tickIntervalMs=Math.max(20,Math.min(1e3,policy.idleExitMs/4)),ticker=setInterval(()=>{!draining&&decider.update(currentActivity())==="exit"&&clients.unclassifiedCount===0&&shutdown("idle",0)},tickIntervalMs);function currentActivity(){return{connections:clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:observerLink.healthy(),unhealthySince:observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:decider.idleExitMs,observedBusy:runs.busySessions})}}function observeHostEvent(line){runs.observe(line)&&decider.update(currentActivity())}async function shutdown(reason,exitCode){return shutdownPromise??=performShutdown(reason,exitCode),shutdownPromise}async function performShutdown(reason,exitCode){shuttingDown&&process.exit(exitCode),shuttingDown=!0,clearInterval(ticker),handoffGraceTimer&&clearTimeout(handoffGraceTimer),childExitWatchTimer&&clearInterval(childExitWatchTimer),stopSupersessionWatch?.();let hardExit=process.platform==="win32"?setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS):void 0;try{writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`),clients.destroyAll(),draining||await shieldSocketDuringClose(publicSocket,()=>closeServer(server)),internal.dir&&await rm2(internal.dir,{recursive:!0,force:!0}),await stopChild(child),observerLink.stop(),observerSocket?.destroy(),publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedSocket(publicSocket,publicSocketIdentity,supervisorLog),await releaseGeneration(paths,{instanceId,pid:process.pid,superseded:endpointReplaced})}finally{hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}let publicSocketOwned=!1,publicSocketIdentity;function supervisorLog(message){writeStderrLine(`senpi rpc host supervisor: ${message}`)}function drainForHandoff(){if(draining||shuttingDown)return;draining=!0,supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;handoffGraceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),requestChildDrain()},graceMs),handoffGraceTimer.unref(),requestChildDrain()}function requestChildDrain(){if(child.pid!==void 0&&child.exitCode===null&&child.signalCode===null)try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage2(cause)}`)}}registerSupervisorSignals(shutdown,drainForHandoff);try{await waitForListener(internalSocket,3e4,internalSecret),await observerLink.open(),await prepareSocketPath(bindSocket),await listen(server,bindSocket,publicSecret),publicSocketOwned=!0,successor&&await adoptPublicSocket(bindSocket,publicSocket,launch.replaceIdentity),publicSocketIdentity=await statSocketIdentity(publicSocket),publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join7(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),publicSocketIdentity),stopSupersessionWatch=watchForSupersession({path:publicSocket,identity:publicSocketIdentity,settled:()=>shuttingDown||draining},loss=>{loss==="replaced"&&(endpointReplaced=!0),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drainForHandoff()})}catch(cause){await shutdown(`startup failed: ${errorMessage2(cause)}`,1)}if(process.platform==="win32"&&child.pid!==void 0){let childStartTime=await readProcessStartTime(child.pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checkingChildIdentity=!1;childExitWatchTimer=setInterval(()=>{shuttingDown||checkingChildIdentity||child.exitCode!==null||child.signalCode!==null||(checkingChildIdentity=!0,readProcessStartTime(child.pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(child.pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&¤tStartTime!==void 0&¤tStartTime!==childStartTime||missingIdentityChecks>=2)&&shutdown("rpc host child exit observed by identity watchdog",0)}).catch(()=>{}).finally(()=>{checkingChildIdentity=!1}))},500),childExitWatchTimer.unref?.()}writeStderrLine(`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${policy.coldStart==="persistent"?"never":String(policy.idleExitMs)})`),await new Promise(()=>{})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename3(bindSocket,publicSocket)}async function ensurePublicSocketSecret(publicSocket){let secretPath=socketSecretPath(publicSocket);try{return await ensureSocketSecret(secretPath)}catch(cause){throw new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`,{cause})}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile4(settingsFile,"utf8"))}catch{return}}async function stopChild(child){if(!(child.exitCode!==null||child.signalCode!==null)){try{child.kill("SIGTERM")}catch{return}if(!await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)){try{child.kill("SIGKILL")}catch{return}await waitForChildExit(child,2e3)}}}function waitForChildExit(child,timeoutMs){return child.exitCode!==null||child.signalCode!==null?Promise.resolve(!0):new Promise(resolve4=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve4(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve4(!0)};child.once("exit",onExit2)})}async function waitForListener(socketPath,timeoutMs,secret){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await canConnect(socketPath,secret))return;await delay(50)}throw new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`)}function canConnect(socketPath,secret){return new Promise(resolve4=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=value=>{socket.destroy(),resolve4(value)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}function waitForConnect(socket,timeoutMs){return new Promise((resolve4,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve4()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}async function prepareSocketPath(socketPath){if(process.platform!=="win32"){if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir3(dirname7(socketPath),{recursive:!0,mode:448});try{await access(socketPath)}catch(cause){if(isNodeErrorCode5(cause,"ENOENT"))return;throw cause}if(await canConnect(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink2(socketPath)}}function listen(server,socketPath,secret){return new Promise((resolve4,reject)=>{server.once("error",reject),server.listen({path:resolveSocketTransportAddress(socketPath,process.platform,secret),readableAll:!1,writableAll:!1},async()=>{server.off("error",reject);try{process.platform!=="win32"&&!socketPath.startsWith("\0")&&await chmod2(socketPath,384),resolve4()}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise(resolve4=>{server.close(()=>resolve4())})}function writeStderrLine(text){try{writeSync(2,`${text}
|
|
24
24
|
`)}catch{}}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode5(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath3(import.meta.url)===realpathSync3(entry)}catch{return!1}}if(!isBundledNode&&isEntryScript()){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}export{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch};
|
|
@@ -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,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-5MG76BCM.js";import{isApiKeyLoginProvider}from"./chunk-X6UDRO7J.js";import"./chunk-QNAG7FYM.js";import"./chunk-4GUQVY4Z.js";import"./chunk-BTYFICUC.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-6EH7QXOG.js";import"./chunk-JABBHOD5.js";import"./chunk-CB77NQMN.js";import"./chunk-VJJ53ORU.js";import"./chunk-QMRJYMNH.js";import"./chunk-CM5QTRC2.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-Q2ZTPMWD.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import"./chunk-LUWWM7GA.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
|
package/dist/bundle/chunks/{multi-session-host-5WTKAQJM.js → multi-session-host-KMCBBPTV.js}
RENAMED
|
@@ -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,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,runWithProviderScope,startHostChildReaper}from"./chunk-
|
|
2
|
+
import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,runWithProviderScope,startHostChildReaper}from"./chunk-5MG76BCM.js";import{DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,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_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,createRpcConnectionHandler,readCodemodeKernelRows,readMainThreadHeapBytes,readOwnFootprint}from"./chunk-X6UDRO7J.js";import"./chunk-QNAG7FYM.js";import{SessionManager,assertValidSessionId,liveToolMediaScope,omitInlineMedia,toolMediaPersister}from"./chunk-4GUQVY4Z.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-BTYFICUC.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import{buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-6EH7QXOG.js";import"./chunk-JABBHOD5.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,GENERATION_HANDOFF_CAPABILITY,HostIdleHandover,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,beginHandoverResponse,computeRuntimeBuildId,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-CB77NQMN.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,WARM_CAPABILITY,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-VJJ53ORU.js";import"./chunk-QMRJYMNH.js";import"./chunk-CM5QTRC2.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-Q2ZTPMWD.js";import"./chunk-F6EQ7EV3.js";import{killTrackedDetachedChildren}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import{ClientOccupancy,armHostWatchdog,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-LUWWM7GA.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}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)}var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB",DEFAULT_HOST_RSS_WARN_MB=4096,HOST_MEMORY_SAMPLE_MS=3e4,HOST_MEMORY_STDERR_INTERVAL_MS=5*6e4,BYTES_PER_MEGABYTE=1024*1024;function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readFootprint=options.readFootprint??readOwnFootprint,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.readKernels=options.readKernels??readCodemodeKernelRows,this.readMainHeap=options.readMainHeap??readMainThreadHeapBytes,this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??DEFAULT_HOST_RSS_WARN_MB}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),HOST_MEMORY_SAMPLE_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let footprint=this.readFootprint(),reading={footprintMb:Math.round(footprint.bytes/BYTES_PER_MEGABYTE),measure:footprint.measure,rssMb:Math.round(this.readRssBytes()/BYTES_PER_MEGABYTE),main:{heapBytes:this.readMainHeap()},kernels:this.readKernels()};if(reading.footprintMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(reading));let{footprintMb,measure,rssMb}=reading;this.emit({type:"host_memory_pressure",rssMb,footprintMb,measure,sessions,main:reading.main,kernels:reading.kernels});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<HOST_MEMORY_STDERR_INTERVAL_MS||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb} sessions=${sessions} (idle parking halved)
|
|
3
3
|
`))}};var ZERO_SESSION_TRIM_TICK_MS=1e3,ZERO_SESSION_TRIM_MIN_INTERVAL_MS=6e4,BYTES_PER_MEGABYTE2=1024*1024,ZeroSessionTrimmer=class{constructor(options){this.heldSessions=!1,this.options=options,this.now=options.now??Date.now}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.check(),ZERO_SESSION_TRIM_TICK_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}observe(size){size>0&&(this.heldSessions=!0)}check(){if(this.pending!==void 0&&this.report(this.pending),this.options.sessions()>0){this.heldSessions=!0;return}this.heldSessions&&(this.heldSessions=!1,!(this.lastTrimAt!==void 0&&this.now()-this.lastTrimAt<ZERO_SESSION_TRIM_MIN_INTERVAL_MS)&&this.trim())}trim(){let beforeBytes=this.readFootprint().bytes;this.pending={beforeBytes,collected:(this.options.collect??collectFully)()},this.lastTrimAt=this.now()}report(pending){this.pending=void 0;let after=this.readFootprint();this.options.emit({type:"host_trimmed",footprintBeforeMb:Math.round(pending.beforeBytes/BYTES_PER_MEGABYTE2),footprintAfterMb:Math.round(after.bytes/BYTES_PER_MEGABYTE2),measure:after.measure,collected:pending.collected})}readFootprint(){return(this.options.readFootprint??readOwnFootprint)()}};function collectFully(){let bun=Reflect.get(globalThis,"Bun"),bunGc=typeof bun=="object"&&bun!==null?Reflect.get(bun,"gc"):void 0;if(typeof bunGc=="function")return Reflect.apply(bunGc,bun,[!0]),!0;let nodeGc=Reflect.get(globalThis,"gc");return typeof nodeGc!="function"?!1:(Reflect.apply(nodeGc,globalThis,[]),!0)}var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.cpuUsage=options.cpuUsage??(()=>process.cpuUsage()),this.heapUsed=options.heapUsed??(()=>process.memoryUsage().heapUsed),this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){if(this.timer!==void 0)return;this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage();this.cpuMicrosAtTick=cpu.user+cpu.system,this.heapBytesAtTick=this.heapUsed(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.()}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage(),cpuMicros=cpu.user+cpu.system,heapBytes=this.heapUsed(),previousCpuMicros=this.cpuMicrosAtTick,previousHeapBytes=this.heapBytesAtTick;this.cpuMicrosAtTick=cpuMicros,this.heapBytesAtTick=heapBytes;let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)}; ${describeWindow(processCpuMs,heapDeltaMb)})
|
|
4
4
|
`))}};function startHostObservers(router,writer,options){let loopLag=new LoopLagWatchdog({emit:record=>writer.broadcastHostRecord(record)}),kernels=readCodemodeKernelRows,memory=new HostMemorySampler({emit:record=>writer.broadcastHostRecord(record),sessions:()=>router.sessionCount,onPressure:pressure=>router.setMemoryPressure(pressure),readKernels:kernels,...options.onIdlePressure?{onIdlePressure:options.onIdlePressure}:{}});router.setHostMemoryView({mainHeapBytes:readMainThreadHeapBytes,kernels});let{trim}=options;return loopLag.start(),memory.start(),trim.start(),{stop:()=>{loopLag.stop(),memory.stop(),trim.stop()}}}function createZeroSessionTrim(writer,sessions){return new ZeroSessionTrimmer({emit:record=>writer.broadcastHostRecord(record),sessions})}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)}`)}}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(`
|
|
5
5
|
`)){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}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...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{existsSync}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";var observations=new Set(["get_state","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_session_stats","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"]);function refreshesSessionActivity(command){return!observations.has(command)}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.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}}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing)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)),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)}}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),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)}
|
package/dist/bundle/chunks/{package-manager-cli-NCD5FQGV.js → package-manager-cli-3UIJ4RXY.js}
RENAMED
|
@@ -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{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-
|
|
2
|
+
import{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-5MG76BCM.js";import"./chunk-X6UDRO7J.js";import"./chunk-QNAG7FYM.js";import{DefaultPackageManager,DynamicBorder,keyHint,rawKeyHint}from"./chunk-4GUQVY4Z.js";import{SettingsManager,appendHiddenTuiStdout,initTheme,stopThemeWatcher,theme}from"./chunk-BTYFICUC.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-6EH7QXOG.js";import"./chunk-JABBHOD5.js";import"./chunk-CB77NQMN.js";import"./chunk-VJJ53ORU.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-CM5QTRC2.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-Q2ZTPMWD.js";import"./chunk-F6EQ7EV3.js";import{killProcessTree}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import"./chunk-LUWWM7GA.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
|
|
3
3
|
`)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
|
|
4
4
|
`,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
|
|
5
5
|
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
|
|
@@ -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{classifyCredentialFailure,isCommittedRotationOutput,isRotationStreamStart,rendezvousOrder,resolveConfigValue,rotationErrorFromEvent,runCredentialFailover}from"./chunk-
|
|
2
|
+
import{classifyCredentialFailure,isCommittedRotationOutput,isRotationStreamStart,rendezvousOrder,resolveConfigValue,rotationErrorFromEvent,runCredentialFailover}from"./chunk-Q2ZTPMWD.js";import{activeModelBlockUntil,discoverEnvSlots,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import{acquireHalfOpenLease}from"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-LSE7KE2C.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-6WCOSBI7.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import{listSlots}from"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";async function releaseLeaseIfModelBlocked(repository,providerId,lane,slotName,leaseId,until){until!==void 0&&await repository.mutateSlotState(providerId,lane,slotName,current=>{if(current?.lease?.id!==leaseId)return current;let{lease:_released,...rest}=current;return rest})}function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}function overlayModelBlock(slot,until){return until===void 0||slot.blockedUntil!==void 0&&slot.blockedUntil>=until?slot:{...slot,blockedUntil:until,blockReason:slot.blockReason??"rate_limit"}}async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,modelId=options.modelId,now=sources.now??Date.now,{providerId,credential,env,repository}=sources,policySlots=[];for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,{}):void 0;key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of listSlots(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now());if(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()){let lease=await acquireHalfOpenLease(repository,providerId,"stored",slot.name,{now:(sources.now??Date.now)()});if(!lease)continue;let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name],leasedApplicable=leasedState?.credentialRevision===storedRevision?leasedState:void 0,leasedModelUntil=activeModelBlockUntil(leasedApplicable?.modelBlocks,modelId,now());await releaseLeaseIfModelBlocked(repository,providerId,"stored",slot.name,lease.leaseId,leasedModelUntil),slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedApplicable),leasedModelUntil));continue}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable),modelUntil))}if(policySlots.length===0)return slots;let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases,modelId);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];return listEnvRotationSlots(sources,envSlots,acquireLeases,modelId)}async function listEnvRotationSlots(sources,envSlots,acquireLeases,modelId){if(envSlots.length===0)return[];let{providerId,repository}=sources,now=sources.now??Date.now,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now());if(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()){let lease=await acquireHalfOpenLease(repository,providerId,"env",slot.name,{now:(sources.now??Date.now)()});if(!lease)continue;let leasedState=(await repository.listSlots(providerId,"env"))[slot.name];applicable=leasedState?.credentialRevision===revision?leasedState:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),await releaseLeaseIfModelBlocked(repository,providerId,"env",slot.name,lease.leaseId,modelUntil)}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable),modelUntil))}return slots}var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function modelBlockPatch(family,modelId,blockedUntil,current,now,credentialRevision){let sameMaterial=current!==void 0&¤t.credentialRevision===credentialRevision,{stateVersion:_stateVersion,...kept}=sameMaterial?current:{stateVersion:0};return{...kept,lease:void 0,...credentialRevision===void 0?{}:{credentialRevision},modelBlocks:withModelBlock(sameMaterial?current.modelBlocks:void 0,modelBlockKey(family,modelId),blockedUntil,now)}}function blockPatch(block,current,now,credentialRevision,policy,modelId){if(block.reason==="rate_limit"&&block.modelFamily!==void 0&&modelId!==void 0){let blockedUntil=now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs);return modelBlockPatch(block.modelFamily,modelId,blockedUntil,current,now,credentialRevision)}let failureCount=(current?.failureCount??0)+1,liveModelBlocks=current?.credentialRevision===credentialRevision?pruneModelBlocks(current?.modelBlocks,now):void 0,base={failureCount,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt},...liveModelBlocks===void 0?{}:{modelBlocks:liveModelBlocks}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:{...base,blockReason:block.reason}}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources,options.modelId===void 0?{}:{modelId:options.modelId}),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let winner=(useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:isCommittedRotationOutput,isStreamStart:isRotationStreamStart,errorFromEvent:rotationErrorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,nowMs:now(),cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0,modelBlocks:pruneModelBlocks(current.modelBlocks,now(),options.modelId)}:void 0)},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy,options.modelId))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
|
|
@@ -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{runRpcMode}from"./chunk-
|
|
2
|
+
import{runRpcMode}from"./chunk-X6UDRO7J.js";import"./chunk-BTYFICUC.js";import"./chunk-K4AZKFRB.js";import"./chunk-6EH7QXOG.js";import"./chunk-JABBHOD5.js";import"./chunk-VJJ53ORU.js";import"./chunk-ZJHRDQCH.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-CIRZTP7W.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-LSE7KE2C.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
|
|
@@ -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{RUNNER_HEARTBEAT_INTERVAL_MS,RUNNER_HEARTBEAT_STALE_MS,acquireSessionDeliveryLock,cancelScheduledJob,claimOccurrence,formatScheduledMessage,isCancelled,isOwnerAmong,listScheduledJobs,liveRunners,liveSessionHolders,nextRecurringDueAt,ownRunnerIdentity,pruneTombstones,readJobFile,rearmRecurringJob,removeRunnerLease,restoreAbandonedSchedule,restorePending,scheduleDir,settleOccurrence,writeRunnerLease}from"./chunk-QNAG7FYM.js";import"./chunk-U5KVIAHJ.js";import{killWindowsProcessTree}from"./chunk-JEZWV7JW.js";import{resolveCliMainPath}from"./chunk-
|
|
2
|
+
import{RUNNER_HEARTBEAT_INTERVAL_MS,RUNNER_HEARTBEAT_STALE_MS,acquireSessionDeliveryLock,cancelScheduledJob,claimOccurrence,formatScheduledMessage,isCancelled,isOwnerAmong,listScheduledJobs,liveRunners,liveSessionHolders,nextRecurringDueAt,ownRunnerIdentity,pruneTombstones,readJobFile,rearmRecurringJob,removeRunnerLease,restoreAbandonedSchedule,restorePending,scheduleDir,settleOccurrence,writeRunnerLease}from"./chunk-QNAG7FYM.js";import"./chunk-U5KVIAHJ.js";import{killWindowsProcessTree}from"./chunk-JEZWV7JW.js";import{resolveCliMainPath}from"./chunk-MJGHZT4N.js";import"./chunk-CIRZTP7W.js";import"./chunk-LUWWM7GA.js";import"./chunk-YI7SPFDN.js";import"./chunk-U3VOXCGP.js";import{APP_NAME,getAgentDir,isBunBinary}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";import{mkdirSync,watch}from"node:fs";import{join as join2}from"node:path";import{spawn}from"node:child_process";import{existsSync}from"node:fs";async function deferWhileSessionOpen(job){if(job.sessionFile===null||!existsSync(job.sessionFile))return;let holders=await liveSessionHolders(job.sessionFile,job.sessionId);if(holders.length!==0)return`session is open in pid ${holders.map(holder=>holder.pid).join(", ")}; waiting until it closes`}var STDERR_TAIL_CHARS=2e3,POSIX_GATE='IFS= read -r _ <&3 || exit 75; exec 3<&-; exec "$0" "$@"';function killTree(pid){if(process.platform==="win32"){killWindowsProcessTree(pid);return}try{process.kill(-pid,"SIGKILL")}catch{}}function runDeliveryProcess(launch,timeoutMs,context={}){return new Promise(resolve=>{let posix=process.platform!=="win32",child=posix?spawn("/bin/sh",["-c",POSIX_GATE,launch.command,...launch.args],{cwd:launch.cwd,env:launch.env,stdio:["pipe","ignore","pipe","pipe"],detached:!0}):spawn(launch.command,[...launch.args],{cwd:launch.cwd,env:launch.env,stdio:["pipe","ignore","pipe"],windowsHide:!0,windowsVerbatimArguments:launch.windowsVerbatimArguments===!0}),stderr="",failure,timer=setTimeout(()=>{failure??=`delivery timed out after ${Math.round(timeoutMs/1e3)}s`,child.pid!==void 0&&killTree(child.pid)},timeoutMs);child.stderr?.on("data",chunk=>{stderr=(stderr+chunk.toString("utf8")).slice(-STDERR_TAIL_CHARS)}),child.stdin?.on("error",()=>{});let gate=posix?child.stdio[3]:null;gate?.on("error",()=>{}),child.on("error",error=>{failure??=error.message}),child.on("close",(code,signal)=>{if(clearTimeout(timer),failure!==void 0)resolve({ok:!1,error:failure});else if(code===0)resolve({ok:!0});else{let status=code===null?`signal ${signal}`:`exit code ${code}`;resolve({ok:!1,error:stderr.trim()?`${status}: ${stderr.trim()}`:status})}});let pid=child.pid;pid!==void 0&&Promise.resolve(context.onSpawn?.(pid)).then(()=>{gate!=null&&"end"in gate&&gate.end(`go
|
|
3
3
|
`),child.stdin?.end(launch.stdin??"")},error=>{failure??=`could not register the delivery: ${error instanceof Error?error.message:String(error)}`,killTree(pid)})})}function eventEnv(event){return{...process.env,SENPI_SCHEDULE_ID:event.id,SENPI_SCHEDULE_SESSION_ID:event.sessionId,SENPI_SCHEDULE_SESSION_FILE:event.sessionFile??"",SENPI_SCHEDULE_CWD:event.cwd}}function execHookDelivery(command,timeoutMs){let shell=process.platform==="win32"?{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${command}"`],windowsVerbatimArguments:!0}:{command:"/bin/sh",args:["-c",command]};return(event,context)=>runDeliveryProcess({...shell,env:eventEnv(event),stdin:`${JSON.stringify(event)}
|
|
4
4
|
`,cwd:process.cwd()},timeoutMs,context)}function sessionResumeDelivery(senpi,timeoutMs){return async(event,context)=>existsSync(event.cwd)?event.sessionFile!==null&&!existsSync(event.sessionFile)?{ok:!1,error:`session file no longer exists: ${event.sessionFile}`}:runDeliveryProcess({command:senpi.command,args:[...senpi.args,"-p","--session",event.sessionFile??event.sessionId,event.message],cwd:event.cwd,env:eventEnv(event)},timeoutMs,context):{ok:!1,error:`working directory no longer exists: ${event.cwd}`}}import{join}from"node:path";var DEFERRED_RETRY_MS=15e3,ABANDONED_OCCURRENCE_ERROR="the runner exited while delivering this occurrence; outcome unknown, not retried";async function recoverAbandoned(options,records){let firing=records.filter(record=>record.state==="firing");if(firing.length===0)return{events:[],restoredDueAt:[]};let runners=await(options.runners??(()=>liveRunners(options.dir)))(),events=[],restoredDueAt=[];for(let record of firing){if(record.owner===void 0||record.occurrence===void 0||record.owner.pid===options.owner.pid&&record.owner.processStartedAtMs===options.owner.processStartedAtMs||isOwnerAmong(record.owner,runners))continue;let restored=await restoreAbandonedSchedule(options.dir,record.job,record.occurrence,options.now());restored!==void 0&&restoredDueAt.push(restored.dueAt),await settleOccurrence(options.dir,record.file,record.job,record.occurrence,{ok:!1,error:ABANDONED_OCCURRENCE_ERROR}),events.push({event:"abandoned",id:record.job.id,sessionId:record.job.sessionId,occurrence:record.occurrence,error:ABANDONED_OCCURRENCE_ERROR})}return{events,restoredDueAt}}async function freshPendingJob(options,id){let job=await readJobFile(join(options.dir,"pending",`${id}.json`),id).catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});if(!(job===void 0||job.dueAt>options.now()||await isCancelled(options.dir,id)))return job}async function fireOne(options,listed){let lock=await acquireSessionDeliveryLock(options.dir,listed.sessionId,{maxDeliveryMs:options.deliveryTimeoutMs});if(!lock.acquired){let holder=lock.heldByPid===void 0?"another runner":`process ${lock.heldByPid}`;return{event:"deferred",id:listed.id,sessionId:listed.sessionId,reason:`${holder} is delivering to this session`}}try{let job=await freshPendingJob(options,listed.id);if(job===void 0)return;let deferReason=await options.shouldDefer?.(job);return deferReason!==void 0?{event:"deferred",id:job.id,sessionId:job.sessionId,reason:deferReason}:await deliverClaimed(options,job,pid=>lock.attachDelivery(pid))}finally{await lock.release()}}async function deliverClaimed(options,job,onSpawn){let record=await claimOccurrence(options.dir,job,options.owner);if(record===void 0)return;let occurrence=job.fireCount+1,firedAt=options.now(),nextDueAt;if(job.everyMs!==null){nextDueAt=nextRecurringDueAt(job.dueAt,job.everyMs,firedAt);try{await rearmRecurringJob(options.dir,{...job,fireCount:occurrence,lastFiredAt:firedAt,dueAt:nextDueAt})}catch(error){throw await restorePending(options.dir,record,job.id),error}}let result;try{result=await options.deliver({type:"scheduled_prompt",id:job.id,sessionId:job.sessionId,sessionFile:job.sessionFile,cwd:job.cwd,prompt:job.prompt,message:formatScheduledMessage(job,firedAt),dueAt:job.dueAt,firedAt,everyMs:job.everyMs,fireCount:occurrence},{onSpawn})}catch(error){result={ok:!1,error:error instanceof Error?error.message:String(error)}}return await settleOccurrence(options.dir,record,{...job,fireCount:occurrence,lastFiredAt:firedAt},occurrence,result),{event:"fired",id:job.id,sessionId:job.sessionId,occurrence,outcome:result.ok?"delivered":"failed",...result.ok?{}:{error:result.error},firedAt,dueAt:job.dueAt,...nextDueAt===void 0||await isCancelled(options.dir,job.id)?{}:{nextDueAt}}}async function runDueJobs(options){let listing=await listScheduledJobs(options.dir),events=listing.invalid.map(invalid=>({event:"invalid",...invalid})),recovery=await recoverAbandoned(options,listing.jobs);events.push(...recovery.events),await pruneTombstones(options.dir,listing,options.now());let nextDueAt,noteNext=dueAt=>{nextDueAt=nextDueAt===void 0?dueAt:Math.min(nextDueAt,dueAt)};for(let dueAt of recovery.restoredDueAt)noteNext(dueAt);let bySession=new Map;for(let{state,job}of listing.jobs){if(state!=="pending")continue;if(job.dueAt>options.now()){noteNext(job.dueAt);continue}if(await isCancelled(options.dir,job.id))continue;let queue=bySession.get(job.sessionId)??[];queue.push(job),bySession.set(job.sessionId,queue)}let queues=[...bySession.values()],workers=Math.max(1,Math.min(options.concurrency??4,queues.length)),next=0;return await Promise.all(Array.from({length:workers},async()=>{for(;next<queues.length;){let queue=queues[next++]??[];for(let job of queue){let event;try{event=await fireOne(options,job)}catch(error){let message=error instanceof Error?error.message:String(error);events.push({event:"error",id:job.id,sessionId:job.sessionId,error:message}),noteNext(options.now()+DEFERRED_RETRY_MS);break}if(event!==void 0&&(events.push(event),event.event==="fired"&&event.nextDueAt!==void 0&¬eNext(event.nextDueAt),event.event==="deferred")){noteNext(options.now()+DEFERRED_RETRY_MS);break}}}})),{events,nextDueAt}}function writeLine(value){process.stdout.write(`${JSON.stringify(value)}
|
|
5
5
|
`)}function resolveDelivery(options){let timeoutMs=options.timeoutSeconds*1e3;return options.exec!==void 0?{deliver:execHookDelivery(options.exec,timeoutMs),shouldDefer:void 0}:{deliver:sessionResumeDelivery({command:process.execPath,args:isBunBinary?[]:[...process.execArgv,resolveCliMainPath()]},timeoutMs),shouldDefer:deferWhileSessionOpen}}function reporter(){let deferred=new Map,invalid=new Map;return result=>{let ok=!0,stillInvalid=new Set;for(let event of result.events){if(event.event==="deferred"){if(deferred.get(event.id)===event.reason)continue;deferred.set(event.id,event.reason)}else if(event.event==="invalid"){if(stillInvalid.add(event.file),invalid.get(event.file)===event.error)continue;invalid.set(event.file,event.error)}else event.event==="fired"?(deferred.delete(event.id),event.outcome==="failed"&&(ok=!1)):event.event==="error"&&(ok=!1);writeLine(event)}for(let file of invalid.keys())stillInvalid.has(file)||invalid.delete(file);return ok}}async function guardedPass(pass){try{return await pass()}catch(error){return{events:[{event:"error",error:error instanceof Error?error.message:String(error)}],nextDueAt:void 0}}}async function runPasses(dir,options){let plan=resolveDelivery(options),owner=ownRunnerIdentity(),startedAt=Date.now(),lease=()=>writeRunnerLease(dir,{startedAt,watch:options.watch,exec:options.exec??null},Date.now()),report=reporter(),pass=()=>runDueJobs({dir,now:Date.now,deliver:plan.deliver,owner,concurrency:options.concurrency,deliveryTimeoutMs:options.timeoutSeconds*1e3,shouldDefer:plan.shouldDefer});await lease();let leaseFailing=!1,heartbeat=setInterval(()=>{lease().then(()=>{leaseFailing=!1},error=>{leaseFailing||writeLine({event:"lease_error",error:error instanceof Error?error.message:String(error)}),leaseFailing=!0})},RUNNER_HEARTBEAT_INTERVAL_MS),watcher,stopping=!1,wake,stop=()=>{stopping=!0,wake?.()};try{if(!options.watch)return report(await guardedPass(pass))?0:1;process.on("SIGTERM",stop),process.on("SIGINT",stop);let pendingDir=join2(dir,"pending");for(mkdirSync(pendingDir,{recursive:!0,mode:448}),watcher=watch(pendingDir,()=>wake?.()),writeLine({event:"watching",pid:process.pid,dir,pollSeconds:options.pollSeconds});!stopping;){let rescan=!1,woken=new Promise(resolve=>{wake=()=>{rescan=!0,resolve()}}),result=await guardedPass(pass);if(report(result),stopping)break;if(rescan)continue;let untilDue=result.nextDueAt===void 0?Number.POSITIVE_INFINITY:result.nextDueAt-Date.now(),waitMs=Math.max(0,Math.min(options.pollSeconds*1e3,untilDue)),timer;await Promise.race([woken,new Promise(resolve=>timer=setTimeout(resolve,waitMs))]),clearTimeout(timer)}return writeLine({event:"stopped",pid:process.pid}),0}finally{clearInterval(heartbeat),watcher?.close(),process.off("SIGTERM",stop),process.off("SIGINT",stop),await removeRunnerLease(dir)}}var EXIT_OK=0,EXIT_FAILED=1,EXIT_USAGE=2,DEFAULT_POLL_SECONDS=60,DEFAULT_TIMEOUT_SECONDS=900,DEFAULT_CONCURRENCY=4,USAGE=`usage: ${APP_NAME} schedule <list|cancel|run> [options]
|