@code-yeongyu/senpi 2026.10.24-2 → 2026.10.24-3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/bundle/chunks/chunk-4TRKE3ZC.js +7 -0
- package/dist/bundle/chunks/chunk-7IRLFYNM.js +23 -0
- package/dist/bundle/chunks/{chunk-FIBIVBQK.js → chunk-7UUOGZKR.js} +1 -1
- package/dist/bundle/chunks/{chunk-ONLNXGO3.js → chunk-AVLYZET7.js} +1 -1
- package/dist/bundle/chunks/{chunk-VZAYN5SB.js → chunk-CYG4LS4S.js} +1 -1
- package/dist/bundle/chunks/chunk-CZYADQ2E.js +8 -0
- package/dist/bundle/chunks/{chunk-OA5INWHI.js → chunk-DITSGW4R.js} +68 -8
- package/dist/bundle/chunks/{chunk-IELM5U6I.js → chunk-DYWHYQUD.js} +2 -2
- package/dist/bundle/chunks/chunk-EWOEVVQT.js +4 -0
- package/dist/bundle/chunks/{chunk-RQHK4QZ5.js → chunk-FWXMMMCV.js} +1 -1
- package/dist/bundle/chunks/{chunk-HHYSXDYP.js → chunk-GOB5BLDV.js} +1 -1
- package/dist/bundle/chunks/{chunk-BRXN5R2F.js → chunk-H6IG2ITJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-3N2PQEQV.js → chunk-I5NIJZDY.js} +1 -1
- package/dist/bundle/chunks/chunk-II22E3CV.js +3 -0
- package/dist/bundle/chunks/chunk-MRN6IKOQ.js +27 -0
- package/dist/bundle/chunks/{chunk-QQSCUEYJ.js → chunk-RHHBXIRN.js} +2 -5
- package/dist/bundle/chunks/chunk-RVYSJBZ7.js +7 -0
- package/dist/bundle/chunks/{chunk-RAIZG6HA.js → chunk-V3CK2AVC.js} +1 -1
- package/dist/bundle/chunks/{chunk-HRPMLI7O.js → chunk-VRDU425E.js} +2 -2
- package/dist/bundle/chunks/{chunk-OUPD5LWY.js → chunk-XUFUKDKJ.js} +3 -3
- package/dist/bundle/chunks/{chunk-QEQG42HL.js → chunk-ZGAB7WQA.js} +1 -1
- package/dist/bundle/chunks/cli-main-BOYWBHOB.js +3 -0
- package/dist/bundle/chunks/host-command-7MAXSZIH.js +2 -0
- package/dist/bundle/chunks/host-lifecycle-U36U7JTE.js +3 -0
- package/dist/bundle/chunks/host-lifecycle.js +26 -21
- package/dist/bundle/chunks/host-session-command-L2UTORL5.js +20 -0
- package/dist/bundle/chunks/{host-socket-request-KKGH3JHV.js → host-socket-request-ZDJGSSZO.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-NVBFOE5R.js +2 -0
- package/dist/bundle/chunks/{multi-session-host-O5GZQSRL.js → multi-session-host-3TVASSQD.js} +12 -12
- package/dist/bundle/chunks/{package-manager-cli-LC5GAGTW.js → package-manager-cli-5BHVDVJC.js} +1 -1
- package/dist/bundle/chunks/{role-4G43UDOC.js → role-BHA5ROSF.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-LPP46I7H.js +2 -0
- package/dist/bundle/chunks/rpc-monitor-source-OL5KU6NO.js +3 -0
- package/dist/bundle/chunks/{schedule-command-QNCVE4HM.js → schedule-command-QW67J57R.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-QQBBY5AT.js +3 -0
- package/dist/bundle/chunks/session-worker.js +425 -359
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +26 -21
- 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/cli/host-command-args.d.ts +33 -0
- package/dist/cli/host-command-args.js +145 -0
- package/dist/cli/host-command.d.ts +1 -30
- package/dist/cli/host-command.js +5 -137
- package/dist/cli/host-session-command.d.ts +1 -0
- package/dist/cli/host-session-command.js +5 -3
- package/dist/core/extensions/builtin/prompt-preset/contract.js +6 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.js +93 -0
- package/dist/core/extensions/builtin/prompt-preset/matchers.d.ts +2 -0
- package/dist/core/extensions/builtin/prompt-preset/matchers.js +9 -0
- package/dist/core/extensions/builtin/prompt-preset/presets.js +3 -0
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.d.ts +2 -1
- package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.js +12 -4
- package/dist/modes/rpc/host-admission-proxy.d.ts +2 -1
- package/dist/modes/rpc/host-admission-proxy.js +10 -9
- package/dist/modes/rpc/host-cli-entry.d.ts +2 -0
- package/dist/modes/rpc/host-cli-entry.js +13 -1
- package/dist/modes/rpc/host-ensure-client.d.ts +5 -1
- package/dist/modes/rpc/host-ensure-client.js +8 -0
- package/dist/modes/rpc/host-ensure-types.d.ts +1 -0
- package/dist/modes/rpc/host-ensure.js +6 -11
- package/dist/modes/rpc/host-gc-pass.js +3 -0
- package/dist/modes/rpc/host-gc.js +3 -0
- package/dist/modes/rpc/host-internal-transport.d.ts +16 -5
- package/dist/modes/rpc/host-internal-transport.js +40 -9
- package/dist/modes/rpc/host-lifecycle-proxy.d.ts +4 -8
- package/dist/modes/rpc/host-lifecycle-proxy.js +9 -21
- package/dist/modes/rpc/host-lifecycle-shutdown.d.ts +2 -0
- package/dist/modes/rpc/host-lifecycle-shutdown.js +3 -0
- package/dist/modes/rpc/host-lifecycle.js +9 -16
- package/dist/modes/rpc/host-observe-request.js +1 -1
- package/dist/modes/rpc/host-probe.d.ts +8 -6
- package/dist/modes/rpc/host-probe.js +13 -13
- package/dist/modes/rpc/host-request-key-root.d.ts +8 -0
- package/dist/modes/rpc/host-request-key-root.js +14 -0
- package/dist/modes/rpc/host-runner.d.ts +3 -1
- package/dist/modes/rpc/host-runner.js +6 -1
- package/dist/modes/rpc/host-socket-bind.d.ts +6 -0
- package/dist/modes/rpc/host-socket-bind.js +42 -0
- package/dist/modes/rpc/host-socket-request.d.ts +3 -2
- package/dist/modes/rpc/host-socket-request.js +55 -10
- package/dist/modes/rpc/host-status.d.ts +3 -2
- package/dist/modes/rpc/host-status.js +5 -0
- package/dist/modes/rpc/host-supervisor-log.d.ts +1 -0
- package/dist/modes/rpc/host-supervisor-log.js +3 -0
- package/dist/modes/rpc/host-watchdog.d.ts +8 -1
- package/dist/modes/rpc/host-watchdog.js +37 -12
- package/dist/modes/rpc/internal-channel.js +14 -14
- package/dist/modes/rpc/multi-session-host.js +18 -46
- package/dist/modes/rpc/rpc-auth-client.d.ts +13 -0
- package/dist/modes/rpc/rpc-auth-client.js +142 -0
- package/dist/modes/rpc/rpc-auth-proof.d.ts +12 -0
- package/dist/modes/rpc/rpc-auth-proof.js +27 -0
- package/dist/modes/rpc/rpc-client-socket.d.ts +5 -0
- package/dist/modes/rpc/rpc-client-socket.js +30 -0
- package/dist/modes/rpc/rpc-client.d.ts +2 -0
- package/dist/modes/rpc/rpc-client.js +2 -24
- package/dist/modes/rpc/rpc-host-command-types.d.ts +4 -0
- package/dist/modes/rpc/rpc-protocol-info-types.d.ts +6 -0
- package/dist/modes/rpc/rpc-public-auth.d.ts +41 -0
- package/dist/modes/rpc/rpc-public-auth.js +237 -0
- package/dist/modes/rpc/rpc-public-key.d.ts +28 -0
- package/dist/modes/rpc/rpc-public-key.js +193 -0
- package/dist/modes/rpc/socket-ownership.d.ts +7 -0
- package/dist/modes/rpc/socket-ownership.js +17 -0
- package/docs/rpc.md +108 -2
- package/docs/settings.md +1 -1
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-3474DPZK.js +0 -2
- package/dist/bundle/chunks/chunk-64CFJHKT.js +0 -7
- package/dist/bundle/chunks/chunk-B6NJHBLH.js +0 -21
- package/dist/bundle/chunks/chunk-HZTQHE5O.js +0 -26
- package/dist/bundle/chunks/chunk-IBDADH5Z.js +0 -4
- package/dist/bundle/chunks/chunk-OJZD7CO7.js +0 -8
- package/dist/bundle/chunks/cli-main-4JNPG6LB.js +0 -3
- package/dist/bundle/chunks/host-command-I3ZMWQQ3.js +0 -2
- package/dist/bundle/chunks/host-lifecycle-QEO422VW.js +0 -3
- package/dist/bundle/chunks/host-session-command-INULKX6E.js +0 -20
- package/dist/bundle/chunks/interactive-mode-SYWJVPKK.js +0 -2
- package/dist/bundle/chunks/rpc-mode-JMCYSP4P.js +0 -2
- package/dist/bundle/chunks/rpc-monitor-source-34AQDTZ6.js +0 -3
- package/dist/bundle/chunks/session-control-endpoint-IW5X56WN.js +0 -3
|
@@ -1,4 +0,0 @@
|
|
|
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{socketNeedsHandshake}from"./chunk-3474DPZK.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-QEQG42HL.js";import{createConnection}from"node:net";var PROBE_REQUEST_ID="ensure-host-probe";async function requestOnSocket(socketPath,command,timeoutMs){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,...command},timeoutMs)).answer}async function connectAndAsk(socketPath,request,timeoutMs,keep=!1){let secret;if(socketNeedsHandshake(socketPath))try{secret=await readSocketSecret(socketSecretPath(socketPath))}catch{return{connected:!1,answer:void 0}}return new Promise(resolveProbe=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),buffer="",settled=!1,connected=!1,finish=value=>{if(!settled){if(settled=!0,clearTimeout(timeout),keep&&value!==void 0&&!socket.destroyed){resolveProbe({connected,answer:value,kept:socket});return}socket.destroy(),resolveProbe({connected,answer:value})}},timeout=setTimeout(()=>finish(),timeoutMs);socket.once("connect",()=>{connected=!0,socket.write(`${JSON.stringify(request)}
|
|
3
|
-
`)}),socket.on("data",chunk=>{for(buffer+=chunk.toString("utf8");;){let newline=buffer.indexOf(`
|
|
4
|
-
`);if(newline===-1)return;let line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);let answer=readAnswer(line);if(answer!==void 0)return finish(answer)}}),socket.once("error",()=>finish()),socket.once("close",()=>finish()),secret&&sendSocketHandshake(socket,secret)})}function readAnswer(text,id=PROBE_REQUEST_ID){let parsed;try{parsed=JSON.parse(text)}catch{return}if(!(!isRecord(parsed)||parsed.id!==id||parsed.success!==!0))return parsed.data??{}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}export{PROBE_REQUEST_ID,requestOnSocket,connectAndAsk,readAnswer,isRecord};
|
|
@@ -1,8 +0,0 @@
|
|
|
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{RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_UNKNOWN_COMMAND,SUMMARIZATION_MAX_DURATION_CAP_MS,SUMMARIZATION_TOTAL_BUDGET_MS,clientMessageIdentity,isAbortGraceInRange}from"./chunk-GY5MR5KR.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{DETACH_CONNECTION_CAPABILITY}from"./chunk-64CFJHKT.js";import{socketNeedsHandshake}from"./chunk-3474DPZK.js";import{ORIGIN_HOST_INSTANCE_FIELD,attachJsonlLineReader,originHostInstance,serializeJsonLine}from"./chunk-QQSCUEYJ.js";import{fuzzyFilter}from"./chunk-YJA2B7FQ.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-QEQG42HL.js";var COMMAND_TOKEN=/^\/[A-Za-z][A-Za-z0-9:_-]*$/,MAX_SUGGESTIONS=3,UnknownCommandError=class extends Error{constructor(command,suggestions,reason){super(formatUnknownCommandMessage(command,suggestions,reason)),this.name="UnknownCommandError",this.command=command,this.suggestions=suggestions,this.reason=reason}};function formatUnknownCommandMessage(command,suggestions,reason){if(reason==="interactive_only")return`/${command} is an interactive command and cannot be sent as a prompt.`;let hint=suggestions.length===0?"":` Did you mean ${suggestions.map(name=>`/${name}`).join(", ")}?`;return`Unknown command /${command}.${hint}`}var UNKNOWN_COMMAND_CONFIRM_HINT='Resend with "unknownCommandAsText": true to send it as text.';function unknownCommandErrorFromWire(data){if(typeof data!="object"||data===null)return;let command=Reflect.get(data,"command"),suggestions=Reflect.get(data,"suggestions"),reason=Reflect.get(data,"reason");if(typeof command!="string"||!Array.isArray(suggestions)||reason!=="unknown"&&reason!=="interactive_only")return;let names=suggestions.filter(name=>typeof name=="string");return new UnknownCommandError(command,names,reason)}function commandShapedName(text){let token=text.trim().split(/\s/,1)[0]??"";return COMMAND_TOKEN.test(token)?token.slice(1):void 0}function findUnknownCommand(text,catalog){let command=commandShapedName(text);if(command===void 0||catalog.promptCommands.has(command))return;if(catalog.interactiveCommands.has(command))return new UnknownCommandError(command,[],"interactive_only");let known=[...new Set([...catalog.promptCommands,...catalog.interactiveCommands])],suggestions=fuzzyFilter(known,command,name=>name).slice(0,MAX_SUGGESTIONS);return new UnknownCommandError(command,suggestions,"unknown")}import{existsSync}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
|
|
3
|
-
Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
|
|
4
|
-
Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
|
|
5
|
-
${issue.sessionCwd}
|
|
6
|
-
|
|
7
|
-
continue in current cwd
|
|
8
|
-
${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{spawn}from"node:child_process";import{createConnection}from"node:net";var REQUEST_DEADLINE_MS=3e4;function requestDeadlineMs(command){return command.type!=="abort"||command.awaitIdle!==!0?REQUEST_DEADLINE_MS:command.graceMs===void 0?1e4+REQUEST_DEADLINE_MS:isAbortGraceInRange(command.graceMs)?command.graceMs+REQUEST_DEADLINE_MS:REQUEST_DEADLINE_MS}var PROMPT_COMPACTION_DEADLINE_MS=SUMMARIZATION_TOTAL_BUDGET_MS+SUMMARIZATION_MAX_DURATION_CAP_MS+REQUEST_DEADLINE_MS,PROMPT_ACK_MAX_WAIT_MS=PROMPT_COMPACTION_DEADLINE_MS+REQUEST_DEADLINE_MS,OPEN_AFTER_QUEUED_DEADLINE_MS=10*6e4,PROMPT_AFTER_QUEUED_DEADLINE_MS=5*6e4;function promptStalledMessage(){return`prompt was received by the host but not accepted within ${PROMPT_AFTER_QUEUED_DEADLINE_MS/6e4} minutes`}function openStalledMessage(position){let queued=typeof position=="number"?` at queue position ${position}`:"",minutes=OPEN_AFTER_QUEUED_DEADLINE_MS/6e4;return`open_session was accepted by the host${queued} but not answered within ${minutes} minutes`}var RpcRequestTimeoutError=class extends Error{constructor(message){super(message),this.code="rpc_request_timeout",this.name="RpcRequestTimeoutError"}};function armRequestDeadline(ms,message,expire){let timer=setTimeout(()=>expire(new RpcRequestTimeoutError(message())),ms);return{extend(nextMs,nextMessage){clearTimeout(timer),timer=setTimeout(()=>expire(new RpcRequestTimeoutError(nextMessage())),nextMs)},clear(){clearTimeout(timer)}}}var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.compactions=new Map,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.originHost=originHostInstance(),this.options=options,this.onEvent(event=>{switch(event.type){case"compaction_start":{let key=event.requestId??"";if(this.compactions.has(key))return;this.compactions.set(key,Date.now());break}case"compaction_end":if(!this.compactions.delete(event.requestId??""))return;break;case"session_replaced":this.compactions.clear();break;default:return}for(let pending of this.pendingRequests.values())pending.sessionId===this.sessionId&&pending.onCompaction?.(this.isCompacting())})}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.compactions.clear(),this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&this.options.model&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve=>setTimeout(resolve,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}isCompacting(){let now=Date.now();for(let[key,startedAt]of this.compactions)now-startedAt>=PROMPT_COMPACTION_DEADLINE_MS&&this.compactions.delete(key);return this.compactions.size>0}async stop(){if(this.compactions.clear(),this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,signalSpawnedChild(this.process,"SIGTERM"),await new Promise(resolve=>{let timeout=setTimeout(()=>{this.process&&signalSpawnedChild(this.process,"SIGKILL"),resolve()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=socketNeedsHandshake(path)?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve,reject)=>{let onConnect=()=>{cleanup(),resolve()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.compactions.clear(),this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async resumeSession(){await this.send({type:"resume_session"})}async pauseForRun(command){return this.getData(await this.send({...command,type:"pause_for_run"}))}async resumeForRun(command){return this.getData(await this.send({...command,type:"resume_for_run"}))}async holdInput(command){return this.getData(await this.send({...command,type:"hold_input"}))}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async unloadSession(options){let sessionId=options.sessionId??this.sessionId;if(!sessionId)throw new Error("unload_session needs a session");return this.getData(await this.send({...options,type:"unload_session",sessionId},!1))}async setSessionContext(patch,sessionId=this.sessionId){if(!sessionId)throw new RpcCommandError(`${RPC_ERROR_SESSION_NOT_ATTACHED}: set_session_context needs a session`,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this client has no attached session",action:"attach with openSession first, or pass a sessionId"});this.getData(await this.send({type:"set_session_context",sessionId,patch},!1))}async closeSession(sessionId=this.sessionId){if(sessionId){try{this.getData(await this.send({type:"close_session",sessionId},!1))}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0,this.compactions.clear())}}async detachConnection(){let info=this.getData(await this.send({type:"get_protocol_info"},!1));if(!Array.isArray(info.capabilities)||!info.capabilities.includes(DETACH_CONNECTION_CAPABILITY))return"unsupported";let data=this.getData(await this.send({type:"detach_connection"},!1));return{deferred:Array.isArray(data?.deferred)?data.deferred.filter(id=>typeof id=="string"):[]}}async listSessions(options){let response=await this.send({type:"list_sessions",...options},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...clientMessageIdentity(options),...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options.unknownCommandAsText?{unknownCommandAsText:!0}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success){let failure=response;throw(failure.errorCode===RPC_ERROR_UNKNOWN_COMMAND?unknownCommandErrorFromWire(failure.errorData):void 0)??new RpcCommandError(failure.error,failure.errorCode,failure.errorData)}return response.data?.disposition??"handled"}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async continueFromLeaf(){let response=await this.send({type:"continue_from_leaf"});this.getData(response)}async steer(message,images,recovery){let response=await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder,...clientMessageIdentity(recovery)});return this.getData(response)?.disposition??"handled"}async followUp(message,images,recovery){let response=await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder,...clientMessageIdentity(recovery)});return this.getData(response)?.disposition??"handled"}async abort(options){if(options===void 0){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}return}return this.getData(await this.send({...options,type:"abort"}))}async getEffectStatus(effectId,options={}){let command={type:"get_effect_status",effectId,...options.sessionPath===void 0?{}:{sessionPath:options.sessionPath}};return this.getData(await this.send(command,options.sessionPath===void 0))}async getPendingInputs(knownClientMessageIds){let command={type:"get_pending_inputs",...knownClientMessageIds===void 0?{}:{knownClientMessageIds:[...knownClientMessageIds]}};return this.getData(await this.send(command))}async abortStrict(){this.getData(await this.send({type:"abort"}))}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async getModelThinkingLevel(provider,modelId){let response=await this.send({type:"get_model_thinking_level",provider,modelId});return this.getData(response)}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async setRetryFallback(retryFallback){await this.send({type:"set_retry_fallback",retryFallback})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async resolvePath(path){let response=await this.send({type:"resolve_path",path});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since,page){let response=await this.send({type:"get_entries",since,...page});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async editUserMessage(entryId,text,options={}){let response=await this.send({type:"edit_user_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async recordDraftActivity(){await this.send({type:"record_user_activity",kind:"draft"})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async listEvalCells(){return this.getData(await this.send({type:"eval_cells.list"}))}async peekEvalCell(cellId,tailBytes){return this.getData(await this.send({type:"eval_cells.peek",cellId,...tailBytes===void 0?{}:{tailBytes}}))}async stopEvalCell(cellId){return this.getData(await this.send({type:"eval_cells.stop",cellId}))}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async orderProviderAccounts(provider,names){await this.send({type:"account_order",provider,names})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve())})})}collectEvents(timeout=6e4){return new Promise((resolve,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||event.type==="queued"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(data.type==="queued"&&typeof data.for_request=="string"&&this.pendingRequests.get(data.for_request)?.onQueued?.(data.position),typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of[...this.eventListeners])listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of[...this.eventListeners])listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{},...this.socket&&this.originHost?{[ORIGIN_HOST_INSTANCE_FIELD]:this.originHost}:{}};if(!expectResponse)return stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0});let sessionId="sessionId"in fullCommand?fullCommand.sessionId:void 0;return new Promise((resolve,reject)=>{let timeoutMessage=()=>`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`,promptCap,promptReceived=!1,expire=timeoutError=>{clearTimeout(promptCap);let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(timeoutError),reject(timeoutError)},deadline=armRequestDeadline(command.type==="prompt"&&sessionId===this.sessionId&&this.isCompacting()?PROMPT_COMPACTION_DEADLINE_MS:requestDeadlineMs(command),timeoutMessage,expire);command.type==="prompt"&&(promptCap=setTimeout(()=>{deadline.clear(),expire(new RpcRequestTimeoutError(timeoutMessage()))},PROMPT_ACK_MAX_WAIT_MS)),this.pendingRequests.set(id,{sessionId,resolve:response=>{deadline.clear(),clearTimeout(promptCap),resolve(response)},reject:error=>{deadline.clear(),clearTimeout(promptCap),reject(error)},...command.type==="prompt"?{onCompaction:compacting=>compacting?deadline.extend(PROMPT_COMPACTION_DEADLINE_MS,timeoutMessage):promptReceived?deadline.extend(PROMPT_AFTER_QUEUED_DEADLINE_MS,promptStalledMessage):deadline.extend(REQUEST_DEADLINE_MS,timeoutMessage),onQueued:()=>{promptReceived=!0,this.isCompacting()||deadline.extend(PROMPT_AFTER_QUEUED_DEADLINE_MS,promptStalledMessage)}}:{},...command.type==="open_session"?{onQueued:position=>deadline.extend(OPEN_AFTER_QUEUED_DEADLINE_MS,()=>openStalledMessage(position))}:{},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}})}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{UnknownCommandError,UNKNOWN_COMMAND_CONFIRM_HINT,commandShapedName,findUnknownCommand,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcRequestTimeoutError,RpcCommandError,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
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"./chunk-MYAENL22.js";import{enableStartupCompileCache}from"./chunk-3N2PQEQV.js";import"./chunk-IELM5U6I.js";import{installStaleExtensionContainment,main}from"./chunk-OA5INWHI.js";import"./chunk-OJZD7CO7.js";import"./chunk-CZR7C6CY.js";import{configureHttpDispatcher}from"./chunk-LR6Z6V54.js";import"./chunk-DXJJP6RP.js";import"./chunk-HCF5M6NA.js";import"./chunk-HHYSXDYP.js";import"./chunk-GY5MR5KR.js";import"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-FIBIVBQK.js";import"./chunk-SGATKHO4.js";import"./chunk-MLVIYDHK.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-VUKNGMDT.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-HZTQHE5O.js";import"./chunk-64CFJHKT.js";import"./chunk-QMRJYMNH.js";import"./chunk-RQHK4QZ5.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-BRXN5R2F.js";import"./chunk-YJA2B7FQ.js";import"./chunk-JAXZOEJE.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-ONLNXGO3.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
|
|
@@ -1,2 +0,0 @@
|
|
|
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,resolveHostSocket,runHostCommand}from"./chunk-HZTQHE5O.js";import"./chunk-64CFJHKT.js";import"./chunk-QMRJYMNH.js";import"./chunk-RQHK4QZ5.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
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{INTERNAL_SUPERVISOR_FLAG,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,runHostSupervisor,spawnableChildLaunch}from"./chunk-B6NJHBLH.js";import{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,IdleExitDecider,parseColdStart,parseIdleExitMs,resolveHostPolicy}from"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-7ASLQ243.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};
|
|
@@ -1,20 +0,0 @@
|
|
|
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{RpcClient,RpcCommandError,RpcRequestTimeoutError,RpcTransportGoneError,isTransportGoneError}from"./chunk-OJZD7CO7.js";import"./chunk-GY5MR5KR.js";import{SessionManager,assertValidSessionId}from"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-KLAX467B.js";import"./chunk-SOMFLLPD.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,STOP_WAIT_BUDGET_MS,daemonEnvKeys,daemonEnvOverrides,emit,ensureHost,loadHostLaunchSpec,refusal,resolveHostSocket,writeDaemonEnvKeys}from"./chunk-HZTQHE5O.js";import{HostEnsureRefusedError}from"./chunk-64CFJHKT.js";import"./chunk-QMRJYMNH.js";import{endpointKindOfSocket}from"./chunk-RQHK4QZ5.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import{canonicalSessionPath,createHostDaemonPaths}from"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-YJA2B7FQ.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import{APP_NAME,getAgentDir}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";import{readFileSync}from"node:fs";import{resolve}from"node:path";var DETACH_ACK_TIMEOUT_MS=5e3;async function detachBeforeClose(client,report,timeoutMs=DETACH_ACK_TIMEOUT_MS){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),timeoutMs)});try{await Promise.race([client.detachConnection(),late])==="late"&&report(`the host did not confirm the detach within ${timeoutMs} ms; closing the connection anyway`)}catch(error){if(error instanceof RpcTransportGoneError)return;report(`the host refused the detach (${error instanceof Error?error.message:String(error)}); closing the connection anyway`)}finally{clearTimeout(timer)}}var USAGE_CODES=new Set(["missing_session_id","invalid_path","invalid_session_context","invalid_session_kind","invalid_launch_profile","invalid_session_id","invalid_release_reason","empty","unknown_command"]),FAILURE_CODES=new Set(["open_failed","warm_failed","release_failed"]),REASON_FOR_CODE={streaming:"busy",not_found:"unknown_cursor"},BARE_CODE=/^[a-z][a-z0-9_]*$/;function mapError(error,socket){let detail=error instanceof Error?error.message:String(error);if(error instanceof RpcCommandError){let code=error.errorCode??(BARE_CODE.test(detail)?detail:void 0);if(code===void 0)return hostError(detail,socket);let exitCode=USAGE_CODES.has(code)?HOST_EXIT_USAGE:FAILURE_CODES.has(code)?HOST_EXIT_ERROR:HOST_EXIT_REFUSED;return{exitCode,payload:{action:exitCode===HOST_EXIT_REFUSED?"refuse":"error",reason:REASON_FOR_CODE[code]??code,detail,socket,...error.errorData!==void 0&&{data:error.errorData}}}}return isTransportGoneError(error)?{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"transport_gone",detail,socket}}:hostError(detail,socket)}function hostError(detail,socket){return{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"host_error",detail,socket}}}async function openHostSession(client,request,socket,ensured){let opened=await client.openSession({cwd:request.cwd,retain_on_disconnect:!0,...request.model&&{provider:request.model.provider,modelId:request.model.id}});ensured?.release();let{state}=opened,identity={sessionId:opened.sessionId,sessionPath:state.sessionFile,durableSessionId:state.sessionId};try{request.name!==void 0&&await client.setSessionName(request.name);let disposition=request.prompt===void 0?void 0:await client.prompt(request.prompt);return{exitCode:HOST_EXIT_OK,payload:{action:"open",socket,pid:ensured?.pid,reused:ensured?.reused,...identity,cwd:state.cwd,model:state.model?{provider:state.model.provider,id:state.model.id}:null,attached:opened.attached??!1,...disposition!==void 0&&{prompt:{disposition}}}}}catch(error){let outcome=mapError(error,socket),closed=await closeOpened(client,opened.sessionId);return{...outcome,payload:{...outcome.payload,...identity,closed}}}}async function closeOpened(client,sessionId){try{return await client.closeSession(sessionId),!(await client.listSessions()).some(row=>row.sessionId===sessionId)}catch{return!1}}import{existsSync}from"node:fs";import{readdir}from"node:fs/promises";import{dirname,join}from"node:path";async function resolveSessionRef(client,ref,agentDir){let rows=await client.listSessions(),handle=rows.find(row=>row.sessionId===ref);if(handle)return{kind:"live",row:handle};if(isSessionId(ref)){let byId=await resolveDurableId(ref,rows,agentDir);if(byId)return byId}let named=rows.filter(row=>row.name===ref);if(named.length>1)return{kind:"ambiguous",candidates:named.map(row=>row.sessionId)};let live=named[0]??rows.find(row=>row.sessionPath!==void 0&&samePath(row.sessionPath,ref));return live?{kind:"live",row:live}:looksLikePath(ref)?parkedByPath(ref):{kind:"unknown"}}async function resolveDurableId(id,rows,agentDir){let liveRows=rows.filter(row=>row.durableSessionId===id),transcripts=(await transcriptsUnder(agentDir)).filter(session=>session.id===id),files=new Set([...liveRows.map(row=>row.sessionPath===void 0?row.sessionId:canonicalSessionPath(row.sessionPath)),...transcripts.map(session=>canonicalSessionPath(session.path))]);return files.size>1?{kind:"ambiguous",candidates:[...files]}:liveRows[0]?{kind:"live",row:liveRows[0]}:transcripts[0]?parked(transcripts[0]):void 0}function isSessionId(ref){try{return assertValidSessionId(ref),!0}catch{return!1}}function looksLikePath(ref){return ref.includes("/")||ref.includes("\\")||ref.endsWith(".jsonl")}async function parkedByPath(ref){let path=canonicalSessionPath(ref);if(!existsSync(path))return{kind:"unknown"};let info=(await SessionManager.listAll(dirname(path))).find(session=>samePath(session.path,path));return info?parked(info):{kind:"unknown"}}async function transcriptsUnder(agentDir){let root=join(agentDir,"sessions");if(!existsSync(root))return[];let dirs=(await readdir(root,{withFileTypes:!0})).filter(entry=>entry.isDirectory());return(await Promise.all(dirs.map(entry=>SessionManager.listAll(join(root,entry.name))))).flat()}function parked(info){return{kind:"parked",sessionPath:info.path,cwd:info.cwd,durableSessionId:info.id}}function samePath(left,right){return canonicalSessionPath(left)===canonicalSessionPath(right)}function waitForHostSession(client,sessionId,request,onTransportLoss){let started=Date.now();return new Promise((resolveWait,reject)=>{let finished=!1,observed=!1,state,timer,cleanup=()=>{finished=!0,clearTimeout(timer),unsubscribe(),onTransportLoss(void 0)},fail=error=>{finished||(cleanup(),reject(error))},finish=outcome=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_OK,payload:{action:"wait",sessionId,until:request.until,outcome,waited_ms:Date.now()-started,state:{isStreaming:state?.isStreaming??!1,pendingMessageCount:state?.pendingMessageCount??0,lastAbortSource:state?.lastAbortSource??null}}}))},unsubscribe=client.onEvent(record=>{let event=record;if(event.type==="session_closed"||event.type==="session_parked"){finish(event.type);return}if(event.type==="agent_settled"&&"reason"in event&&event.reason==="session_closed"){finish("session_closed");return}event.type!=="agent_idle"&&!(request.until==="done"&&event.type==="agent_settled")||(observed=!0,client.getState().then(snapshot=>{state=snapshot,request.until==="done"?finish("done"):isDrained(snapshot)&&finish("idle")},fail))});onTransportLoss(fail),timer=setTimeout(()=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"wait_timeout",sessionId,until:request.until,timeoutMs:request.timeoutMs}}))},request.timeoutMs),client.getState().then(snapshot=>{state=snapshot,!observed&&(request.until==="done"?!snapshot.isStreaming:isDrained(snapshot))&&finish("already_idle")},fail)})}function isDrained(state){return!state.isStreaming&&state.steering.length===0&&state.followUp.length===0&&state.ordered.length===0&&state.pendingMessageCount===0}async function runHostSessionRequest(request){let deadline=Date.now()+STOP_WAIT_BUDGET_MS;for(;;)try{return await runHostSessionRequestOnce(request,Math.max(0,deadline-Date.now()))}catch(error){if(request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping"&&Date.now()<deadline)continue;return mapError(error,request.target.socket)}}async function runHostSessionRequestOnce(request,stoppingTimeoutMs){let{socket,agentDir}=request.target,client,ensured,disconnected,connectionUnusable=!1;try{if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"});request.action==="open"&&(ensured=await ensureHost({socket,agentDir,hostArgs:request.spec.hostArgs,env:daemonEnvOverrides(process.env,request.spec.env),policy:request.spec.policy,upgrade:"never",stoppingTimeoutMs}),ensured.reused||await writeDaemonEnvKeys(createHostDaemonPaths({socket,agentDir}),daemonEnvKeys(process.env,request.spec.env))),client=new RpcClient({socketPath:socket,onDisconnect:error=>{connectionUnusable=!0,disconnected?.(error)}});try{await client.start()}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ECONNREFUSED"))return refusal("refuse",void 0,{reason:"host_unavailable",socket,detail:error.message});throw error}let sessionId,durableSessionId;if("ref"in request){let found=await resolveSessionRef(client,request.ref,agentDir);if(found.kind==="unknown")return refusal("refuse",void 0,{reason:"unknown_session",ref:request.ref,socket});if(found.kind==="ambiguous"){let detail={reason:"ambiguous_session",ref:request.ref,candidates:found.candidates,socket};return refusal("refuse",void 0,detail)}let reopen=found.kind==="parked"?{sessionPath:found.sessionPath,cwd:found.cwd,retain_on_disconnect:!0,attended:!1}:{sessionPath:found.row.sessionPath,cwd:found.row.cwd};durableSessionId=found.kind==="parked"?found.durableSessionId:found.row.durableSessionId,sessionId=(await client.openSession(reopen)).sessionId}switch(request.action){case"open":return await openHostSession(client,request,socket,ensured);case"prompt":return{exitCode:HOST_EXIT_OK,payload:{action:"prompt",sessionId,disposition:await client.prompt(request.text)}};case"steer":{let streaming=(await client.getState()).isStreaming,disposition=await client.steer(request.text);return{exitCode:HOST_EXIT_OK,payload:{action:"steer",sessionId,disposition,streaming}}}case"abort":{let aborted=(await client.getState()).isStreaming;return await client.abortStrict(),{exitCode:HOST_EXIT_OK,payload:{action:"abort",sessionId,acknowledged:!0,aborted}}}case"model":{await client.setModel(request.model.provider,request.model.id);let state=await client.getState();return{exitCode:HOST_EXIT_OK,payload:{action:"model",sessionId,requested:request.model,model:state.model?{provider:state.model.provider,id:state.model.id}:null,pendingModelSwitch:state.pendingModelSwitch??null}}}case"list":return{exitCode:HOST_EXIT_OK,payload:{action:"list",socket,sessions:await client.listSessions({observe:!0})}};case"state":return{exitCode:HOST_EXIT_OK,payload:{action:"state",sessionId,durableSessionId,state:await client.getState()}};case"read":{if(request.messages){let all=await client.getMessages(),messages=request.tail===void 0?all:all.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,messages,count:messages.length}}}let{entries,leafId}=await client.getEntries(request.since),slice=request.tail===void 0?entries:entries.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,entries:slice,count:slice.length,total:entries.length,leafId,nextSince:slice.at(-1)?.id??request.since??null,...request.since!==void 0&&{since:request.since}}}}case"wait":return await waitForHostSession(client,sessionId,request,handler=>{disconnected=handler});case"unload":{let answer=await client.unloadSession({sessionId,interrupt:request.interrupt,force:request.force,clearQueue:request.clearQueue,children:request.children});return{exitCode:answer.outcome==="unloaded"?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{action:"unload",sessionId,...answer}}}case"close":{let reason,unsubscribe=client.onEvent(record=>{let event=record;event.type==="session_closed"&&(reason=event.reason)});try{await client.closeSession(sessionId);let remaining=(await client.listSessions()).find(row=>row.sessionId===sessionId);return{exitCode:HOST_EXIT_OK,payload:remaining?{action:"close",sessionId,closed:!1,attachments:remaining.attachments}:{action:"close",sessionId,closed:!0,reason:reason??"client_close"}}}finally{unsubscribe()}}default:return assertNever(request)}}catch(error){if((error instanceof RpcRequestTimeoutError||isTransportGoneError(error))&&(connectionUnusable=!0),request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping")throw error;return error instanceof HostEnsureRefusedError?refusal("refuse",void 0,{reason:error.reason,socket,detail:error.detail}):mapError(error,socket)}finally{ensured?.release(),client&&!connectionUnusable&&await detachBeforeClose(client,line=>process.stderr.write(`senpi host session: ${line}
|
|
3
|
-
`)),await client?.stop()}}function assertNever(value){throw new Error(`unreachable host session request: ${JSON.stringify(value)}`)}var USAGE=`usage: ${APP_NAME} host session <command> [--socket <path>] [--json]
|
|
4
|
-
|
|
5
|
-
open --cwd <dir> [--model <provider/id>] [--name <text>] [--prompt <text|@file>] [--launch-spec <file>]
|
|
6
|
-
close <ref>
|
|
7
|
-
model <ref> <provider/id>
|
|
8
|
-
prompt <ref> <text|@file>
|
|
9
|
-
steer <ref> <text|@file>
|
|
10
|
-
abort <ref>
|
|
11
|
-
read <ref> [--tail <N>] [--since <entryId>] [--messages]
|
|
12
|
-
state <ref>
|
|
13
|
-
list
|
|
14
|
-
wait <ref> [--until idle|done] [--timeout <ms>]
|
|
15
|
-
|
|
16
|
-
Every command prints one JSON line. wait defaults to idle and 600000 ms.
|
|
17
|
-
@file is verbatim UTF-8 prompt text (BOM stripped), not an attachment wrapper.
|
|
18
|
-
References accept a host session id, durable session id, path, or name.`;function parseHostSessionArgs(args){let[action,...rest]=args;if(!["open","close","unload","model","prompt","steer","abort","read","state","list","wait"].includes(action??""))return`Unknown host session command "${action??""}".`;let values={},positional=[],messages=!1,unloadFlags={interrupt:!1,force:!1,clearQueue:!1};for(let index=0;index<rest.length;index++){let flag=rest[index];if(flag==="--json")continue;if(action==="unload"&&(flag==="--interrupt"||flag==="--force"||flag==="--clear-queue")){unloadFlags[flag==="--clear-queue"?"clearQueue":flag.slice(2)]=!0;continue}if(flag==="--messages"&&action==="read"){messages=!0;continue}if(!flag.startsWith("--")){positional.push(flag);continue}let allowed=flag==="--socket"||action==="open"&&["--cwd","--model","--name","--prompt","--launch-spec"].includes(flag)||action==="read"&&["--tail","--since"].includes(flag)||action==="wait"&&["--until","--timeout"].includes(flag)||action==="unload"&&flag==="--children",value=rest[++index];if(!allowed||value===void 0||value.startsWith("--"))return`Invalid option or missing value: ${flag}.`;values[flag]=value}let count=action==="open"||action==="list"?0:["model","prompt","steer"].includes(action??"")?2:1;if(positional.length!==count)return`${action} expects ${count} positional argument(s).`;let ref=positional[0]??"",common={socket:values["--socket"],specPath:values["--launch-spec"]};switch(action){case"open":{if(!values["--cwd"])return"open requires --cwd <dir>.";let model=values["--model"]===void 0?void 0:parseModel(values["--model"]);return typeof model=="string"?model:{...common,command:{action,cwd:resolve(values["--cwd"]),model,name:values["--name"],prompt:values["--prompt"]}}}case"model":{let model=parseModel(positional[1]);return typeof model=="string"?model:{...common,command:{action,ref,model}}}case"prompt":case"steer":return{...common,command:{action,ref,text:positional[1]}};case"close":case"abort":case"state":return{...common,command:{action,ref}};case"list":return{...common,command:{action}};case"unload":{let children=values["--children"]??"refuse";return children!=="refuse"&&children!=="detach"?"--children must be refuse or detach.":{...common,command:{action,ref,...unloadFlags,children}}}case"read":{let tail=values["--tail"]===void 0?void 0:integer(values["--tail"],1);return tail===null?"--tail must be a positive integer.":messages&&values["--since"]!==void 0?"--since cannot be combined with --messages.":{...common,command:{action,ref,tail,since:values["--since"],messages}}}case"wait":{let until=values["--until"]??"idle",timeoutMs=integer(values["--timeout"]??"600000",0);return until!=="idle"&&until!=="done"?"--until must be idle or done.":timeoutMs===null?"--timeout must be a non-negative integer.":{...common,command:{action,ref,until,timeoutMs}}}default:return`Unknown host session command "${action}".`}}function parseModel(text){let parts=text.split("/");return parts.length!==2||!parts[0]||!parts[1]?"Model must be provider/id.":{provider:parts[0],id:parts[1]}}function integer(text,minimum){let value=Number(text);return/^\d+$/.test(text)&&Number.isSafeInteger(value)&&value>=minimum?value:null}function usage(reason,detail){return process.stderr.write(`${detail}
|
|
19
|
-
${USAGE}
|
|
20
|
-
`),emit({action:"error",reason,detail}),HOST_EXIT_USAGE}async function runHostSessionCommand(args){let parsed=parseHostSessionArgs(args);if(typeof parsed=="string")return usage("usage",parsed);try{let command=parsed.command;try{"text"in command&&(command.text=promptText(command.text)),command.action==="open"&&command.prompt!==void 0&&(command.prompt=promptText(command.prompt))}catch(error){return usage("prompt_file_unreadable",error instanceof Error?error.message:String(error))}let agentDir=getAgentDir(),target={socket:resolveHostSocket(parsed.socket,agentDir),agentDir},request=command.action==="open"?{...command,target,spec:parsed.specPath===void 0?DEFAULT_HOST_LAUNCH_SPEC:await loadHostLaunchSpec(parsed.specPath)}:{...command,target},outcome=await runHostSessionRequest(request);return emit(outcome.payload),outcome.exitCode}catch(error){return error instanceof HostLaunchSpecError?usage(error.reason,error.detail):(emit({action:"error",reason:"host_error",detail:error instanceof Error?error.message:String(error)}),HOST_EXIT_ERROR)}}function promptText(text){return text.startsWith("@")?readFileSync(text.slice(1),"utf8").replace(/^\uFEFF/,""):text}export{parseHostSessionArgs,runHostSessionCommand};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-OA5INWHI.js";import"./chunk-OJZD7CO7.js";import"./chunk-CZR7C6CY.js";import"./chunk-LR6Z6V54.js";import"./chunk-DXJJP6RP.js";import"./chunk-HCF5M6NA.js";import"./chunk-HHYSXDYP.js";import"./chunk-GY5MR5KR.js";import"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-FIBIVBQK.js";import"./chunk-SGATKHO4.js";import"./chunk-MLVIYDHK.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-VUKNGMDT.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-HZTQHE5O.js";import"./chunk-64CFJHKT.js";import"./chunk-QMRJYMNH.js";import"./chunk-RQHK4QZ5.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-BRXN5R2F.js";import"./chunk-YJA2B7FQ.js";import"./chunk-JAXZOEJE.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-ONLNXGO3.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
|
|
@@ -1,2 +0,0 @@
|
|
|
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-OA5INWHI.js";import"./chunk-OJZD7CO7.js";import"./chunk-CZR7C6CY.js";import"./chunk-LR6Z6V54.js";import"./chunk-DXJJP6RP.js";import"./chunk-HCF5M6NA.js";import"./chunk-HHYSXDYP.js";import"./chunk-GY5MR5KR.js";import"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-FIBIVBQK.js";import"./chunk-SGATKHO4.js";import"./chunk-MLVIYDHK.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-VUKNGMDT.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-HZTQHE5O.js";import"./chunk-64CFJHKT.js";import"./chunk-QMRJYMNH.js";import"./chunk-RQHK4QZ5.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-BRXN5R2F.js";import"./chunk-YJA2B7FQ.js";import"./chunk-JAXZOEJE.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-ONLNXGO3.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
|
|
@@ -1,3 +0,0 @@
|
|
|
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{allocateMonitorId,endpointSockets,matchesTask,subscriptionFor,wantsRecord}from"./chunk-FIBIVBQK.js";import"./chunk-RQHK4QZ5.js";import{socketNeedsHandshake}from"./chunk-3474DPZK.js";import{MAX_RPC_LINE_CHARACTERS,OBSERVE_REQUEST_FIELD,attachJsonlLineReader}from"./chunk-QQSCUEYJ.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-QEQG42HL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";var DELTA_KINDS=new Set(["message_update","tool_execution_update","bash_execution_update"]),SURFACE_KINDS=new Set(["loaded_surfaces_changed","commands_changed"]),LAST_TEXT_LIMIT=60,RpcMonitorCoalescer=class{#windows=new Map;#flush;constructor(flush){this.#flush=flush}accept(sessionKey2,label,record){let type=String(record.type),delta=DELTA_KINDS.has(type);if(!delta&&!SURFACE_KINDS.has(type))return!1;let key=delta?`${sessionKey2}#deltas`:`${sessionKey2}#${type}`,open=this.#windows.get(key),last=delta?lastText(record):"";if(open!==void 0)return open.count+=1,last!==""&&(open.last=last),!0;let window={count:1,last,timer:setTimeout(()=>{this.#windows.delete(key),this.#flush(delta?`rpc ${label()} streaming +${window.count} deltas${window.last===""?"":` (last: "${window.last}")`}`:`rpc ${label()} ${type} x${window.count}`)},delta?2e3:5e3)};return this.#windows.set(key,window),!0}dispose(){for(let window of this.#windows.values())clearTimeout(window.timer);this.#windows.clear()}};function lastText(record){let event=record.assistantMessageEvent,flat=(event?.type==="text_delta"&&typeof event.delta=="string"?event.delta:typeof record.output=="string"?record.output:"").replace(/\s+/g," ").trim();return flat.length>LAST_TEXT_LIMIT?flat.slice(-LAST_TEXT_LIMIT):flat}import{createConnection}from"node:net";var SUBSCRIBE_ID="monitor-subscribe";async function openRpcObserver(socketPath,subscription,handlers){let secret=socketNeedsHandshake(socketPath)?await readSocketSecret(socketSecretPath(socketPath)):void 0,socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),answer=Promise.withResolvers(),ended=!1,end=reason=>{ended||(ended=!0,answer.reject(new Error(`rpc monitor: ${socketPath}: ${reason}`)),handlers.closed(reason))};socket.once("connect",()=>{secret!==void 0&&sendSocketHandshake(socket,secret);let frame={...subscription,[OBSERVE_REQUEST_FIELD]:!0,id:SUBSCRIBE_ID,type:"subscribe_sessions"};socket.write(`${JSON.stringify(frame)}
|
|
3
|
-
`)});let detach=attachJsonlLineReader(socket,line=>{let record;try{record=JSON.parse(line)}catch{return}if(record.type==="response"&&record.id===SUBSCRIBE_ID){record.success===!0?answer.resolve(record):(answer.reject(new Error(`rpc monitor: ${socketPath} refused the subscription: ${String(record.error)}`)),socket.destroy());return}handlers.record(record)},{maxLineLength:MAX_RPC_LINE_CHARACTERS});return socket.on("error",error=>end(error.message)),socket.once("close",()=>{detach(),end("connection closed")}),{subscribed:answer.promise,close:()=>socket.destroy()}}var RpcMonitorRenderer=class{#sessions=new Map;#namedThisBatch=new Set;seed(socket,snapshot){return snapshot.map(row=>{let view=this.#view(socket,row);view.status=String(row.status);let model=modelId(row.model),attachments=typeof row.attachments=="number"?row.attachments:0;return`${view.label} ${view.status} (${attachments} attached${model===void 0?"":`, model ${model}`})`})}forgetSocket(socket){let count2=0;for(let key of[...this.#sessions.keys()])key.startsWith(`${socket}#`)&&(this.#sessions.delete(key),count2++);return count2}statuses(){return new Map([...this.#sessions].map(([key,view])=>[key,view.status]))}label(socket,record){let view=this.#view(socket,record),key=sessionKey(socket,record);return this.#namedThisBatch.has(key)?view.label:(this.#namedThisBatch.size===0&&queueMicrotask(()=>this.#namedThisBatch.clear()),this.#namedThisBatch.add(key),`${view.label} (${String(record.sessionId)})`)}render(socket,record){switch(record.type){case"session_status":return this.#status(socket,record);case"effect_status":{let detail=record.disposition??reasonOf(record.outcome);return`rpc ${this.label(socket,record)} effect ${String(record.kind)} ${tail(String(record.effectId))} ${String(record.state)}${detail===void 0?"":` (${String(detail)})`}`}case"agent_end":return`rpc ${this.label(socket,record)} agent_end${record.aborted===!0?` aborted(${String(record.abortSource??"user")})`:""}`;case"model_changed":return`rpc ${this.label(socket,record)} model_changed -> ${modelId(record.model)??"?"}${record.source===void 0?"":` (${String(record.source)})`}`;case"queue_update":return`rpc ${this.label(socket,record)} queue_update steering=${count(record.steering)} followUp=${count(record.followUp)}`;case"session_replaced":return`rpc ${this.label(socket,record)} session_replaced -> ${String(record.durableSessionId??record.newSessionId??"?")}`;case"session_closed":return`rpc ${this.label(socket,record)} session_closed ${String(record.reason??"")}`.trimEnd();case"extension_event":return`rpc ${this.label(socket,record)} extension_event ${String(record.name??record.event??"")}`.trimEnd();case"entry_appended":return`rpc ${this.label(socket,record)} entry_appended ${entryType(record)}`;case"tool_execution_start":case"tool_execution_end":return`rpc ${this.label(socket,record)} tool ${String(record.toolName??"?")} ${record.type==="tool_execution_start"?"started":"ended"}`;case"turn_end":case"turn_start":case"agent_start":case"agent_idle":case"agent_settled":return`rpc ${this.label(socket,record)} ${record.type}`;default:{let{type:_type,sessionId:_sessionId,...rest}=record,json=JSON.stringify(rest),body=json.length>160?`${json.slice(0,160)}...`:json;return`rpc ${this.label(socket,record)} ${String(record.type)} ${body}`}}}#status(socket,record){let view=this.#view(socket,record),to=String(record.status),from=view.status;if(view.status=to,from===to)return;let change=record.lastChange,why=change===void 0?"":` (${String(change.cause)}, by ${String(change.by)})`;return`rpc ${this.label(socket,record)} status ${from} -> ${to}${why} seq=${String(record.seq)}`}#view(socket,record){let key=sessionKey(socket,record),view=this.#sessions.get(key);return view===void 0?(view={label:labelOf(record),status:"unknown"},this.#sessions.set(key,view)):(typeof record.name=="string"||contextTask(record)!==void 0)&&(view.label=labelOf(record)),view}};function sessionKey(socket,record){return`${socket}#${String(record.sessionId)}`}function labelOf(record){let task=contextTask(record);return task!==void 0?task:typeof record.name=="string"&&record.name!==""?record.name:(typeof record.durableSessionId=="string"?record.durableSessionId:String(record.sessionId)).slice(0,8)}function contextTask(record){let context=record.context;return typeof context?.task_id=="string"?context.task_id:void 0}function modelId(model){return typeof model=="object"&&model!==null&&"id"in model?String(model.id):void 0}function reasonOf(outcome){return typeof outcome=="object"&&outcome!==null&&"reason"in outcome?String(outcome.reason):void 0}function count(value){return Array.isArray(value)?value.length:typeof value=="number"?value:0}function tail(id){return id.length>8?id.slice(-8):id}function entryType(record){let entry=record.entry;return String(entry?.type??record.entryType??"?")}var RPC_RESCAN_MS=3e4,RpcMonitorWatch=class{#options;#observers=new Map;#hosts=new Map;#renderer=new RpcMonitorRenderer;#coalescer;#taskSessions=new Set;#rescan;#stopped=!1;constructor(options){this.#options=options,this.#coalescer=new RpcMonitorCoalescer(options.line)}async start(){let rows=await this.#join();return this.#rescan=setInterval(()=>{this.#join()},RPC_RESCAN_MS),this.#rescan.unref?.(),rows}checkpoint(){return{hosts:Object.fromEntries(this.#hosts),statuses:Object.fromEntries(this.#renderer.statuses())}}diffSince(saved){let lines=[];for(let[socket,host]of this.#hosts){let before=saved.hosts[socket];before!==void 0&&before.generation!==host.generation&&lines.push(`rpc host ${socket} restarted (generation ${before.generation} -> ${host.generation})`)}let now=this.#renderer.statuses();for(let[key,status]of Object.entries(saved.statuses)){let label=key.slice(key.lastIndexOf("#")+1).slice(0,8),current=now.get(key),socket=key.slice(0,key.lastIndexOf("#"));current===void 0?lines.push(this.#hosts.has(socket)&&this.#options.target.kind!=="children"?`rpc ${label} closed (gone while detached)`:this.#hosts.has(socket)?`rpc ${label} no longer listed (closed or no longer a child while detached)`:`rpc ${label} unreachable (its host did not answer)`):current!==status&&lines.push(`rpc ${label} status ${status} -> ${current} (changed while detached)`)}return lines}stop(){this.#stopped=!0,this.#rescan!==void 0&&clearInterval(this.#rescan),this.#coalescer.dispose();for(let observer of this.#observers.values())observer.close();this.#observers.clear()}async#join(){let fresh=(await(this.#options.endpoints??(()=>endpointSockets(this.#options.agentDir)))().catch(()=>[])).filter(socket=>!this.#observers.has(socket));return(await Promise.all(fresh.map(socket=>this.#observe(socket)))).flat()}async#observe(socket){if(this.#stopped)return[];let{target,events}=this.#options,observer;try{observer=await openRpcObserver(socket,subscriptionFor(target,events),{record:record=>{this.#stopped||this.#record(socket,record)},closed:()=>this.#lost(socket,observer)})}catch{return[]}if(this.#stopped)return observer.close(),[];this.#observers.set(socket,observer);let answer=await observer.subscribed.catch(()=>{});if(this.#stopped)return observer.close(),[];let data=answer?.data;if(data===void 0)return[];this.#hosts.set(socket,{instanceId:String(data.hostInstanceId),generation:String(data.hostGeneration)});let matched=(Array.isArray(data.snapshot)?data.snapshot:[]).filter(row=>matchesTask(target,row));for(let row of matched)this.#taskSessions.add(sessionKey(socket,row));if(target.kind!=="all"&&target.kind!=="children"&&matched.length===0)return observer.close(),this.#observers.delete(socket),[];let rows=this.#renderer.seed(socket,matched);return this.#options.checkpoint?.(this.checkpoint()),rows}#lost(socket,observer){if(this.#observers.get(socket)!==observer||(this.#observers.delete(socket),this.#stopped))return;let forgotten=this.#renderer.forgetSocket(socket);for(let key of[...this.#taskSessions])key.startsWith(`${socket}#`)&&this.#taskSessions.delete(key);(this.#hosts.delete(socket)||forgotten>0)&&(this.#options.line(`rpc host ${socket} gone (${forgotten} session${forgotten===1?"":"s"} no longer watched)`),this.#options.checkpoint?.(this.checkpoint()))}#record(socket,record){let{target,events,exclude}=this.#options,type=String(record.type);if(!wantsRecord(events,exclude,type))return;let key=sessionKey(socket,record);if(target.kind==="task"&&(matchesTask(target,record)&&this.#taskSessions.add(key),!this.#taskSessions.has(key))||this.#coalescer.accept(key,()=>this.#renderer.label(socket,record),record))return;let line=this.#renderer.render(socket,record);line!==void 0&&(this.#options.line(line),type==="session_status"&&this.#options.checkpoint?.(this.checkpoint()))}};var RPC_WATCHER_TIMED_OUT_SUMMARY="watcher timed_out",RpcMonitorSource=class{#records=new Map;#host;#nextId=1;constructor(host){this.#host=host}get(id){return this.#records.get(id)}values(){return this.#records.values()}keys(){return this.#records.keys()}async register(options){let id=`rpc_${this.#nextId++}`,monitorId=options.monitorId??allocateMonitorId(),watch=new RpcMonitorWatch({agentDir:options.agentDir,target:options.target,events:options.events,exclude:options.exclude,...options.endpoints===void 0?{}:{endpoints:options.endpoints},line:line=>this.#line(id,line),...options.onCheckpoint===void 0?{}:{checkpoint:checkpoint=>options.onCheckpoint?.(monitorId,checkpoint)}}),record={id,monitorId,description:options.description,startedAtMs:Date.now(),command:null,filter:options.filter,persistent:options.persistent,deadlineMs:options.persistent||options.timeoutMs===void 0?null:Date.now()+options.timeoutMs,fireCount:0,lastFiredAtMs:null,expiresAt:options.expiresAt,paused:!1,settled:!1,rpcWatch:watch,targetText:options.targetText,mutedDropped:0,lastLine:void 0,deadline:options.persistent||options.timeoutMs===void 0?void 0:setTimeout(()=>this.settle(id,RPC_WATCHER_TIMED_OUT_SUMMARY),options.timeoutMs)};this.#records.set(id,record),this.#host.changed();let rows=await watch.start();if(options.restoredFrom!==void 0)for(let line of watch.diffSince(options.restoredFrom))this.#line(id,line);return{id,monitorId,rows}}settle(id,summary){let record=this.#records.get(id);return record===void 0||record.settled?!1:(record.settled=!0,record.rpcWatch.stop(),clearTimeout(record.deadline),this.#records.delete(id),this.#host.changed(),summary!=="watcher disposed"&&this.#host.emit(record,{type:"summary",id,description:record.description,summary}),this.#host.ended(record,summary===RPC_WATCHER_TIMED_OUT_SUMMARY?"timeout":summary==="watcher disposed"?"disposed":"killed",null),!0)}settleAll(summary){let ids=[...this.#records.keys()];for(let id of ids)this.settle(id,summary);return ids.length}#line(id,line){let record=this.#records.get(id);if(!(record===void 0||record.settled)&&!(record.filter instanceof RegExp&&!record.filter.test(line))&&line!==record.lastLine){if(record.lastLine=line,record.paused){record.mutedDropped+=1;return}this.#host.emit(record,{type:"line",id,description:record.description,line})}}};export{RpcMonitorSource};
|
|
@@ -1,3 +0,0 @@
|
|
|
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{SessionEventWriter,answerSubscribeSessions,answerUnsubscribeSessions,refusal,sessionRuntimeView,socketSink}from"./chunk-VZAYN5SB.js";import{WakeScheduler,answeredUiRequestId,availableModelsData,buildRpcSessionState,interruptRunningTurn,onProcessContinue,rpcCommandShapeError,runGetEffectStatus,settledQuestionStatus,subscribeSessionRecords,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-HHYSXDYP.js";import"./chunk-GY5MR5KR.js";import"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import{SESSION_STATUS_CAPABILITY,acquireHostEnsureLock,engineBuildIdentity,gcHostEndpoints}from"./chunk-64CFJHKT.js";import"./chunk-QMRJYMNH.js";import"./chunk-RQHK4QZ5.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import{tuiSocketName}from"./chunk-3474DPZK.js";import{thisProcessStartTime,writeHostRegistration}from"./chunk-OUPD5LWY.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,createDaemonDirectories,createHostDaemonPaths,serializeJsonLine}from"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-HB35RBP4.js";import"./chunk-RUGYFYH7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YJA2B7FQ.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-YU2P3CAR.js";import{MAX_SOCKET_PATH_BYTES}from"./chunk-HRPMLI7O.js";import{authenticateSocket,createSocketSecret,socketSecretPath}from"./chunk-QEQG42HL.js";import{VERSION}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{rm as rm2}from"node:fs/promises";var ControlAttachments=class{constructor(session,pendingQuestions){this.writer=new SessionEventWriter(()=>{}),this.attached=new Set,this.session=session,this.writer.status.setSource({sessionIds:()=>[this.handle],entryView:id=>id===this.handle?this.entryView():void 0,view:id=>id===this.handle?{entry:this.entryView(),runtime:sessionRuntimeView(session,pendingQuestions())}:void 0}),this.writer.registerConnection(NULL_CONNECTION,{writeRaw:()=>{},waitForBackpressure:async()=>{}}),this.stopRecords=subscribeSessionRecords(session,record=>this.writer.enqueue(this.handle,record))}get handle(){return this.session.sessionId}opened(connection){this.writer.registerConnection(keyOf(connection),connection.transport)}closed(connection){let key=keyOf(connection);this.attached.delete(key)&&this.writer.status.publish(this.handle,"detach","client"),this.writer.unregisterConnection(key)}attach(connection){let key=keyOf(connection);return this.attached.has(key)?!1:(this.attached.add(key),this.writer.attachConnectionToSession(key,this.handle),this.writer.status.publish(this.handle,"attach","client"),!0)}isAttached(connection){return this.attached.has(keyOf(connection))}run(connection,task){return this.writer.withConnection(keyOf(connection),task)}respond(connection,answer2){this.writer.enqueueControl(answer2,keyOf(connection)).catch(()=>connection.transport.close?.())}dispose(){this.stopRecords()}entryView(){let manager=this.session.sessionManager,path=this.session.sessionFile,name=manager.getSessionName();return{state:"open",kind:"interactive",cwd:manager.getCwd(),attachments:1+this.attached.size,durableSessionId:this.session.sessionId,...path!==void 0?{sessionPath:path}:{},...name!==void 0?{name}:{},context:{}}}},NULL_CONNECTION="tui-null";function keyOf(connection){return`tui-${connection.id}`}import{randomUUID}from"node:crypto";import{realpathSync}from"node:fs";import{resolve}from"node:path";var TUI_RPC_COMMANDS=["open_session","subscribe_sessions","unsubscribe_sessions","steer","follow_up","prompt","get_effect_status"];async function runTuiRpcCommand(context,connection,command){switch(command.type){case"open_session":return openSession(context,connection,command);case"subscribe_sessions":return subscribe(context,connection,command);case"unsubscribe_sessions":return answerUnsubscribeSessions(command,keyOf(connection),context.attachments.writer.status);case"steer":case"follow_up":return admitInput(context,command,command.type==="steer"?"steer":"followUp",command.whenIdle);case"prompt":return admitPrompt(context,command);case"get_effect_status":return runGetEffectStatus({session:context.session,by:{connectionId:keyOf(connection)},sessionId:context.attachments.handle},command);default:return}}function idOf(command){return typeof command.id=="string"?command.id:void 0}function openSession(context,connection,command){let{session,attachments}=context,ownPath=typeof command.sessionPath=="string"&&samePath(command.sessionPath,session.sessionFile),ownId=command.sessionId!==void 0&&command.sessionId===session.sessionId;return!ownPath&&!ownId?refusal(idOf(command),"open_session","terminal_single_session",{reason:"this terminal hosts one session and the request names another",action:"open it by this terminal's sessionPath, or open the other session on a host"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:attachments.handle,state:buildRpcSessionState(session),attached:!0}})}),null)}function subscribe(context,connection,command){let{writer}=context.attachments,key=keyOf(connection),{answer:answer2,activate}=answerSubscribeSessions(command,key,writer.status);return activate===void 0?answer2:(writer.enqueueControl(answer2,key).then(()=>{writer.hasConnection(key)?writer.status.activate(activate):writer.status.unsubscribe(key,activate)}).catch(()=>writer.status.unsubscribe(key,activate)),null)}function admitPrompt(context,command){let behavior=command.streamingBehavior;return behavior===void 0&&context.session.isStreaming?refusal(idOf(command),"prompt","session_busy",{reason:"a turn is running and the prompt names no streamingBehavior",action:'send it with streamingBehavior "steer" or "followUp", or as a steer/follow_up'}):admitInput(context,command,behavior==="followUp"?"followUp":"steer","start")}var UNSERVED_INPUT_FIELDS=["images","thinkingLevel","expandPromptTemplates","unknownCommandAsText","sessionTitlePrompt","enqueueOrder"];function samePath(requested,own){if(own===void 0)return!1;let canonical=path=>{try{return realpathSync(resolve(path))}catch{return resolve(path)}};return canonical(requested)===canonical(own)}function admitInput(context,command,deliverAs,whenIdle){let id=idOf(command),unserved=UNSERVED_INPUT_FIELDS.filter(field=>command[field]!==void 0);if(unserved.length>0)return refusal(id,command.type,"unsupported_field",{reason:`a terminal delivers input through its admission, which carries text only, not ${unserved.join(", ")}`,action:"send the message without those fields, or send it to a host session"});let message=command.message;if(typeof message!="string"||message.trim()==="")return refusal(id,command.type,"invalid_message",{reason:"message is empty",action:"send a non-empty message"});if(whenIdle!==void 0&&whenIdle!=="queue"&&whenIdle!=="start")return refusal(id,command.type,"invalid_when_idle",{reason:`whenIdle must be "queue" or "start", not ${JSON.stringify(whenIdle)}`,action:'send whenIdle: "queue" (the default) or "start"'});let admission=context.session.externalAdmission,clientMessageId=typeof command.clientMessageId=="string"?command.clientMessageId:void 0,expected=typeof command.expected_turn_id=="number"?command.expected_turn_id:admission.turnEpoch,result=admission.admit({delivery_id:clientMessageId??`tui-rpc-${randomUUID()}`,text:message,sender:{kind:"external",platform:"rpc"},deliverAs,expected_turn_id:expected,whenIdle:whenIdle==="start"?"start":"queue"}),identity=clientMessageId===void 0?{}:{clientMessageId};switch(result.kind){case"started":return answered(id,command.type,{disposition:"started",...identity});case"steered":case"queued":return answered(id,command.type,{disposition:"queued",...identity});case"already_admitted":return answered(id,command.type,{disposition:"queued",duplicate:!0,...identity});case"held_draft":return refusal(id,command.type,"held_draft",{reason:"the user is composing in this terminal, so nothing was delivered",action:"retry after the draft is sent or cleared"});case"turn_conflict":return refusal(id,command.type,"turn_conflict",{reason:`the turn moved on (now ${result.turn_epoch}); this steer named an earlier one`,action:"read get_state's turn_epoch and send it again"})}}function answered(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,data}}import{chmod}from"node:fs/promises";import{createServer}from"node:net";async function listenControlSocket(socketPath,secret,handlers){let clients=new Set,nextConnection=0,server=createServer(socket=>{clients.add(socket),socket.once("close",()=>clients.delete(socket)),socket.on("error",()=>socket.destroy()),authenticateSocket(socket,secret,()=>acceptConnection(socket,++nextConnection,handlers))});return await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(socketPath,()=>{server.off("error",reject),resolve2()})}),server.on("error",error=>handlers.listenerError(error)),await chmod(socketPath,384),{close:()=>closeServer(server,clients)}}function acceptConnection(socket,id,handlers){let connection={id,send:record=>{handlers.respond!==void 0?handlers.respond(connection,record):socket.destroyed||socket.write(serializeJsonLine(record))},transport:socketSink(socket)};handlers.opened?.(connection);let detach=attachJsonlLineReader(socket,line=>{answer(connection,line,handlers)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>connection.send(failure(void 0,"parse","RPC line exceeds the size limit."))});socket.once("close",()=>{detach(),handlers.closed(connection)})}async function answer(connection,line,handlers){let parsed;try{parsed=JSON.parse(line)}catch{connection.send(failure(void 0,"parse","Invalid JSON."));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError!==void 0||!isCommand(parsed)){connection.send(failure(void 0,"parse",shapeError??"RPC command needs a string `type`."));return}let answer2=await handlers.command(connection,parsed);answer2!==null&&connection.send(answer2)}function isCommand(value){return typeof value=="object"&&value!==null&&"type"in value&&typeof value.type=="string"}function failure(id,command,error){return{...id===void 0?{}:{id},type:"response",command,success:!1,error}}function success(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,...data===void 0?{}:{data}}}function closeServer(server,clients){for(let client of clients)client.destroy();return new Promise(resolve2=>server.close(()=>resolve2()))}var SESSION_CONTROL_COMMANDS=["get_available_models","get_available_thinking_levels","set_model","set_thinking_level","interrupt"];async function runSessionControlCommand(session,controls,command){let{id,type}=command;switch(type){case"get_available_models":return success(id,type,await availableModelsData(session));case"get_available_thinking_levels":return success(id,type,{levels:session.getAvailableThinkingLevels()});case"set_model":return await setModel(session,controls,command);case"set_thinking_level":{let level=session.getAvailableThinkingLevels().find(candidate=>candidate===command.level);return level===void 0?failure(id,type,unsupportedThinkingLevel(command.level)):(controls.selectThinkingLevel(level,command.scope!=="turn"),success(id,type))}case"interrupt":return success(id,type,await interruptRunningTurn(session,command.turnId,()=>controls.interruptTurn()));default:return}}async function setModel(session,controls,command){let{id,type}=command,model=(await session.modelRegistry.getAvailable()).find(candidate=>candidate.provider===command.provider&&candidate.id===command.modelId);if(model===void 0)return failure(id,type,`Model not found: ${String(command.provider)}/${String(command.modelId)}`);try{let change=await controls.selectModel(model);return success(id,type,{...model,systemPromptName:change?.systemPromptName})}catch(error){return failure(id,type,error instanceof Error?error.message:String(error))}}var TUI_CONTROL_CAPABILITY="tui_control",TUI_CONTROL_COMMANDS=["get_protocol_info","list_sessions","get_state","get_messages","set_session_name","subscribe","wake","extension_ui_response",...SESSION_CONTROL_COMMANDS,...TUI_RPC_COMMANDS];async function runControlCommand(context,connection,command){let{id,type}=command,{session}=context;switch(type){case"get_protocol_info":{let build=engineBuildIdentity();return success(id,type,{protocolVersion:1,serverVersion:VERSION,capabilities:[TUI_CONTROL_CAPABILITY,SESSION_STATUS_CAPABILITY],mode:"tui",endpoint_kind:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS})}case"list_sessions":return success(id,type,{sessions:[sessionRow(session)]});case"get_state":return success(id,type,{...buildRpcSessionState(session),turn_epoch:session.externalAdmission.turnEpoch,blocking_question:context.surface.blockingQuestion(),compacting:session.isCompacting,editor_has_draft:context.surface.draftHold()!==void 0,state_version:context.feed.stateVersion});case"get_messages":return success(id,type,{messages:session.messages});case"set_session_name":{let name=typeof command.name=="string"?command.name.trim():"";return name===""?failure(id,type,"Session name cannot be empty"):(session.setSessionName(name),success(id,type))}case"subscribe":{let cursor=typeof command.cursor=="number"?command.cursor:void 0;return success(id,type,{cursor:context.feed.subscribe(connection.id,cursor,connection.send)})}case"wake":{let ids=Array.isArray(command.delivery_ids)?command.delivery_ids.filter(entry=>typeof entry=="string"):void 0,result=await context.wake(ids);return success(id,type,{admitted:result.admitted??[]})}case"extension_ui_response":return answerQuestion(context.surface,command);default:{let rpc=await runTuiRpcCommand(context,connection,command);return rpc!==void 0?rpc:await runSessionControlCommand(session,context.surface,command)??failure(id,type,"unsupported")}}}function sessionRow(session){let manager=session.sessionManager,created=manager.getHeader()?.timestamp??null,last=manager.getEntries().at(-1);return{sessionId:session.sessionId,sessionPath:session.sessionFile??null,session_file:session.sessionFile??null,kind:"interactive",surface:"tui",cwd:manager.getCwd(),name:session.sessionName??null,created_at:created,updated_at:last?.timestamp??created,attachments:1}}function answerQuestion(surface,command){let frameId=command.id,requestId=answeredUiRequestId(command),request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return failure(frameId,"extension_ui_response","unknown_request");let response=questionResponse(command,request.questions);return response==="question_incomplete"?failure(frameId,"extension_ui_response",response):response===void 0||!surface.answerQuestion(requestId,response)?failure(frameId,"extension_ui_response","invalid_response"):success(frameId,"extension_ui_response")}function questionResponse(command,questions){if(command.cancelled===!0)return{status:"cancelled",cancelOrigin:"user",answers:{},unanswered:[]};let answers=command.answers;if(typeof answers!="object"||answers===null||Array.isArray(answers))return;let parsed={};for(let[question,value]of Object.entries(answers)){if(typeof value!="object"||value===null||!("selected"in value)||!Array.isArray(value.selected))return;let selected=value.selected.filter(entry=>typeof entry=="string"),text="text"in value&&typeof value.text=="string"?value.text:void 0;parsed[question]=text===void 0?{selected}:{selected,text}}let comment=typeof command.comment=="string"?command.comment:void 0,status=settledQuestionStatus(parsed,comment);if(status===void 0)return"question_incomplete";let unanswered=unansweredQuestionIds(questions,parsed);return{status,resolvedBy:"control_endpoint",answers:parsed,unanswered,...comment===void 0?{}:{comment}}}var ControlFeed=class{constructor(){this.seq=0,this.stateVersionValue=0,this.ring=[],this.subscribers=new Map}get stateVersion(){return this.stateVersionValue}publish(kind,data={}){kind==="state"&&(this.stateVersionValue+=1);let event={type:"session_control_event",seq:++this.seq,kind,data:kind==="state"?{...data,state_version:this.stateVersionValue}:data};this.ring.push(event),this.ring.length>256&&this.ring.shift();for(let send of this.subscribers.values())send(event)}subscribe(connection,cursor,send){if(this.subscribers.set(connection,send),cursor!==void 0)for(let event of this.ring)event.seq>cursor&&send(event);return this.seq}unsubscribe(connection){this.subscribers.delete(connection)}clear(){this.subscribers.clear()}};import{createHash}from"node:crypto";import{rmSync}from"node:fs";import{chmod as chmod2,lstat,mkdir,realpath,rm}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname,join}from"node:path";var PRIVATE_DIRECTORY_MODE=448,REGISTRY_LOCK_WAIT_MS=5e3;async function resolveTuiSocket(agentDir,instanceId){let name=tuiSocketName(instanceId),primary=join(agentDir,"rpc","tui",name);if(Buffer.byteLength(primary)<=MAX_SOCKET_PATH_BYTES)return await makePrivateDirectory(dirname(primary)),primary;let fallbackName=`senpi-rpc-${createHash("sha256").update(agentDir).digest("hex").slice(0,8)}`,scopedRoot=join(tmpdir(),fallbackName),root=Buffer.byteLength(join(scopedRoot,"tui",name))<=MAX_SOCKET_PATH_BYTES?scopedRoot:join("/tmp",fallbackName),tuiRoot=join(root,"tui");await makePrivateDirectory(tuiRoot);for(let directory of[root,tuiRoot])await assertPrivateDirectory(directory);let fallback=join(tuiRoot,name);if(Buffer.byteLength(fallback)>MAX_SOCKET_PATH_BYTES)throw new Error(`socket path ${fallback} exceeds ${MAX_SOCKET_PATH_BYTES} bytes`);return fallback}async function makePrivateDirectory(directory){await mkdir(directory,{recursive:!0,mode:PRIVATE_DIRECTORY_MODE}),await chmod2(directory,PRIVATE_DIRECTORY_MODE)}async function assertPrivateDirectory(directory){let stat=await lstat(await realpath(directory)),ownedByUs=process.getuid===void 0||stat.uid===process.getuid();if(!stat.isDirectory()||!ownedByUs||(stat.mode&63)!==0)throw new Error(`alt_root_unsafe: ${directory} is not a private directory of this user`)}async function registerTuiEndpoint(options){let paths=createHostDaemonPaths({socket:options.socket,agentDir:options.agentDir}),release=await acquireHostEnsureLock(options.socket,REGISTRY_LOCK_WAIT_MS);try{await writeHostRegistration(paths,{record:{pid:process.pid,processStartTime:await thisProcessStartTime()},socket:options.socket,instanceId:options.instanceId,generation:0,launchProfileId:"tui",build:engineBuildIdentity()},{fresh:!0}),await createDaemonDirectories(paths,{kind:"tui"})}finally{await release()}return{paths,socket:options.socket}}async function unregisterTuiEndpoint(entry){let release=await acquireHostEnsureLock(entry.socket,REGISTRY_LOCK_WAIT_MS).catch(()=>{});try{await rm(entry.socket,{force:!0}),await rm(socketSecretPath(entry.socket),{force:!0}),await rm(entry.paths.dir,{recursive:!0,force:!0})}finally{await release?.()}}function unregisterTuiEndpointSync(entry){rmSync(entry.socket,{force:!0}),rmSync(socketSecretPath(entry.socket),{force:!0}),rmSync(entry.paths.dir,{recursive:!0,force:!0})}var REPORT_TEXT_LIMIT=4e3;function activateControlEndpoint(parts){let{context,feed,wake}=parts,{session,surface}=context;session.externalAdmission.setEditorSource(()=>editorHold(context));let unsubscribeSession=session.subscribe(event=>{event.type==="agent_start"?feed.publish("state"):event.type==="agent_idle"?(feed.publish("completion",{turn_epoch:session.externalAdmission.turnEpoch}),feed.publish("state"),wake("idle")):event.type==="agent_end"||event.type==="queue_update"||event.type==="compaction_start"||event.type==="compaction_end"?feed.publish("state"):event.type==="message_end"&&event.message.role==="assistant"&&feed.publish("report",{text:assistantText(event.message).slice(0,REPORT_TEXT_LIMIT)})}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>{wake("emitted")}),unsubscribeInputs=session.externalAdmission.onInputsSettled(()=>queueMicrotask(()=>{wake("submission")})),stopContinue=onProcessContinue(()=>{wake("continue")}),exitCleanup=()=>unregisterTuiEndpointSync(parts.entry);process.once("exit",exitCleanup);let disposing,dispose=()=>(disposing??=(async()=>{process.removeListener("exit",exitCleanup),unsubscribeSession(),unsubscribeEmitted(),unsubscribeInputs(),stopContinue(),parts.stopInbox(),parts.scheduler.dispose(),feed.clear(),session.externalAdmission.setEditorSource(void 0),await parts.server.close(),await sessionReferenced(parts.options,surface)||await session.sessionManager.discardHeaderOnlyFile(),await unregisterTuiEndpoint(parts.entry)})(),disposing);return{socket:parts.entry.socket,wake:reason=>{wake(reason)},noteState:()=>feed.publish("state"),noteQuestions:()=>feed.publish("question",{pending:[...surface.pendingQuestionIds()]}),dispose}}function editorHold(context){let hold=context.surface.draftHold(),revision=context.editorRevision();return hold===void 0?{revision}:{hold_reason:hold,revision}}async function sessionReferenced(options,surface){if(options.isSessionReferenced===void 0)return!1;try{return await options.isSessionReferenced()}catch(error){return surface.notice(`control endpoint kept the session file: ${error instanceof Error?error.message:String(error)}`),!0}}function assistantText(message){return message.role!=="assistant"?"":message.content.flatMap(part=>part.type==="text"?[part.text]:[]).join(`
|
|
3
|
-
`)}async function registerSessionControlEndpoint(context,options){let cleanups=[];try{let endpoint=await openEndpoint(context,options,cleanups);return{registration:{status:"registered",socket:endpoint.socket,dispose:endpoint.dispose},endpoint}}catch(error){for(let cleanup of cleanups.reverse())await Promise.resolve(cleanup()).catch(()=>{});let reason=errorText(error);return context.surface.notice(`control endpoint unavailable: ${reason}`),{registration:{status:"failed",reason}}}}async function openEndpoint(context,options,cleanups){let{session,agentDir,surface}=context;thisProcessStartTime();let headerDurable=session.sessionManager.persistHeaderNow();headerDurable.catch(()=>{});let instanceId=randomUUID2(),socket=await resolveTuiSocket(agentDir,instanceId);cleanups.push(()=>rm2(socket,{force:!0}),()=>rm2(socketSecretPath(socket),{force:!0}));let secret=await createSocketSecret(socketSecretPath(socket)),feed=new ControlFeed,failing,scheduler=new WakeScheduler(async event=>{await session.extensionRunner.emit(event);let result=await options.drain(event)??{admitted:[]};return failing=void 0,result},error=>{let reason=errorText(error);reason!==failing&&(failing=reason,surface.notice(`control endpoint drain failed: ${reason}`))});cleanups.push(()=>scheduler.dispose());let wake=(reason,ids)=>scheduler.request(reason,ids),attachments=new ControlAttachments(session,()=>surface.pendingQuestionIds().length);cleanups.push(()=>attachments.dispose());let commandContext={instanceId,session,surface,feed,wake:ids=>wake("command",ids),attachments},server=await listenControlSocket(socket,secret,{command:(connection,command)=>runControlCommand(commandContext,connection,command),opened:connection=>attachments.opened(connection),respond:(connection,answer2)=>attachments.respond(connection,answer2),closed:connection=>{feed.unsubscribe(connection.id),attachments.closed(connection)},listenerError:error=>surface.notice(`control endpoint listener failed: ${error.message}`)});cleanups.push(()=>server.close()),await headerDurable;let entry=await registerTuiEndpoint({agentDir,socket,instanceId});cleanups.push(()=>unregisterTuiEndpoint(entry));let inbox=await watchInbox(options.inboxDir,()=>{wake("inbox")},error=>surface.notice(`control endpoint inbox watch failed: ${errorText(error)}`));cleanups.push(()=>inbox.stop());let endpoint=activateControlEndpoint({context,options,entry,server,scheduler,feed,stopInbox:inbox.stop,wake});return endpoint.wake("inbox"),inbox.armed.then(()=>endpoint.wake("inbox")),setImmediate(()=>{gcHostEndpoints(agentDir,{kinds:["tui"]}).catch(error=>surface.notice(`control endpoint gc of dead terminals failed: ${errorText(error)}`))}),endpoint}function errorText(error){return error instanceof Error?error.message:String(error)}export{registerSessionControlEndpoint};
|