@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
8 lines (7 loc) • 11.4 kB
JavaScript
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 = () => {}; } }
import{MODULE_JOB_KIND,NOTICE_TAIL_MAX_CHARS,TERMINAL_CHILD_JOB_KINDS,TerminalManager,ToolChildJobError,childTerminalIdScope,controlFd,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createModuleJobHandler,createPtyBashTool,goShimScript,runToolChild,sanitizeTerminalOutput,withControlPipe}from"./chunk-V7NFEFOZ.js";import"./chunk-JLK2DPXP.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import"./chunk-YWBNR4MT.js";import{getShellConfig}from"./chunk-T4O3Z7IC.js";import"./chunk-DPNC7S74.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-OBXBNBXE.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-7K42R46I.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-QD45L5SP.js";import"./chunk-WDTJ6JKE.js";import"./chunk-AFDUWYAX.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-REXE2FGU.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-IDTQWHTP.js";import"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import{value_exports}from"./chunk-MIKPY3E7.js";import"./chunk-OXNWERO4.js";import{SecretOutputRedactor}from"./chunk-5GCZFK4X.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";var PTY_GO_SHIM='stty -echo 2>/dev/null; IFS= read -r _go || exit 127; stty echo 2>/dev/null; exec "$0" "$@"';function parseArgs(value){let field=name=>typeof value=="object"&&value!==null?Reflect.get(value,name):void 0,cwd=field("cwd"),toolCallId=field("toolCallId"),env=field("env");if(typeof cwd!="string"||typeof toolCallId!="string"||typeof env!="object"||env===null)throw new ToolChildJobError("terminal_job_bad_args","a terminal job needs cwd, toolCallId and env");let shellPath=field("shellPath"),timeoutAction=field("timeoutAction"),autoReap=field("backgroundAutoReapMinutes");return{params:field("params"),toolCallId,cwd,env:Object.fromEntries(Object.entries(env).filter(entry=>typeof entry[1]=="string")),...typeof shellPath=="string"?{shellPath}:{},defaultCols:Number(field("defaultCols"))||0,defaultRows:Number(field("defaultRows"))||0,redactSecretsInOutput:field("redactSecretsInOutput")===!0,...timeoutAction==="background"||timeoutAction==="kill"?{timeoutAction}:{},...typeof autoReap=="number"&&Number.isFinite(autoReap)?{backgroundAutoReapMinutes:autoReap}:{}}}function barrierFor(job){return{wrap:(command,args)=>({command:"/bin/sh",args:["-c",PTY_GO_SHIM,command,...args]}),async release(session){if(session.pid===void 0)throw new ToolChildJobError("terminal_spawn_failed","the PTY reported no pid");let gated=job.gate.request({jobId:job.jobId,origin:"terminal",api:"pty.spawn",containment:"own-group",lifetime:"owned",pid:session.pid,pgid:session.pid});session.onExit(exitCode=>job.gate.done(gated.launchId,exitCode===null?{}:{exitCode})),job.gate.skipsAckWait||await gated.acked,job.gate.invokeNow(gated.launchId),session.write(`go
`)}}}function exitSummary(id,runtime){let output=sanitizeTerminalOutput(runtime.fullOutput()).trimEnd(),exit=runtime.exitResult;return{event:"background_exit",id,exit:exit===null?null:{exitCode:exit.exitCode,signal:exit.signal,cancelled:exit.cancelled,timedOut:exit.timedOut},output:output.length>NOTICE_TAIL_MAX_CHARS?output.slice(output.length-NOTICE_TAIL_MAX_CHARS-1):output,...runtime.autoReapedAfterMinutes===void 0?{}:{autoReapedAfterMinutes:runtime.autoReapedAfterMinutes}}}function createTerminalJobHandlers(injected){let manager=injected,managerFor=generation=>(manager??=new TerminalManager({idScope:childTerminalIdScope(generation)}),manager),tell=(job,wake)=>{job.wake(TERMINAL_CHILD_JOB_KINDS.bash,wake).catch(error=>{process.stderr.write(`tool-child: terminal ${wake.event} for ${wake.id} not delivered: ${error instanceof Error?error.message:String(error)}
`)})},contextFor=(args,job)=>({manager:managerFor(job.generation),...args.timeoutAction===void 0?{}:{timeoutAction:args.timeoutAction},...args.backgroundAutoReapMinutes===void 0?{}:{backgroundAutoReapMinutes:args.backgroundAutoReapMinutes},onBackgroundStart:(id,description,startedAtMs,command,autoReapMinutes)=>tell(job,{event:"background_start",id,description,startedAtMs,...command===void 0?{}:{command},...autoReapMinutes===void 0?{}:{autoReapMinutes}}),onBackgroundExit:(id,runtime)=>tell(job,exitSummary(id,runtime)),onBackgroundReapFailed:(id,autoReapMinutes,reason)=>tell(job,{event:"background_reap_failed",id,autoReapMinutes,reason}),cwd:args.cwd,...args.shellPath===void 0?{}:{shellPath:args.shellPath},defaultCols:args.defaultCols,defaultRows:args.defaultRows,redactSecretsInOutput:args.redactSecretsInOutput,getEnv:()=>({...args.env}),launchBarrier:barrierFor(job)}),run=create=>async(value,job)=>{let args=parseArgs(value),tool=create(contextFor(args,job));if(!value_exports.Check(tool.parameters,args.params))throw new ToolChildJobError("terminal_job_bad_args","the tool's parameters do not match its schema");let onUpdate=update=>{job.update(update).catch(error=>{process.stderr.write(`tool-child: ${args.toolCallId} update not sent: ${error instanceof Error?error.message:String(error)}
`)})};return tool.execute(args.toolCallId,args.params,job.signal,onUpdate,{cwd:args.cwd})};return{[TERMINAL_CHILD_JOB_KINDS.bash]:run(createPtyBashTool),[TERMINAL_CHILD_JOB_KINDS.output]:run(createBashOutputTool),[TERMINAL_CHILD_JOB_KINDS.input]:run(createBashInputTool),[TERMINAL_CHILD_JOB_KINDS.resize]:run(createBashResizeTool),[TERMINAL_CHILD_JOB_KINDS.kill]:run(createKillBashTool)}}import{access}from"node:fs/promises";import{constants as osConstants}from"node:os";import{spawn}from"node:child_process";import{once}from"node:events";import{Socket}from"node:net";async function launchOwnGroup(launch){if(process.platform==="win32")throw new Error("launchOwnGroup is POSIX-only; Windows launches are contained by the job");let callerStdio=[...launch.options?.stdio??["ignore","pipe","pipe"]],fd=controlFd(callerStdio),shim=spawn("/bin/sh",["-c",goShimScript(fd),launch.program,...launch.args],{...launch.options,detached:!0,stdio:withControlPipe(callerStdio,fd,"ignore","pipe")}),pid=shim.pid,exited=once(shim,"exit").then(([exitCode,signal])=>({exitCode,signal}));if(pid===void 0)throw new Error(`could not start ${launch.program}`);let gated=launch.gate.request({jobId:launch.jobId,origin:launch.origin,api:launch.api,containment:"own-group",lifetime:launch.lifetime??"owned",pid,pgid:pid});if(exited.then(({exitCode,signal})=>launch.gate.done(gated.launchId,{...exitCode===null?{}:{exitCode},...signal===null?{}:{signal}})),launch.gate.skipsAckWait||await Promise.race([gated.acked,exited]),shim.exitCode===null&&shim.signalCode===null){launch.gate.invokeNow(gated.launchId);let control=shim.stdio[fd];control instanceof Socket&&(control.on("error",()=>{}),exited.then(()=>control.destroy()),control.unref(),control.write(`go
`))}return{launchId:gated.launchId,child:shim,exited}}var USER_BASH_JOB_KIND="user.bash";function parseUserBashArgs(value){let field=name=>typeof value=="object"&&value!==null?Reflect.get(value,name):void 0,command=field("command"),cwd=field("cwd"),env=field("env");if(typeof command!="string"||typeof cwd!="string"||typeof env!="object"||env===null)throw new ToolChildJobError("user_bash_bad_args","a user bash job needs command, cwd and env");let shellPath=field("shellPath"),timeoutSeconds=field("timeoutSeconds");return{command,cwd,redactSecretsInOutput:field("redactSecretsInOutput")===!0,env:Object.fromEntries(Object.entries(env).filter(entry=>typeof entry[1]=="string")),...typeof shellPath=="string"?{shellPath}:{},...typeof timeoutSeconds=="number"&&timeoutSeconds>0?{timeoutSeconds}:{}}}function streamClosed(stream){return stream==null?Promise.resolve():new Promise(resolveClosed=>{stream.once("end",()=>resolveClosed()),stream.once("close",()=>resolveClosed()),stream.once("error",()=>resolveClosed())})}function killGroup(pid){try{process.kill(-pid,"SIGKILL")}catch{}}async function runUserBash(args,job){await access(args.cwd).catch(()=>{throw new ToolChildJobError("user_bash_bad_cwd",`Working directory does not exist: ${args.cwd}
Cannot execute bash commands.`)});let shell=getShellConfig(args.shellPath),fromStdin=shell.commandTransport==="stdin",launched=await launchOwnGroup({gate:job.gate,jobId:job.jobId,origin:"user_bash",api:"cp.spawn",program:shell.shell,args:fromStdin?shell.args:[...shell.args,args.command],options:{cwd:args.cwd,env:{...args.env},stdio:[fromStdin?"pipe":"ignore","pipe","pipe"]}}),{child}=launched;fromStdin&&(child.stdin?.on("error",()=>{}),child.stdin?.end(args.command));let sent=Promise.resolve(),updateFailure,redactors=args.redactSecretsInOutput?{stdout:{redactor:new SecretOutputRedactor,decoder:new TextDecoder},stderr:{redactor:new SecretOutputRedactor,decoder:new TextDecoder}}:void 0,send=(chunk,stream)=>{sent=sent.then(()=>job.update({data:chunk.toString("base64"),stream})).catch(error=>{updateFailure??=error})},forward=(chunk,stream)=>{let state=redactors?.[stream];if(!state)return send(chunk,stream);let text=state.redactor.push(state.decoder.decode(chunk,{stream:!0}));text&&send(Buffer.from(text),stream)};child.stdout?.on("data",chunk=>forward(chunk,"stdout")),child.stderr?.on("data",chunk=>forward(chunk,"stderr"));let drained=Promise.all([streamClosed(child.stdout),streamClosed(child.stderr)]),pid=child.pid,stop=()=>{pid!==void 0&&killGroup(pid)};job.signal.addEventListener("abort",stop,{once:!0});let timer=args.timeoutSeconds===void 0?void 0:setTimeout(stop,args.timeoutSeconds*1e3);try{let{exitCode,signal}=await launched.exited;if(await drained,redactors)for(let stream of["stdout","stderr"]){let{redactor,decoder}=redactors[stream],text=redactor.push(decoder.decode())+redactor.finish();text&&send(Buffer.from(text),stream)}if(await sent,job.signal.aborted)throw new ToolChildJobError("user_bash_aborted","aborted");if(updateFailure!==void 0)throw new ToolChildJobError("user_bash_output_lost",`output could not be sent: ${updateFailure instanceof Error?updateFailure.message:String(updateFailure)}`);return exitCode!==null?{exitCode}:{exitCode:signal===null?null:128+(osConstants.signals[signal]??0)}}finally{timer!==void 0&&clearTimeout(timer),job.signal.removeEventListener("abort",stop)}}function createUserBashJobHandler(){return(value,job)=>{if(process.platform==="win32")throw new ToolChildJobError("tool_child_platform_unsupported","user bash on the tool child is POSIX-only");return runUserBash(parseUserBashArgs(value),job)}}var TOOL_CHILD_JOB_HANDLERS={[MODULE_JOB_KIND]:createModuleJobHandler(),...createTerminalJobHandlers(),[USER_BASH_JOB_KIND]:createUserBashJobHandler()};async function runToolChildRole(){await runToolChild({handlers:TOOL_CHILD_JOB_HANDLERS}),process.exit(0)}export{TOOL_CHILD_JOB_HANDLERS,runToolChildRole};