@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
27 lines (24 loc) • 9.81 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{RUNNER_HEARTBEAT_INTERVAL_MS,RUNNER_HEARTBEAT_STALE_MS,cancelScheduledJob,deferWhileSessionOpen,execHookDelivery,listScheduledJobs,liveRunners,ownRunnerIdentity,removeRunnerLease,runDueJobs,scheduleDir,sessionResumeDelivery,writeRunnerLease}from"./chunk-OP3NDEXO.js";import"./chunk-KQYPGYFV.js";import"./chunk-SOMFLLPD.js";import"./chunk-26UBFF6N.js";import{resolveCliMainPath}from"./chunk-RETVFKJZ.js";import"./chunk-Q5HNTEVZ.js";import"./chunk-N6FVJRTO.js";import"./chunk-76ECBOPA.js";import"./chunk-APCZVDHX.js";import"./chunk-SF4MQDKZ.js";import"./chunk-U3VOXCGP.js";import"./chunk-JLK2DPXP.js";import"./chunk-YWBNR4MT.js";import"./chunk-T4O3Z7IC.js";import"./chunk-DPNC7S74.js";import"./chunk-R7J5TEYK.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{runtimeExecArgv}from"./chunk-6S66JQWD.js";import"./chunk-GKBPYB3Q.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-IDTQWHTP.js";import{APP_NAME,getAgentDir,isBunBinary}from"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIKPY3E7.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{mkdirSync,watch}from"node:fs";import{join}from"node:path";function writeLine(value){process.stdout.write(`${JSON.stringify(value)}
`)}function resolveDelivery(options){let timeoutMs=options.timeoutSeconds*1e3;return options.exec!==void 0?{deliver:execHookDelivery(options.exec,timeoutMs),shouldDefer:void 0}:{deliver:sessionResumeDelivery({command:process.execPath,args:isBunBinary?[]:[...runtimeExecArgv(),resolveCliMainPath()]},timeoutMs),shouldDefer:deferWhileSessionOpen}}function reporter(){let deferred=new Map,invalid=new Map;return result=>{let ok=!0,stillInvalid=new Set;for(let event of result.events){if(event.event==="deferred"){if(deferred.get(event.id)===event.reason)continue;deferred.set(event.id,event.reason)}else if(event.event==="invalid"){if(stillInvalid.add(event.file),invalid.get(event.file)===event.error)continue;invalid.set(event.file,event.error)}else event.event==="fired"?(deferred.delete(event.id),event.outcome==="failed"&&(ok=!1)):event.event==="error"&&(ok=!1);writeLine(event)}for(let file of invalid.keys())stillInvalid.has(file)||invalid.delete(file);return ok}}async function guardedPass(pass){try{return await pass()}catch(error){return{events:[{event:"error",error:error instanceof Error?error.message:String(error)}],nextDueAt:void 0}}}async function runPasses(dir,options){let plan=resolveDelivery(options),owner=ownRunnerIdentity(),startedAt=Date.now(),lease=()=>writeRunnerLease(dir,{startedAt,watch:options.watch,exec:options.exec??null},Date.now()),report=reporter(),pass=()=>runDueJobs({dir,now:Date.now,deliver:plan.deliver,owner,concurrency:options.concurrency,deliveryTimeoutMs:options.timeoutSeconds*1e3,shouldDefer:plan.shouldDefer});await lease();let leaseFailing=!1,heartbeat=setInterval(()=>{lease().then(()=>{leaseFailing=!1},error=>{leaseFailing||writeLine({event:"lease_error",error:error instanceof Error?error.message:String(error)}),leaseFailing=!0})},RUNNER_HEARTBEAT_INTERVAL_MS),watcher,stopping=!1,wake,stop=()=>{stopping=!0,wake?.()};try{if(!options.watch)return report(await guardedPass(pass))?0:1;process.on("SIGTERM",stop),process.on("SIGINT",stop);let pendingDir=join(dir,"pending");for(mkdirSync(pendingDir,{recursive:!0,mode:448}),watcher=watch(pendingDir,()=>wake?.()),writeLine({event:"watching",pid:process.pid,dir,pollSeconds:options.pollSeconds});!stopping;){let rescan=!1,woken=new Promise(resolve=>{wake=()=>{rescan=!0,resolve()}}),result=await guardedPass(pass);if(report(result),stopping)break;if(rescan)continue;let untilDue=result.nextDueAt===void 0?Number.POSITIVE_INFINITY:result.nextDueAt-Date.now(),waitMs=Math.max(0,Math.min(options.pollSeconds*1e3,untilDue)),timer;await Promise.race([woken,new Promise(resolve=>timer=setTimeout(resolve,waitMs))]),clearTimeout(timer)}return writeLine({event:"stopped",pid:process.pid}),0}finally{clearInterval(heartbeat),watcher?.close(),process.off("SIGTERM",stop),process.off("SIGINT",stop),await removeRunnerLease(dir)}}var EXIT_OK=0,EXIT_FAILED=1,EXIT_USAGE=2,DEFAULT_POLL_SECONDS=60,DEFAULT_TIMEOUT_SECONDS=900,DEFAULT_CONCURRENCY=4,USAGE=`usage: ${APP_NAME} schedule <list|cancel|run> [options]
list [--json] every scheduled prompt, all sessions
cancel <id> cancel a scheduled prompt for good
run [--watch] [--exec <command>] fire due prompts (once, or keep running with --watch)
[--poll-seconds <n>] --watch rescan interval (default ${DEFAULT_POLL_SECONDS}; new jobs also wake it)
[--timeout-seconds <n>] per-delivery time limit (default ${DEFAULT_TIMEOUT_SECONDS})
[--concurrency <n>] sessions delivered in parallel (default ${DEFAULT_CONCURRENCY})
Scheduled prompts are created by the schedule_prompt tool from any session, including --print runs.
With --exec, the command receives the due prompt as one JSON object on stdin (plus SENPI_SCHEDULE_ID,
SENPI_SCHEDULE_SESSION_ID, SENPI_SCHEDULE_SESSION_FILE, SENPI_SCHEDULE_CWD); exit 0 means delivered.
Without --exec, the scheduling session is resumed headlessly: ${APP_NAME} -p --session <session> <prompt>,
waiting while another process has that session open.`,UsageError=class extends Error{};function positiveInteger(flag,value){let parsed=Number(value);if(value===void 0||!Number.isSafeInteger(parsed)||parsed<1)throw new UsageError(`${flag} needs a positive integer`);return parsed}function parseRunOptions(args){let watch2=!1,exec,pollSeconds=DEFAULT_POLL_SECONDS,timeoutSeconds=DEFAULT_TIMEOUT_SECONDS,concurrency=DEFAULT_CONCURRENCY;for(let index=0;index<args.length;index+=1){let arg=args[index];if(arg==="--watch")watch2=!0;else if(arg==="--exec"){if(exec=args[++index],exec===void 0||exec.trim().length===0)throw new UsageError("--exec needs a command")}else if(arg==="--poll-seconds")pollSeconds=positiveInteger(arg,args[++index]);else if(arg==="--timeout-seconds")timeoutSeconds=positiveInteger(arg,args[++index]);else if(arg==="--concurrency")concurrency=positiveInteger(arg,args[++index]);else throw new UsageError(`unknown option for run: ${arg}`)}return{watch:watch2,exec,pollSeconds,timeoutSeconds,concurrency}}function formatRelative(ms){let minutes=Math.round(Math.abs(ms)/6e4),text=minutes<60?`${minutes}m`:minutes<2880?`${Math.round(minutes/60)}h`:`${Math.round(minutes/1440)}d`;return ms>=0?`in ${text}`:`${text} ago`}async function list(dir,json){let{jobs,invalid}=await listScheduledJobs(dir),now=Date.now(),runners=(await liveRunners(dir)).map(runner=>({...runner,fresh:now-runner.beatAt<=RUNNER_HEARTBEAT_STALE_MS}));if(json)return writeLine({jobs:jobs.map(record=>({state:record.state,file:record.file,...record.occurrence===void 0?{}:{occurrence:record.occurrence},...record.job})),invalid,runners}),EXIT_OK;let lines=jobs.map(({state,job,occurrence})=>{let every=job.everyMs===null?"":` every ${Math.round(job.everyMs/1e3)}s`,which=occurrence===void 0?"":` #${occurrence}`,error=job.lastError===null?"":` (error: ${job.lastError})`;return`${job.id}${which} ${state} ${new Date(job.dueAt).toISOString()} (${formatRelative(job.dueAt-now)})${every} session ${job.sessionId}${error}
${job.prompt.split(`
`)[0]}`});for(let bad of invalid)lines.push(`${bad.file} invalid: ${bad.error}`);lines.length===0&&lines.push("No scheduled prompts.");let watchers=runners.filter(runner=>runner.watch&&runner.fresh);return lines.push(watchers.length>0?`Runner: active (pid ${watchers.map(runner=>runner.pid).join(", ")})`:`Runner: none (start one with \`${APP_NAME} schedule run --watch\`)`),process.stdout.write(`${lines.join(`
`)}
`),EXIT_OK}async function cancel(dir,id){if(id===void 0)throw new UsageError("cancel needs a job id");let removed=await cancelScheduledJob(dir,id);return removed===void 0?(process.stderr.write(`No scheduled prompt ${id}.
`),EXIT_FAILED):(process.stdout.write(removed.inFlight?`Cancelled ${id}. One delivery had already started and may still complete; nothing after it will run.
`:`Cancelled ${id}.
`),EXIT_OK)}async function runScheduleCommand(args){let dir=scheduleDir(getAgentDir()),[subcommand,...rest]=args;try{switch(subcommand){case"list":if(rest.some(arg=>arg!=="--json"))throw new UsageError(`unknown option for list: ${rest.join(" ")}`);return await list(dir,rest.includes("--json"));case"cancel":if(rest.length>1)throw new UsageError("cancel takes exactly one job id");return await cancel(dir,rest[0]);case"run":return await runPasses(dir,parseRunOptions(rest));case"--help":case"-h":case"help":return process.stdout.write(`${USAGE}
`),EXIT_OK;default:throw new UsageError(subcommand===void 0?"missing subcommand":`unknown subcommand: ${subcommand}`)}}catch(error){if(error instanceof UsageError)return process.stderr.write(`${error.message}
${USAGE}
`),EXIT_USAGE;throw error}}export{runScheduleCommand};