@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
8 lines • 69.8 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{PresentationBroker,armedEvalOnlyToolNames,bootstrapRuntime,buildToolRegistry,builtInExtensions,canonicalizeFilesystemPath,childModuleRoots,createAgentSessionServices,createProjectTrustContext,createToolChildRuntime,directActiveToolNames,forwardToolEvents,normalizeToolExposure,presetTrustsProject,projectKernelPrelude,registeredEvalOnlyToolNames,requestedActiveToolNames,resolveEvalOnlyToolNames,resolveProjectTrusted,resolveToolSelection,sessionExtensionFlagValues,toolChildModuleRoots,toolInfosOf,withFileMutationQueue,withFileMutationQueues}from"./chunk-NV2UUR2Z.js";import"./chunk-6OYUHKJ4.js";import"./chunk-Q6ICUFYH.js";import"./chunk-CRDOOAFI.js";import"./chunk-ARIPHUYY.js";import"./chunk-OP3NDEXO.js";import"./chunk-PWGJGKPI.js";import"./chunk-R3F4JKFN.js";import"./chunk-R7SWQZBB.js";import"./chunk-TQHNFP77.js";import{SettingsManager}from"./chunk-WIPTRIAJ.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-WZ4IZIR2.js";import"./chunk-4R7JSL3B.js";import"./chunk-KQYPGYFV.js";import{ProjectTrustStore,getSavedProjectTrust,hasTrustRequiringProjectResources}from"./chunk-7AEFFKBD.js";import"./chunk-KAQBXCAT.js";import"./chunk-5QZIEDOI.js";import"./chunk-CSCNDNNU.js";import"./chunk-B4V35GCK.js";import"./chunk-3MCOVENJ.js";import"./chunk-3VN5RC6W.js";import"./chunk-4B5JSLLR.js";import"./chunk-UWUN3IBB.js";import"./chunk-MOVB6H22.js";import"./chunk-YLXPMNNR.js";import"./chunk-H4ELF6OO.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-FR7YK76O.js";import"./chunk-2JCYUXD3.js";import"./chunk-QMRJYMNH.js";import"./chunk-RVIBYQSJ.js";import"./chunk-2C4UHQNO.js";import"./chunk-26UBFF6N.js";import"./chunk-SCO4TA5Q.js";import"./chunk-INTQIW2O.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import{closeServer,listen,prepareSocketPath}from"./chunk-RETVFKJZ.js";import"./chunk-Q5HNTEVZ.js";import"./chunk-N6FVJRTO.js";import"./chunk-76ECBOPA.js";import"./chunk-APCZVDHX.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-SF4MQDKZ.js";import"./chunk-2JKFVGLS.js";import"./chunk-KMWFC44T.js";import"./chunk-N7EA2JAR.js";import"./chunk-KLAX467B.js";import"./chunk-OPWT74QF.js";import"./chunk-PQGNLQCI.js";import"./chunk-ZZU4J6QP.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-WHTAR5IS.js";import"./chunk-WHQ2QPP5.js";import"./chunk-SY5HNH77.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-6QQL3SKM.js";import"./chunk-WB6WW5V6.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-V7NFEFOZ.js";import"./chunk-JLK2DPXP.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import"./chunk-YWBNR4MT.js";import{localDeviceFiles}from"./chunk-T4O3Z7IC.js";import{DeviceFileError,FILE_CHANNEL_MAX_BYTES,HAND_WAKE_LANE,base64Length,createAdmissionLine,createHandWakeLink,createMemoryStoreMedium,createReliableTransport,createRemoteExecutor,createWakeOutbox,decodeBase64,decodeDeviceFileArgs,encodeBase64,fileRefusal,fileResult,openMemoryStore,serveLoopHooks,toStoreValue}from"./chunk-DPNC7S74.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import{validateToolArguments}from"./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-GM2CSWYR.js";import"./chunk-2ZIKIVBD.js";import"./chunk-ZFIC2DZV.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-6S66JQWD.js";import"./chunk-GKBPYB3Q.js";import"./chunk-42XRJQM6.js";import"./chunk-REXE2FGU.js";import{shieldSocketDuringClose,unlinkOwnedSocket}from"./chunk-5XHOHZIR.js";import{acquireOwnershipSafeLock,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import"./chunk-IDTQWHTP.js";import{isLocalPath,resolvePath}from"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import"./chunk-4EGD7FGJ.js";import"./chunk-MIKPY3E7.js";import"./chunk-OXNWERO4.js";import"./chunk-5GCZFK4X.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{createServer}from"node:net";import{posix as posix2,win32}from"node:path";import{isAbsolute as isAbsolute2}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{basename as basename4,dirname as dirname4,join as join4,resolve as resolve3}from"node:path";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{existsSync}from"node:fs";import{constants as fsConstants}from"node:fs";import{open}from"node:fs/promises";import{constants as osConstants}from"node:os";import{basename,dirname,join,resolve}from"node:path";var GIT_ACTIVITY_LOCK_NAME="git-activity.flock",GIT_ACTIVITY_SHARED_WAIT_MS=1e4,RETRY_MS=5,LOCK_SH=1,LOCK_NB=4;function classifyFlockErrno(errno){let{EAGAIN,EWOULDBLOCK,ENOLCK,EOPNOTSUPP,ENOSYS}=osConstants.errno;return errno===EAGAIN||errno===EWOULDBLOCK?"busy":errno===ENOLCK||errno===EOPNOTSUPP||errno===ENOSYS?"no-lock":"failed"}function identityLocksDir(repoDir){let repo=resolve(repoDir);if(!(basename(repo)!=="repo"||basename(dirname(dirname(repo)))!=="agents"))return join(dirname(repo),"runtime","locks")}var NO_HOLD={fd:void 0,release:async()=>{}},delay=ms=>new Promise(done=>setTimeout(done,ms));async function holdActivityLock(cwd,flock,waitMs=GIT_ACTIVITY_SHARED_WAIT_MS){let locksDir=identityLocksDir(cwd);if(locksDir===void 0||flock===void 0)return NO_HOLD;if(!existsSync(locksDir))throw new DeviceFileError("not_found","the identity's locks directory does not exist");let handle=await open(join(locksDir,GIT_ACTIVITY_LOCK_NAME),fsConstants.O_RDWR|fsConstants.O_CREAT,384),deadline=Date.now()+waitMs;try{for(;;){let{rc,errno}=flock(handle.fd,LOCK_SH|LOCK_NB);if(rc===0)return{fd:handle.fd,release:()=>handle.close()};let kind=classifyFlockErrno(errno);if(kind==="no-lock")return await handle.close(),NO_HOLD;if(kind==="failed")throw new DeviceFileError("io",`flock on the git-activity lock failed (errno ${errno})`);if(Date.now()>=deadline)throw new DeviceFileError("io",`the git-activity lock stayed exclusively held for ${waitMs} ms`);await delay(RETRY_MS)}}catch(error){throw await handle.close(),error}}import{posix}from"node:path";var k=kind=>({kind}),eq=(prefix,kind)=>({prefix,kind}),opt=(...optional)=>({optional}),rep=(min,...repeat)=>({repeat,min}),NUL=/\0/,REV=/^(?![-./~:])[A-Za-z0-9._/@{}^~+-]+$/,REL=/^(?![/-])(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/,rev=value=>REV.test(value)&&!value.includes("..")&&!value.includes("//"),range=value=>{let parts=value.split("..");return parts.length===2&&parts.every(rev)},blobref=value=>{let at=value.indexOf(":");return at>=0&&(at===0||rev(value.slice(0,at)))&&REL.test(value.slice(at+1))},filesystem=value=>value.length>0&&!NUL.test(value)&&!/^[-:]/.test(value);function scheme(value){return/^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(value)?.[1]}function urlIsLocal(value){let colon=value.indexOf(":"),slash=value.indexOf("/");return colon<0||slash>=0&&slash<colon||process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(value)}var unsafeUrl=value=>value.length===0||NUL.test(value)||/\s/.test(value)||value.startsWith("-")||value.includes("::");function remote(value){if(unsafeUrl(value))return!1;let named=scheme(value);return named!==void 0?named==="https"||named==="ssh":!urlIsLocal(value)}function localUrlPath(value){if(unsafeUrl(value)||scheme(value)!=="file")return;let rest=value.slice(7);if(!rest.startsWith("/")||/[?#]/.test(rest))return;let path;try{path=decodeURIComponent(rest)}catch{return}return path.length>1&&!NUL.test(path)&&!path.endsWith("/")&&posix.normalize(path)===path&&path.split("/").slice(1).every(part=>part!==""&&part!=="."&&part!=="..")?path:void 0}var localCandidate=value=>!unsafeUrl(value)&&(scheme(value)==="file"||scheme(value)===void 0&&urlIsLocal(value)),KINDS={rev,range,revish:value=>rev(value)||range(value),object:value=>rev(value)||blobref(value),blobref,ref:value=>value==="HEAD"||/^refs\/[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refpat:value=>/^refs\/[A-Za-z0-9._/-]+\*?$/.test(value)&&!value.includes(".."),branch:value=>/^(?![-./])[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refspec:value=>/^[A-Za-z0-9._/]+(?:-[A-Za-z0-9._/]+)*:[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),msg:value=>!NUL.test(value),count:value=>/^\d{1,9}$/.test(value),mode:value=>/^(?:100644|100755|120000|160000)$/.test(value),oid:value=>/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(value),filter:value=>/^[ACDMRTUXB]+$/i.test(value),fmt:value=>!NUL.test(value),iso:value=>/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value),relpath:value=>REL.test(value),gitpath:value=>value==="index"||value==="MERGE_HEAD",path:filesystem,worktree:filesystem,source:value=>remote(value)||localCandidate(value),target:value=>remote(value)||localCandidate(value)},FORMAT=eq("--format=","fmt"),LOG_RECORD="--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI",SHAPES={add:[["-A","--",rep(1,k("path"))]],branch:[["--show-current"],["-D",k("branch")]],"cat-file":[["blob",k("object")],["--batch"],["-e",k("blobref")]],checkout:[[k("rev"),"--",k("path")]],commit:[["-q","--no-verify","-m",k("msg")]],"commit-tree":[[k("rev"),opt("-p",k("rev")),"-F","-"]],"count-objects":[["-v"]],diff:[["--cached","-M","-C","-z","--raw","--no-abbrev"],["--name-only","-z",eq("--diff-filter=","filter"),k("rev"),k("rev"),"--"],["--name-status","-M","-z",k("range"),"--"],["--cached","--quiet",k("rev"),"--"],["--no-renames","--name-only","-z",k("range"),"--",k("path")],["--name-only","-z",k("range"),"--"],["--name-only",eq("--diff-filter=","filter")]],"diff-files":[["--name-only","-z"]],"diff-tree":[["-r","-m","--no-commit-id","--no-renames",eq("--diff-filter=","filter"),"--raw","-z",k("rev")]],"for-each-ref":[[FORMAT,rep(1,k("refpat"))]],"hash-object":[[opt("-w"),"--no-filters","--stdin"],[opt("-w"),eq("--path=","relpath"),"--stdin"]],init:[["--template="]],log:[["-1",FORMAT,k("rev")],[{prefix:"-",kind:"count"},FORMAT,k("rev")],[FORMAT,"--name-only","-z","--no-renames","--diff-merges=first-parent",eq("--diff-filter=","filter"),rep(0,k("revish")),"--"],[LOG_RECORD,opt("--name-only","-z","--no-renames","--full-diff"),opt("--fixed-strings","--all-match",rep(1,eq("--grep=","msg"))),opt("-n",k("count")),opt(eq("--since=","iso")),opt(k("revish")),opt("--",rep(1,k("path")))]],"ls-files":[["--stage","-z","--",k("path")],["--eol","-z"]],"ls-remote":[[k("source"),k("ref")]],"ls-tree":[["-r","--name-only","-z",k("rev"),opt("--",k("path"))],["-r","-l","-z",k("rev")],["-r","-z",k("rev")],["-z",k("rev"),"--",k("path")]],maintenance:[["run","--task=loose-objects","--quiet"]],merge:[[],["--abort"],[opt("--no-ff"),opt("-m",k("msg")),k("rev")],["--no-ff",k("rev"),rep(1,"-m",k("msg"))]],"merge-base":[["--is-ancestor",k("rev"),k("rev")]],"prune-packed":[["--quiet"]],push:[["--quiet",k("target"),k("refspec")]],"read-tree":[["--empty"],[k("rev")]],remote:[["-v"]],reset:[["--soft",k("rev")]],restore:[["--source=HEAD","--staged",opt("--worktree"),"--",rep(1,k("path"))]],"rev-list":[[opt("--count"),k("range")],["--reverse",k("range")]],"rev-parse":[["--verify",opt("--quiet"),k("rev")],["-q","--verify",k("rev")],["--git-path",k("gitpath")],["--git-common-dir"]],rm:[["-q","--cached",opt("-f"),"--ignore-unmatch","--",rep(1,k("path"))],["-rf","-q","--ignore-unmatch","--",k("path")]],show:[["-s",FORMAT,k("rev")],[k("blobref")]],"show-ref":[["--verify",k("ref")]],status:[["--porcelain",opt("--untracked-files=all",opt("--",rep(1,k("path"))))]],"symbolic-ref":[["HEAD",k("ref")]],"update-index":[["--force-remove","--",k("path")],["--add","--cacheinfo",k("mode"),k("oid"),k("path")],["-q","-z","--stdin"]],"update-ref":[["-m",k("msg"),"HEAD",k("rev"),k("rev")]],worktree:[["add","-b",k("branch"),k("worktree"),k("rev")],["remove",opt("--force"),k("worktree")],["list","--porcelain"],["prune"]],"write-tree":[[]]};function match(items,args,at,paths,then){let[item,...rest]=items;if(item===void 0)return then(at);let next=to=>match(rest,args,to,paths,then);if(typeof item=="string")return args[at]===item&&next(at+1);if("optional"in item)return match(item.optional,args,at,paths,next)||next(at);if("repeat"in item){let again=(count,from)=>count>=item.min&&next(from)||match(item.repeat,args,from,paths,to=>to>from&&again(count+1,to));return again(0,at)}let arg=args[at];if(arg===void 0)return!1;let value="prefix"in item?arg.startsWith(item.prefix)?arg.slice(item.prefix.length):void 0:arg;if(value===void 0||!KINDS[item.kind](value))return!1;let kind=item.kind,typed=kind==="path"||kind==="worktree"||(kind==="source"||kind==="target")&&localCandidate(value);return typed&&paths.push({kind,value}),next(at+1)?!0:(typed&&paths.pop(),!1)}function matchShape(sub,args){for(let shape of SHAPES[sub]??[]){let paths=[];if(match(shape,args,0,paths,at=>at===args.length))return paths}}var HAND_GIT_PREFIX=["-c","core.fsmonitor=false","-c","protocol.file.allow=always"],SUBCOMMANDS=new Set(["add","branch","cat-file","checkout","commit","commit-tree","config","count-objects","diff","diff-files","diff-tree","for-each-ref","hash-object","init","log","ls-files","ls-remote","ls-tree","maintenance","merge","merge-base","prune-packed","push","read-tree","remote","reset","restore","rev-list","rev-parse","rm","show","show-ref","status","symbolic-ref","update-index","update-ref","worktree","write-tree"]);function configKey(key){let parts=key.split(".");if(parts.length<2)return key;let section=parts[0]?.toLowerCase()??"",name=parts[parts.length-1]?.toLowerCase()??"";return[section,...parts.slice(1,-1),name].join(".")}var keySet=keys=>new Set(keys.map(configKey)),CALLER_C_KEYS=keySet(["maintenance.auto","gc.auto","user.name","user.email","core.autocrlf","log.showRoot","core.quotePath","log.showSignature","log.follow"]),CONFIG_KEYS=keySet(["omo.agentId","user.name","user.email","commit.gpgsign","gc.auto","core.autocrlf","omo.memoryRepository.url","omo.sync.binding","omo.sync.space"]);function subcommandArgs(sub,rest){if(sub==="config"){let[scope,first,second,extra]=rest;if(scope!=="--local"||first===void 0||extra!==void 0)return"config shape";let key=first==="--get"||first==="--unset-all"?second:first;return key===void 0||first!=="--get"&&first!=="--unset-all"&&(second??"-").startsWith("-")?"config shape":CONFIG_KEYS.has(configKey(key))?[]:`config key ${key}`}return matchShape(sub,rest)??`${sub} shape`}function planGit(argv){let index=0;for(;argv[index]?.startsWith("-");){let arg=argv[index]??"";if(arg==="--literal-pathspecs"){index++;continue}if(arg!=="-c")return arg;let setting=argv[index+1]??"",separator=setting.indexOf("=");if(separator<=0||!CALLER_C_KEYS.has(configKey(setting.slice(0,separator))))return`-c ${setting}`;index+=2}let sub=argv[index];if(sub===void 0||!SUBCOMMANDS.has(sub))return`subcommand ${sub??"(none)"}`;let paths=subcommandArgs(sub,argv.slice(index+1));return typeof paths=="string"?paths:{argv:[...HAND_GIT_PREFIX,...argv],paths}}var equal=(args,expected)=>args.length===expected.length&&args.every((arg,index)=>arg===expected[index]);function planLsof(argv,uid){let holders=argv.length===3&&argv[0]==="-t"&&argv[1]==="--"&&(argv[2]??"").length>0,inUse=equal(argv,["-w","-a","-d","cwd","-u",String(uid),"-Fpn"]);return holders||inUse?[...argv]:"lsof shape"}var CALLER_ENV={GIT_TERMINAL_PROMPT:value=>value==="0",GIT_INDEX_FILE:value=>value.length>0,GIT_GLOB_PATHSPECS:value=>value==="0"||value==="1",GIT_AUTHOR_NAME:()=>!0,GIT_AUTHOR_EMAIL:()=>!0,GIT_COMMITTER_NAME:()=>!0,GIT_COMMITTER_EMAIL:()=>!0},WIN32_BASELINE=["SYSTEMROOT","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","PATHEXT"];function baseline(context){let env={},keep=key=>{let value=context.ownEnv[key];value!==void 0&&(env[key]=value)};for(let key of["PATH","HOME","SSH_AUTH_SOCK"])keep(key);if(context.platform==="win32")for(let key of WIN32_BASELINE)keep(key);else keep("TMPDIR"),env.LANG="C";return env.GIT_PROTOCOL_FROM_USER="0",env}function planRun(request,context){let env=baseline(context);for(let[key,value]of Object.entries(request.env)){let allowed2=Object.hasOwn(CALLER_ENV,key)?CALLER_ENV[key]:void 0;if(allowed2===void 0||!allowed2(value))return{ok:!1,reason:`not in the run allowlist: env ${key}`};env[key]=value}let planned=request.exe==="git"?planGit(request.argv):request.exe==="lsof"?planLsof(request.argv,context.uid):`executable ${request.exe}`;return typeof planned=="string"?{ok:!1,reason:`not in the run allowlist: ${planned}`}:Array.isArray(planned)?{ok:!0,exe:"lsof",argv:planned,env,paths:[]}:{ok:!0,exe:"git",argv:planned.argv,env,paths:planned.paths}}var SAFE=/^[A-Za-z0-9@%+=:,./_-]+$/;function renderCommand(exe,argv){return[exe,...argv].map(arg=>SAFE.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" ")}import{execFile as execFile2}from"node:child_process";import{lstat as lstat2,stat}from"node:fs/promises";import{basename as basename3,dirname as dirname3,isAbsolute,join as join3,resolve as resolve2,sep}from"node:path";import{execFile}from"node:child_process";import{lstat,readdir,realpath}from"node:fs/promises";import{basename as basename2,dirname as dirname2,join as join2}from"node:path";var SHAPE="local_repo_shape_unsupported",WALK_BOUND=2e4,refuse=detail=>{throw new DeviceFileError("refused_by_policy",`${SHAPE}: ${detail}`)};async function kindOf(path){let entry=await lstat(path).catch(()=>{});if(entry!==void 0)return entry.isSymbolicLink()?"link":entry.isFile()?"file":entry.isDirectory()?"dir":"other"}async function noLinks(path,recursive,budget){let kind=await kindOf(path);if(kind!==void 0&&(kind==="link"&&refuse(`symlink at ${path}`),kind==="dir"))for(let name of await readdir(path)){budget.left-=1,budget.left<0&&refuse(`more than ${WALK_BOUND} entries under the repository`);let child=join2(path,name),childKind=await kindOf(child);childKind==="link"&&refuse(`symlink at ${child}`),recursive&&childKind==="dir"&&await noLinks(child,!0,budget)}}async function plainGitDir(dir){let[head,objects,refs,commondir,alternates]=await Promise.all(["HEAD","objects","refs","commondir","objects/info/alternates"].map(entry=>kindOf(join2(dir,entry))));(head!=="file"||objects!=="dir"||refs!=="dir")&&refuse(`${dir} is not a plain git directory`),(commondir!==void 0||alternates!==void 0)&&refuse(`${dir} redirects through commondir or alternates`);let budget={left:WALK_BOUND};for(let entry of["HEAD","config","packed-refs"])await noLinks(join2(dir,entry),!1,budget);await noLinks(join2(dir,"refs"),!0,budget),await noLinks(join2(dir,"hooks"),!0,budget),await noLinks(join2(dir,"logs"),!0,budget),await noLinks(join2(dir,"worktrees"),!1,budget),await noLinks(join2(dir,"objects"),!1,budget);for(let sub of["info","pack"])await noLinks(join2(dir,"objects",sub),!1,budget)}function gitConfig(file){let env={PATH:process.env.PATH??"/usr/bin:/bin",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",LANG:"C"};return new Promise((done,fail)=>{execFile("git",["config","--file",file,"--no-includes","--list","-z"],{env,timeout:3e4,windowsHide:!0},(error,stdout)=>{if(error)return fail(error);let records=String(stdout).split("\0").filter(Boolean);done(records.map(record=>{let at=record.indexOf(`
`);return at<0?[record,""]:[record.slice(0,at),record.slice(at+1)]}))})})}var INIT_KEYS=new Set(["core.repositoryformatversion","core.filemode","core.bare","core.ignorecase","core.precomposeunicode","core.logallrefupdates"]),CLONE_KEY=/^remote\..+\.(?:url|fetch|mirror|tagopt)$/,WORKING_CLONE_KEY=/^branch\..+\.(?:remote|merge)$|^user\.(?:name|email)$/;async function allowlistedConfig(dir,bare){let config=join2(dir,"config");await kindOf(config)!=="file"&&refuse(`${dir} has no config file`);let entries=await gitConfig(config).catch(()=>refuse("target config is unreadable"));for(let[key,value]of entries){if(key==="core.bare"){value!==String(bare)&&refuse(`core.bare=${value} on a ${bare?"bare":"working-clone"} target`);continue}INIT_KEYS.has(key)||CLONE_KEY.test(key)||!bare&&WORKING_CLONE_KEY.test(key)||refuse(`target config key ${key} is not allowlisted`)}}async function canonicalLocalRepo(path){let parent=await realpath(dirname2(path)).catch(()=>refuse(`no repository at ${path}`)),real=join2(parent,basename2(path)),self=await kindOf(real);self==="link"&&refuse(`${path} is a symlink`),self!=="dir"&&refuse(`no repository at ${path}`),await kindOf(`${real}.git`)!==void 0&&refuse(`${path}.git exists`);let dotGit=await kindOf(join2(real,".git"));dotGit!==void 0&&dotGit!=="dir"&&refuse(`${path}/.git is not a directory`);let gitDir=dotGit==="dir"?join2(real,".git"):real;return await plainGitDir(gitDir),await allowlistedConfig(gitDir,dotGit!=="dir"),gitDir}var MIN_GIT=[2,29];function git(argv,cwd,env){return new Promise((done,fail)=>{execFile2("git",[...argv],{cwd,env,timeout:3e4,windowsHide:!0},(error,stdout)=>error?fail(error):done(String(stdout)))})}var versionChecked;function gitIsSupported(env){return versionChecked??=git(["--version"],process.cwd(),env).then(output=>{let match2=/git version (\d+)\.(\d+)/.exec(output);if(match2===null)return!1;let[major,minor]=[Number(match2[1]),Number(match2[2])];return major>MIN_GIT[0]||major===MIN_GIT[0]&&minor>=MIN_GIT[1]},()=>!1),versionChecked}async function runDirectory(root,cwd){let canonical=await canonicalizeFilesystemPath(resolve2(root,cwd)),entry=await stat(canonical).catch(()=>{});if(entry===void 0)throw new DeviceFileError("not_found",cwd);if(!entry.isDirectory())throw new DeviceFileError("not_a_file",cwd);return canonical}var inside=(path,dir)=>path===dir||path.startsWith(`${dir}${sep}`);async function confinedIndexFile(value,cwd,env){if(!isAbsolute(value))throw new DeviceFileError("refused_by_policy","GIT_INDEX_FILE must be absolute");let dirs=await gitDirs(cwd,env),parent=await canonicalizeFilesystemPath(dirname3(value));if(!dirs.some(dir=>inside(parent,dir)))throw new DeviceFileError("refused_by_policy","GIT_INDEX_FILE is outside the repository's git directory");return join3(parent,basename3(value))}async function hasUrlRewrites(cwd,env){return(await git(["config","--get-regexp","^url\\."],cwd,env).catch(error=>error.code===1?"":Promise.reject(error))).trim().length>0}async function gitDirs(cwd,env){let[gitDir,commonDir]=(await git(["rev-parse","--absolute-git-dir","--git-common-dir"],cwd,env)).trim().split(`
`);if(gitDir===void 0||commonDir===void 0)throw new DeviceFileError("refused_by_policy","no repository at cwd");return Promise.all([gitDir,resolve2(cwd,commonDir)].map(dir=>canonicalizeFilesystemPath(dir)))}async function canonicalTarget(raw,cwd){let target=resolve2(cwd,raw);if((await lstat2(target).catch(()=>{}))?.isSymbolicLink()===!0)throw new DeviceFileError("refused_by_policy",`symlink: ${raw}`);return join3(await canonicalizeFilesystemPath(dirname3(target)),basename3(target))}async function confinePaths(paths,cwd,env){if(paths.length===0)return[];let dirs=await gitDirs(cwd,env),top=await git(["rev-parse","--show-toplevel"],cwd,env).then(output=>canonicalizeFilesystemPath(output.trim()),()=>{}),targets=[];for(let{kind,value}of paths){if(kind==="source"||kind==="target"){let local=localUrlPath(value);if(local===void 0)throw new DeviceFileError("refused_by_policy",`local_repo_shape_unsupported: only an absolute file:// url: ${value}`);let operation=kind==="source"?"read":"write";targets.push({operation,canonicalPath:await canonicalLocalRepo(local)});continue}let canonical=await canonicalTarget(value,cwd),inGitDir=dirs.some(dir=>inside(canonical,dir)||kind==="worktree"&&inside(dir,canonical));if(kind==="worktree"){if(inGitDir)throw new DeviceFileError("refused_by_policy","worktree path is inside the repository's git directory");targets.push({operation:"write",canonicalPath:canonical})}else if(!inGitDir&&(top===void 0||!inside(canonical,top)))throw new DeviceFileError("refused_by_policy",`path outside the repository: ${value}`)}return targets}var HARDENED_RECEIVE_PACK=["git","-c core.hooksPath=/dev/null","-c receive.denyCurrentBranch=refuse","-c core.fsmonitor=false","-c receive.autogc=false","-c gc.auto=0","-c maintenance.auto=false","receive-pack"].join(" "),CLIENT_LOCAL_GUARDS=["-c","core.hooksPath=/dev/null"],REMOTE_GUARDS=["-c","protocol.file.allow=never","-c","protocol.ext.allow=never","-c","protocol.fd.allow=never"];function subcommandAt(argv){let index=0;for(;index<argv.length&&(argv[index]??"").startsWith("-");)index+=argv[index]==="-c"?2:1;return index}function transportFor(argv,env,paths){let at=subcommandAt(argv),sub=argv[at];if(paths.some(path=>path.kind==="source"||path.kind==="target")){let pushed=sub==="push"?[`--receive-pack=${HARDENED_RECEIVE_PACK}`]:[];return{argv:[...argv.slice(0,at),...CLIENT_LOCAL_GUARDS,argv[at]??"",...pushed,...argv.slice(at+1)],env:{...env,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"},local:!0}}return sub==="ls-remote"||sub==="push"?{argv:[...argv.slice(0,at),...REMOTE_GUARDS,...argv.slice(at)],env,local:!1}:{argv:[...argv],env,local:!1}}var RUN_TIMEOUT_CAP_MS=3e5,DEFAULT_TIMEOUT_MS=3e4,KILL_GRACE_MS=1e4;async function judged(guards,command,nested){let input={command},decision;try{decision=await guards.beforeToolCall("bash",`run-${randomUUID()}`,input,nested)}catch(error){throw new DeviceFileError("refused_by_policy",error instanceof Error?error.message:String(error))}if(decision?.block===!0)throw new DeviceFileError("refused_by_policy",decision.reason??"blocked");if(input.command!==command)throw new DeviceFileError("refused_by_policy","a tool_call handler rewrote the command")}async function runOnHand(args,deps,signal){let plan=planRun({exe:args.exe,argv:args.argv,env:args.env},deps.context);if(!plan.ok)throw new DeviceFileError("refused_by_policy",plan.reason);if(args.stdin!==void 0&&base64Length(args.stdin)>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large","stdin");let cwd=await runDirectory(deps.root,args.cwd),verdict=await deps.guards.filesystemPolicy()?.({operation:"write",canonicalPath:cwd,toolName:"bash"});if(verdict!==void 0&&!verdict.allow)throw new DeviceFileError("refused_by_policy",verdict.reason);let transport=plan.exe==="git"?transportFor(plan.argv,plan.env,plan.paths):{argv:plan.argv,env:plan.env,local:!1},env={...transport.env};if(plan.exe==="git"){if(!await gitIsSupported(env))throw new DeviceFileError("unsupported","git 2.29 or newer is required");if(transport.local&&await hasUrlRewrites(cwd,env))throw new DeviceFileError("refused_by_policy","local_url_rewritten: a url.* rewrite is configured")}if(await judged(deps.guards,renderCommand(plan.exe,transport.argv),deps.nested),plan.exe==="git"){env.GIT_INDEX_FILE!==void 0&&(env.GIT_INDEX_FILE=await confinedIndexFile(env.GIT_INDEX_FILE,cwd,env));for(let{operation,canonicalPath}of await confinePaths(plan.paths,cwd,env)){let decision=await deps.guards.filesystemPolicy()?.({operation,canonicalPath,toolName:"bash"});if(decision!==void 0&&!decision.allow)throw new DeviceFileError("refused_by_policy",decision.reason)}}let hold=args.activityLock===!0&&plan.exe==="git"?await holdActivityLock(cwd,deps.flock):void 0;try{return await spawnBounded(plan.exe,transport.argv,cwd,env,args,hold?.fd,signal)}finally{await hold?.release()}}function spawnBounded(exe,argv,cwd,env,args,lockFd,signal){return new Promise((done,fail)=>{let child=spawn(exe,[...argv],{cwd,env,shell:!1,windowsHide:!0,stdio:["pipe","pipe","pipe",lockFd??"ignore"]}),out=[],err=[],size={out:0,err:0},overflow=!1,killTimer,stop=()=>{child.exitCode===null&&child.signalCode===null&&child.kill("SIGTERM"),killTimer??=setTimeout(()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stderr?.destroy()},KILL_GRACE_MS)},timeout=setTimeout(stop,Math.min(args.timeoutMs??DEFAULT_TIMEOUT_MS,RUN_TIMEOUT_CAP_MS)),onAbort=()=>stop();signal.addEventListener("abort",onAbort,{once:!0});let collect=(into,key)=>chunk=>{if(size={...size,[key]:size[key]+chunk.length},size[key]>FILE_CHANNEL_MAX_BYTES){overflow=!0,stop();return}into.push(chunk)};child.stdout?.on("data",collect(out,"out")),child.stderr?.on("data",collect(err,"err")),child.on("error",error=>fail(new DeviceFileError("io",error.message))),child.on("close",(code,exitSignal)=>{if(clearTimeout(timeout),killTimer!==void 0&&clearTimeout(killTimer),signal.removeEventListener("abort",onAbort),signal.aborted)return fail(new DeviceFileError("aborted","the run was aborted"));if(overflow)return fail(new DeviceFileError("too_large","the run's output passed the limit"));done({code,signal:exitSignal,stdout:encodeBase64(new Uint8Array(Buffer.concat(out))),stderr:Buffer.concat(err).toString("utf8")})}),child.stdin?.on("error",()=>{}),child.stdin?.end(args.stdin===void 0?void 0:Buffer.from(decodeBase64(args.stdin)))})}function checksOf(args){switch(args.op){case"read":return[{toolName:"read",operation:"read",path:args.path}];case"list":return[{toolName:"ls",operation:"enumerate",path:args.path}];case"stat":return[{toolName:"ls",operation:"enumerate",path:args.path,entry:!0}];case"write":return[{toolName:"write",operation:"write",path:args.path,content:new TextDecoder().decode(decodeBase64(args.data))}];case"rename":return[{toolName:"write",operation:"write",path:args.path,content:"",entry:!0},{toolName:"write",operation:"write",path:args.to,content:"",entry:!0}];case"remove":return[{toolName:"write",operation:"write",path:args.path,content:"",entry:!0}];case"mkdir":return[{toolName:"write",operation:"write",path:args.path,content:""}]}}async function canonicalOf(path,entry){return entry?join4(await canonicalizeFilesystemPath(dirname4(path)),basename4(path)):canonicalizeFilesystemPath(path)}async function allowed(guards,root,check,nested){let content=check.content??"",input=check.toolName==="write"?{path:check.path,content}:{path:check.path},decision;try{decision=await guards.beforeToolCall(check.toolName,`file-${randomUUID2()}`,input,nested)}catch(error){throw new DeviceFileError("refused_by_policy",error instanceof Error?error.message:String(error))}if(decision?.block===!0)throw new DeviceFileError("refused_by_policy",decision.reason??"blocked");if(input.path!==check.path||check.toolName==="write"&&input.content!==content)throw new DeviceFileError("refused_by_policy","a tool_call handler rewrote the operation");let canonicalPath=await canonicalOf(resolve3(root,check.path),check.entry===!0),verdict=await guards.filesystemPolicy()?.({operation:check.operation,canonicalPath,toolName:check.toolName});if(verdict!==void 0&&!verdict.allow)throw new DeviceFileError("refused_by_policy",verdict.reason);return canonicalPath}function createHandFileOps(root,guards,run){let files=localDeviceFiles();return async(op,rawArgs,signal,nested)=>{let args=decodeDeviceFileArgs(op,rawArgs);if(args===void 0)return fileRefusal("protocol",`malformed ${op} arguments`);if(args.op==="run"){if(run===void 0)return fileRefusal("unsupported","this hand serves no run channel");try{let{exe,argv,env,stdin,timeoutMs,activityLock}=args,request={exe,argv,cwd:args.path,env,activityLock,...stdin===void 0?{}:{stdin},...timeoutMs===void 0?{}:{timeoutMs}},outcome=await runOnHand(request,{root,guards,context:run.context,flock:run.flock,...nested?{nested}:{}},signal);return fileResult({ok:!0,value:{...outcome}})}catch(error){return error instanceof DeviceFileError?fileRefusal(error.code,error.message):fileRefusal("io",error instanceof Error?error.message:String(error))}}if(args.op==="write"&&base64Length(args.data)>FILE_CHANNEL_MAX_BYTES)return fileRefusal("too_large",args.path);try{let[target,destination]=await Promise.all(checksOf(args).map(check=>allowed(guards,root,check,nested)));if(target===void 0)return fileRefusal("protocol","no target");let options={signal};switch(args.op){case"read":return fileResult({ok:!0,value:encodeBase64(await files.read(target,options))});case"list":return fileResult({ok:!0,value:[...await files.list(target,options)]});case"stat":return fileResult({ok:!0,value:{...await files.stat(target,options)}});case"write":{let data=decodeBase64(args.data);await withFileMutationQueue(target,()=>files.write(target,data,{...options,exclusive:args.exclusive}));break}case"rename":await withFileMutationQueues([target,destination??target],()=>files.rename(target,destination??target,options));break;case"remove":await withFileMutationQueue(target,()=>files.remove(target,options));break;case"mkdir":await files.mkdir(target,options);break}return fileResult({ok:!0,value:null})}catch(error){return error instanceof DeviceFileError?fileRefusal(error.code,error.message):fileRefusal("io",error instanceof Error?error.message:String(error))}}}var bound;function loadFlock(){return bound===void 0&&(bound=bindFlock()??null),bound??void 0}function bindFlock(){if(process.platform!=="darwin"&&process.platform!=="linux")return;let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return;let errnoSymbol=process.platform==="darwin"?"__error":"__errno_location";try{let library=ffi.dlopen(process.platform==="darwin"?"libSystem.B.dylib":"libc.so.6",{flock:{args:[ffi.FFIType.i32,ffi.FFIType.i32],returns:ffi.FFIType.i32},[errnoSymbol]:{args:[],returns:ffi.FFIType.ptr}}),errnoPointer=library.symbols[errnoSymbol];return(fd,operation)=>{let rc=Number(library.symbols.flock(fd,operation));if(rc===0||errnoPointer===void 0)return{rc,errno:0};let pointer=errnoPointer();return{rc,errno:typeof pointer=="number"&&pointer!==0?ffi.read.i32(pointer,0):-1}}}catch{return}}var LOOPLESS_EXECUTE_CALLERS=["in-process-test-harness","remote-tool-executor"],issued=new WeakSet,LooplessExecuteRefusedError=class extends Error{constructor(reason){super(`loopless_execute_refused: ${reason}`)}};function grantLooplessExecuteToRemoteExecutor(){let grant=Object.freeze({caller:"remote-tool-executor"});return issued.add(grant),grant}function looplessGrantRunsToolHandlers(grant){return isLooplessExecuteGranted(grant)&&grant?.caller==="remote-tool-executor"}function isLooplessExecuteGranted(grant){return grant!==void 0&&issued.has(grant)&&LOOPLESS_EXECUTE_CALLERS.includes(grant.caller)}import{randomUUID as randomUUID3}from"node:crypto";function loopWakeRoute(offer,sessionId){let wake=(source,fields)=>offer({source,payload:toStoreValue(sessionId===void 0?fields:{...fields,sessionId})});return{sendMessage:(message,options)=>wake("message",{message,options}),sendUserMessage:(content,options)=>wake("user_message",{content,options}),appendEntry:(customType,data)=>wake("entry",{customType,data}),notify:(message,type)=>wake("notice",{message,type})}}function lateLoopRoute(wake,dropped){return wake!==void 0?sessionId=>loopWakeRoute(wake,sessionId):sessionId=>{let drop=what=>dropped(`A ${what} from loop session ${sessionId}'s hook work arrived after its call ended and was dropped: this runtime has no wake route to the loop.`);return{sendMessage:()=>drop("message"),sendUserMessage:()=>drop("user message"),appendEntry:()=>drop("session entry"),notify:()=>drop("notice")}}}async function resolveLooplessSettings(configuration,startupSettingsManager,profile,diagnostics){let{parsed,agentDir,appMode}=configuration,{cwd,launchProfile}=profile,trustStore=new ProjectTrustStore(agentDir),flagValues=sessionExtensionFlagValues(parsed.unknownFlags,launchProfile),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd),savedProjectTrust=await getSavedProjectTrust(trustStore,cwd),globalPreset=startupSettingsManager.getGlobalSettings().permissionPreset,fullAccessTrust=presetTrustsProject(flagValues.get("permission-preset"),globalPreset)&&savedProjectTrust!==!1,shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&!fullAccessTrust&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:parsed.projectTrustOverride??(fullAccessTrust||!hasTrustRequiringResources||savedProjectTrust===!0),trustFromFullAccess=fullAccessTrust&&hasTrustRequiringResources&&parsed.projectTrustOverride===void 0&&savedProjectTrust!==!0;return{settingsManager:SettingsManager.create(cwd,agentDir,{projectTrusted,trustFromFullAccess,projectTrustLocked:parsed.projectTrustOverride!==void 0}),flagValues,reloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:({extensionsResult})=>resolveProjectTrusted({cwd,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:createProjectTrustContext({cwd,mode:appMode,settingsManager:startupSettingsManager,hasUI:!1}),onExtensionError:message=>diagnostics.push({type:"warning",message})})}:void 0}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}function looplessToolSelection(parsed,settingsManager){let noTools=parsed.noTools?"all":parsed.noBuiltinTools?"builtin":void 0,{defaultToolNames,allowedToolNames,excludedToolNames,initialActiveToolNames}=resolveToolSelection({tools:parsed.tools,noTools,excludeTools:parsed.excludeTools},settingsManager.getDefaultTools());return{filters:{...defaultToolNames===void 0?{}:{defaultToolNames:new Set(defaultToolNames)},...allowedToolNames===void 0?{}:{allowedToolNames:new Set(allowedToolNames)},...excludedToolNames===void 0?{}:{excludedToolNames:new Set(excludedToolNames)}},initialActiveToolNames}}function createBrainCalls(){let running=new Map;return{isModelIssuedToolCall:toolCallId=>running.has(toolCallId),promptSurfaceOf:toolCallId=>running.get(toolCallId)?.promptSurface,run(toolCallId,facts,call){return running.set(toolCallId,facts??{}),call().finally(()=>running.delete(toolCallId))}}}var LooplessToolNotFoundError=class extends Error{constructor(toolName){super(`loopless_tool_not_found: ${toolName}`),this.toolName=toolName}};function errorResult(message){return{content:[{type:"text",text:message}],details:void 0,isError:!0}}function withOverride(result,override){let structuredContent=override.structuredContent??(override.content?void 0:result.structuredContent),next={...result,content:override.content??result.content,details:override.details??result.details,usage:override.usage??result.usage,isError:override.isError??result.isError===!0};return structuredContent===void 0?delete next.structuredContent:next.structuredContent=structuredContent,next}async function runLooplessToolCall(tool,call,handlers){let{toolCallId,signal}=call,nested=call.nested===void 0?{}:{nested:call.nested},args;try{let prepared=tool.prepareArguments?tool.prepareArguments(call.params):call.params,toolCall={type:"toolCall",id:toolCallId,name:tool.name,arguments:prepared};args=validateToolArguments(tool,toolCall)}catch(error){return errorResult(error instanceof Error?error.message:String(error))}if(handlers){let before;try{before=await handlers.beforeToolCall({toolName:tool.name,toolCallId,input:args,...nested})}catch(error){return errorResult(error instanceof Error?error.message:`Extension failed, blocking execution: ${String(error)}`)}if(signal?.aborted)return errorResult("Operation aborted");if(before?.block){let blocked=errorResult(before.reason||"Tool execution was blocked");return before.terminate===!0&&(blocked.terminate=!0),blocked}}let result;try{result=await tool.execute(toolCallId,args,signal,void 0)}catch(error){result=errorResult(error instanceof Error?error.message:String(error))}if(!handlers)return result;try{let override=await handlers.afterToolCall({toolName:tool.name,toolCallId,input:args,result,isError:result.isError===!0,...nested});return override?withOverride(result,override):result}catch(error){return errorResult(error instanceof Error?error.message:String(error))}}import{AsyncLocalStorage}from"node:async_hooks";function createLoopHookCall(late){let calls=new AsyncLocalStorage,latest=new Map;return{current:()=>{let call=calls.getStore();return call?.live()===!0?call.facts:void 0},sender:()=>calls.getStore()?.facts.sendMessage,writer:()=>calls.getStore()?.facts,async run(binding,dispatch){let{sessionId,idle}=binding,token={};latest.set(sessionId,token);let live=!0,userMessagesSent=0,controller=new AbortController,effects={sent:[],notices:[],entries:[],userMessages:[]},facts=Object.freeze({sessionManager:readOnlySession(binding,{live:()=>live,ownWork:()=>live||calls.getStore()?.facts===facts}),signal:controller.signal,isIdle:()=>live||binding.endsTurn!==!0?idle:latest.get(sessionId)===token,sendMessage:(message,options)=>{let entry=options===void 0?{message}:{message,options};live?effects.sent.push(entry):late(sessionId).sendMessage(message,options)},notify:(message,type)=>{let entry=type===void 0?{message}:{message,type};live?effects.notices.push(entry):late(sessionId).notify(message,type)},appendEntry:(customType,data)=>{let entry=data===void 0?{customType}:{customType,data};live?effects.entries.push(entry):late(sessionId).appendEntry(customType,data)},sendUserMessage:(content,options)=>{let entry=options===void 0?{content}:{content,options};userMessagesSent++,live?effects.userMessages.push(entry):late(sessionId).sendUserMessage(content,options)},hasPendingMessages:()=>userMessagesSent>0});try{return await calls.run({live:()=>live,facts},()=>dispatch(effects))}finally{live=!1,controller.abort()}}}}var LoopHookCallEndedError=class extends Error{constructor(member){super(`this loop-hook call has ended; ${member} is bound to that call only`),this.name="LoopHookCallEndedError",this.member=member}};function readOnlySession({sessionId,cwd,carried},gates){let gated=open2=>(member,read)=>()=>{if(!open2())throw new LoopHookCallEndedError(`sessionManager.${member}`);return read()},bound2=gated(gates.live),durable=gated(gates.ownWork),unbound=member=>()=>{throw new Error(`sessionManager.${member} is loop-side: a loop-hook call on a hand carries only the session's id`)};return Object.freeze({getSessionId:bound2("getSessionId",()=>sessionId),getSessionFile:bound2("getSessionFile",()=>{}),getCwd:bound2("getCwd",()=>cwd),getSessionDir:unbound("getSessionDir"),getLeafId:carried===void 0?unbound("getLeafId"):durable("getLeafId",()=>carried.leafId),getLeafEntry:unbound("getLeafEntry"),getEntry:unbound("getEntry"),getLabel:unbound("getLabel"),getBranch:unbound("getBranch"),getFullBranch:unbound("getFullBranch"),buildContextEntries:unbound("buildContextEntries"),buildSessionContext:unbound("buildSessionContext"),buildSessionProjection:unbound("buildSessionProjection"),getHeader:unbound("getHeader"),getEntries:unbound("getEntries"),reduceHistory:carried===void 0?unbound("reduceHistory"):reducer=>durable("reduceHistory",()=>carried.handEntries.reduce(reducer.add,reducer.initial()))(),getTree:unbound("getTree"),getSessionName:unbound("getSessionName")})}var REVOCATION_MAX_AGE_MS=360*60*1e3;var REQUIRED_STRINGS=["accountId","sigKeyId","sigPkSha256"],OPTIONAL_STRINGS=["kemKeyId","kemPkSha256","supersedes"],RECORD_KEYS=["kind","generation","kmsKeyArns","templateVersion","verifierKeyId","vouchedAt","checkedAt",...REQUIRED_STRINGS,...OPTIONAL_STRINGS];var HookContractError=class extends Error{constructor(){super(...arguments),this.name="HookContractError"}};var isPlainObject=value=>{if(typeof value!="object"||value===null||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null};function wireJson(value,at){if(value===null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number"){if(Number.isFinite(value))return value;throw new HookContractError(`${at} is not a finite number`)}if(Array.isArray(value))return value.map((item,index)=>wireJson(item,`${at}[${index}]`));if(isPlainObject(value)){let out={};for(let[key,member]of Object.entries(value))member!==void 0&&(out[key]=wireJson(member,`${at}.${key}`));return out}throw new HookContractError(`${at} is not JSON`)}function hookRequestOutputOf(input,payload){let out=wireJson(payload,"payload");return input.model===void 0?{payload:out}:{payload:out,model:input.model}}var MODEL_STRING_FIELDS=["id","name","api","provider","baseUrl"];function parseHookRequestInput(value){if(!isPlainObject(value)||!("payload"in value))throw new HookContractError("hook input is not an object with a payload");let extra=Object.keys(value).filter(key=>key!=="payload"&&key!=="model");if(extra.length>0)throw new HookContractError(`hook input has unknown members: ${extra.join(", ")}`);let payload=wireJson(value.payload,"payload");if(value.model===void 0)return{payload};let model=value.model;if(!isPlainObject(model)||MODEL_STRING_FIELDS.some(field=>typeof model[field]!="string"))throw new HookContractError("hook input model is not a model");if("headers"in model)throw new HookContractError("hook input model carries headers");return{payload,model:wireJson(model,"model")}}function hookModelOf(input){return input.model}var isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function extensionLoopHooks(runner,twoSidedHome,cwd,call){return async(event,payload)=>{if(twoSidedHome!=="hand")throw new Error("this hand is not the home of its extensions' loop hooks");let only=userLoopHooks(runner);if(!isRecord2(payload)||typeof payload.sessionId!="string"||typeof payload.idle!="boolean")throw new Error(`malformed ${event} payload`);let{sessionId,idle}=payload,images=imagesOf(payload.images);if(images===null)throw new Error(`malformed ${event} payload: images`);if(event==="input"){let{inputId,text,source,attribution,streamingBehavior}=payload;if(typeof inputId!="string"||typeof text!="string"||!isOneOf(source,INPUT_SOURCES)||!isOneOf(attribution,INPUT_ATTRIBUTIONS)||!(streamingBehavior===void 0||isOneOf(streamingBehavior,STREAMING_BEHAVIORS)))throw new Error("malformed input payload");return call.run({sessionId,cwd,idle},effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitInput(text,images,source,streamingBehavior,inputId,attribution,only)))}if(event==="before_agent_start"){let{prompt,systemPrompt,trigger,preview,systemPromptOptions}=payload;if(typeof prompt!="string"||typeof systemPrompt!="string"||!isOneOf(trigger,TRIGGERS)||!(preview===void 0||typeof preview=="boolean")||!isRecord2(systemPromptOptions))throw new Error("malformed before_agent_start payload");let options={...systemPromptOptions,cwd};return call.run({sessionId,cwd,idle},effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitBeforeAgentStart(prompt,images,systemPrompt,options,{only,trigger,...preview===void 0?{}:{preview}})))}if(event==="before_provider_request"){let input=parseHookRequestInput(payload.input),model=hookModelOf(input);return call.run({sessionId,cwd,idle},effects=>dispatchLoopHook(runner,call,effects,async()=>({output:hookRequestOutputOf(input,await runner.emitBeforeProviderRequest(structuredClone(input.payload),void 0,void 0,{only,...model===void 0?{}:{model}}))})))}if(event==="session_start"){let{reason,previousSessionFile}=payload;if(!isOneOf(reason,SESSION_START_REASONS)||!(previousSessionFile===void 0||typeof previousSessionFile=="string"))throw new Error("malformed session_start payload");let sessionStart={type:"session_start",reason,...previousSessionFile===void 0?{}:{previousSessionFile}};return call.run({sessionId,cwd,idle},effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitForwardedLoopEvent(sessionStart,only)))}if(event==="agent_end"){let{messages,aborted}=payload,carried=carriedSessionOf(payload);if(!isAgentMessages(messages)||!(aborted===void 0||typeof aborted=="boolean")||carried===null)throw new Error("malformed agent_end payload");let agentEnd={type:"agent_end",messages,...aborted===void 0?{}:{aborted}};return call.run({sessionId,cwd,idle,carried,endsTurn:!0},effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitForwardedLoopEvent(agentEnd,only)))}throw new Error(`no loop hooks run on a hand for ${event}`)}}var HOOKS_BUILTIN_PATH="<builtin:hooks>",isUserLoopHook=extensionPath=>!extensionPath.startsWith("<builtin:")||extensionPath===HOOKS_BUILTIN_PATH;function userLoopHooks(runner){let shipped=runner.getBuiltinProvenancePaths();return path=>isUserLoopHook(path)&&(path===HOOKS_BUILTIN_PATH||!shipped.has(path))}var INPUT_SOURCES=["interactive","rpc","extension"],INPUT_ATTRIBUTIONS=["user","agent"],STREAMING_BEHAVIORS=["steer","followUp"],SESSION_START_REASONS=["startup","reload","new","resume","fork"],TRIGGERS=["prompt","delivery","extension"],isOneOf=(value,allowed2)=>typeof value=="string"&&allowed2.includes(value),imagesOf=value=>value===void 0?void 0:Array.isArray(value)&&value.every(isImage)?value:null,isAgentMessages=value=>Array.isArray(value)&&value.every(message=>isRecord2(message)&&typeof message.role=="string");function carriedSessionOf(payload){let{leafId,handEntries}=payload;return!(leafId===null||typeof leafId=="string")||!Array.isArray(handEntries)||!handEntries.every(isCustomEntry)?null:{leafId,handEntries}}var isCustomEntry=value=>isRecord2(value)&&value.type==="custom"&&typeof value.customType=="string"&&typeof value.id=="string",isImage=value=>isRecord2(value)&&value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string";async function dispatchLoopHook(runner,call,effects,dispatch){let own=call.current(),errors=[],stop=runner.onError(({extensionPath,event,error})=>{own!==void 0&&call.current()===own&&errors.push({extensionPath,event,error})});try{let result=await dispatch(),{sent,notices,entries,userMessages}=effects;return JSON.parse(JSON.stringify({...result,...sent.length>0?{sent}:{},...notices.length>0?{notices}:{},...entries.length>0?{entries}:{},...userMessages.length>0?{userMessages}:{},...errors.length>0?{errors}:{}}))}finally{stop()}}function toolCatalog(tools){return Array.from(tools,tool=>({name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,promptSnippet:tool.promptSnippet,promptGuidelines:tool.promptGuidelines,kernelPrelude:projectKernelPrelude(tool.name,tool.kernelPrelude),namespace:tool.namespace,annotations:tool.annotations,sessionBound:tool.sessionBound===!0,...normalizeToolExposure(tool)}))}var DESCRIBE_TOOLS_EVENT="describe_tools",isRecord3=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function describeHandTools(source){let{registry}=source,requested=requestedActiveToolNames(registry,{requested:source.initialActiveToolNames,explicit:!0,includeAllExtensionTools:!0,previousRegistryNames:new Set,allowedToolNames:source.allowedToolNames}),armed=armedEvalOnlyToolNames(resolveEvalOnlyToolNames(registry.definitions,void 0),registry.toolRegistry),{active}=directActiveToolNames(requested,registry,armed),evalOnly=[...registeredEvalOnlyToolNames(armed,registry.toolRegistry)];return JSON.parse(JSON.stringify({tools:toolCatalog(Array.from(registry.definitions.values(),({definition})=>definition)),active,evalOnly,context:{contextFiles:source.resources.getAgentsFiles().agentsFiles,skills:source.resources.getSkills().skills}}))}function withToolCatalog(hooks,source){return async(event,payload)=>{if(event!==DESCRIBE_TOOLS_EVENT)return hooks(event,payload);if(!isRecord3(payload)||typeof payload.sessionId!="string"||typeof payload.idle!="boolean")throw new Error(`malformed ${DESCRIBE_TOOLS_EVENT} payload`);return describeHandTools(source)}}function extensionToolHandlers(runner,twoSidedHome="loop"){let twoSided=twoSidedHome==="loop"?runner.twoSidedExtensionPaths():new Set,options=nested=>nested===void 0||twoSided.size===0?{}:{forward:forwardToolEvents(twoSided,nested)};return{beforeToolCall:({toolName,toolCallId,input,nested})=>runner.hasHandlers("tool_call")?runner.emitToolCall({type:"tool_call",toolName,toolCallId,input},options(nested)):Promise.resolve(void 0),afterToolCall:({toolName,toolCallId,input,result,isError,nested})=>runner.hasHandlers("tool_result")?runner.emitToolResult({type:"tool_result",toolName,toolCallId,input,content:result.content,details:result.details,...result.structuredContent===void 0?{}:{structuredContent:result.structuredContent},isError,usage:result.usage},options(nested)):Promise.resolve(void 0)}}function createLooplessRuntimeFactory(configuration,local={}){let{parsed,agentDir,toolRuntime}=configuration,extensionFactories=local.extensionFactories??builtInExtensions,startupSettingsManager=local.startupSettingsManager??SettingsManager.create(configuration.cwd,configuration.agentDir);return async profile=>{let{cwd}=profile,diagnostics=[],{settingsManager,flagValues,reloadOptions}=await resolveLooplessSettings(configuration,startupSettingsManager,profile,diagnostics),services=await createAgentSessionServices({cwd,agentDir,settingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:flagValues,...reloadOptions?{resourceLoaderReloadOptions:reloadOptions}:{},resourceLoaderOptions:{sessionKind:profile.launchProfile?.sessionKind,sessionContext:profile.launchProfile?.sessionContext,additionalExtensionPaths:resolveCliPaths(cwd,parsed.extensions),additionalSkillPaths:resolveCliPaths(cwd,parsed.skills),additionalPromptTemplatePaths:resolveCliPaths(cwd,parsed.promptTemplates),additionalThemePaths:resolveCliPaths(cwd,parsed.themes),noExtensions:parsed.noExtensions,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,extensionFactories}}),extensionsResult=services.resourceLoader.getExtensions();diagnostics.push(...services.diagnostics,...extensionsResult.errors.map(({path,error})=>({type:"warning",message:`Failed to load extension "${path}": ${error}`})),...(extensionsResult.warnings??[]).map(({path,warning})=>({type:"warning",message:`Extension package "${path}": ${warning}`})));let execute=()=>Promise.reject(new Error("Loopless runtime is not ready")),toolNames=()=>[],toolChildRuntime=createToolChildRuntime({toolRuntime:toolRuntime??"in-process",agentDir,scopeId:`loopless-${randomUUID3()}`,cwd:services.cwd,moduleRoots:()=>[...toolChildModuleRoots(runtime.extensionRunner.getAllRegisteredTools()),...childModuleRoots(runtime.extensionRunner.getAllChildModules())],hostCallDeps:{cwd:services.cwd,executeNested:async(_parentToolCallId,name,args,signal)=>{let toolCall={type:"toolCall",id:`nested-${randomUUID3()}`,name,arguments:{}},result=await execute(name,toolCall.id,args,signal);return{toolCall,result,isError:result.isError===!0}},callableToolNames:()=>toolNames(),target:()=>{},filesystemPolicy:()=>runtime.filesystemPolicy},onRecord:()=>{}}),{dispatcher,toolChild}=toolChildRuntime,runtime=bootstrapRuntime({cwd:services.cwd,settingsManager:services.settingsManager,extensionsResult,modelRegistry:services.modelRegistry,toolDispatcher:dispatcher}),toolSelection=looplessToolSelection(parsed,services.settingsManager),registry=buildToolRegistry({baseToolDefinitions:runtime.baseToolDefinitions,runner:runtime.extensionRunner,dispatcher,...toolSelection.filters});toolNames=()=>[...registry.toolRegistry.keys()];let getLoadedHookSources=services.resourceLoader.getLoadedHookSources?.bind(services.resourceLoader),{wake}=profile,loopWake=wake===void 0?void 0:loopWakeRoute(wake),loopHookCall=createLoopHookCall(lateLoopRoute(wake,error=>runtime.extensionRunner.emitError({extensionPath:"<loop-hook-call>",event:"late_effect",error}))),brainCalls=createBrainCalls();runtime.extensionRunner.bindSessionlessFacts({isModelIssuedToolCall:brainCalls.isModelIssuedToolCall,promptSurfaceOf:brainCalls.promptSurfaceOf,getAllTools:()=>toolInfosOf(registry.definitions,registeredEvalOnlyToolNames(armedEvalOnlyToolNames(resolveEvalOnlyToolNames(registry.definitions,void 0),registry.toolRegistry),registry.toolRegistry)),loopHookCall:()=>loopHookCall.current(),loopHookSend:()=>loopHookCall.sender(),loopHookWrite:()=>loopHookCall.writer(),...loopWake===void 0?{}:{loopWake},...getLoadedHookSources?{getLoadedHookSources}:{}});let presentation=new PresentationBroker(error=>runtime.extensionRunner.emitError({extensionPath:"<presentation-port>",event:"ui_presentation",error:`A presentation could not reach the attached client: ${error instanceof Error?error.message:String(error)}`}),loopWake?.notify);runtime.extensionRunner.setUiBroker(presentation);let toolHandlers=looplessGrantRunsToolHandlers(local.executeGrant)?extensionToolHandlers(runtime.extensionRunner,local.twoSidedHome):void 0;execute=(name,toolCallId,params,signal,nested,facts)=>{if(!isLooplessExecuteGranted(local.executeGrant))return Promise.reject(new LooplessExecuteRefusedError("no executor runs the tool_call/tool_result handlers for this runtime yet"));let tool=registry.toolRegistry.get(name);return tool===void 0?Promise.reject(new LooplessToolNotFoundError(name)):brainCalls.run(toolCallId,facts,()=>presentation.present(nested,()=>runLooplessToolCall(tool,{toolCallId,params,...signal?{signal}:{},...nested?{nested}:{}},toolHandlers)))};let fileGuards=toolHandlers!==void 0&&isLooplessExecuteGranted(local.executeGrant)?{beforeToolCall:(toolName,toolCallId,input,nested)=>presentation.present(nested,()=>toolHandlers.beforeToolCall({toolName,toolCallId,input,...nested?{nested}:{}})),filesystemPolicy:()=>runtime.filesystemPolicy}:void 0;return{cwd:services.cwd,definitions:registry.definitions,diagnostics,fileGuards,execute:(name,toolCallId,params,signal,nested,facts)=>execute(name,toolCallId,params,signal,nested,facts),runLoopHooks:withToolCatalog(extensionLoopHooks(runtime.extensionRunner,local.twoSidedHome??"loop",services.cwd,loopHookCall),{registry,initialActiveToolNames:toolSelection.initialActiveToolNames,allowedToolNames:toolSelection.filters.allowedToolNames,resources:services.resourceLoader}),dispose:async()=>{runtime.extensionRunner.invalidate("This loopless runtime was disposed.");let failure=(await Promise.allSettled([dispatcher.dispose(),toolChild?.close()])).find(outcome=>outcome.status==="rejected");if(failure!==void 0)throw failure.reason}}}}var handRun={context:{uid:process.getuid?.()??-1,platform:process.platform,ownEnv:process.env},flock:loadFlock()};function callFacts(call){let surface=call.promptSurface;return surface==="terminal"||surface==="app"||surface==="chat"?{promptSurface:surface}:{}}function notFound(name){return{content:[{type:"text",text:`Tool ${name} not found`}],details:{},isError:!0}}var isRecord4=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function scopeOf(payload){let scope=isRecord4(payload)?payload.scope:void 0;if(!isRecord4(scope)||typeof scope.id!="string"||typeof scope.root!="string")throw new Error("a loop-hook call names no scope");return{id:scope.id,root:scope.root}}function createLooplessHand(configuration,local={}){let factory=createLooplessRuntimeFactory(configuration,{...local,executeGrant:grantLooplessExecuteToRemoteExecutor()}),runtimes=new Map,disposed=new Set,closed=!1,disposals=new WeakMap,disposeOnce=runtime=>{let known=disposals.get(runtime);if(known!==void 0)return known;let disposing=runtime.dispose();return disposals.set(runtime,disposing),disposing},runtimeOf=(scope,reopen)=>{if(closed)return Promise.reject(new Error("this hand is closed"));if(!isAbsolute2(scope.root))return Promise.reject(new Error(`scope root must be an absolute path: ${JSON.stringify(scope.root)}`));let known=runtimes.get(scope.id);if(known!==void 0)return known.root===scope.root?known.runtime:Promise.reject(new Error(`scope_binding_mismatch: scope ${JSON.stringify(scope.id)} is bound to another root`));if(!reopen&&disposed.has(scope.id))return Promise.reject(new Error(`scope ${JSON.stringify(scope.id)} was disposed; its extensions' loop-hook state is gone`));disposed.delete(scope.id);let{wakes}=local,opened=factory({cwd:scope.root,...wakes===void 0?{}:{wake:wake=>wakes.offer(scope.id,wake)}});return runtimes.set(scope.id,{root:scope.root,runtime:opened}),opened.catch(()=>runtimes.delete(scope.id)),opened};return{async openScope(scope){let runtime=await runtimeOf(scope,!0);return{run:call=>runtime.definitions.has(call.name)?runtime.execute(call.name,call.toolCallId,call.arguments,call.signal,call.nested,callFacts(call)):Promise.resolve(notFound(call.name)),isSequential:name=>runtime.definitions.get(name)?.definition.executionMode==="sequential",...runtime.fileGuards===void 0?{}:{file:createHandFileOps(scope.root,runtime.fileGuards,handRun)},dispose:()=>(runtimes.delete(scope.id),disposed.add(scope.id),local.wakes?.closeScope(scope.id),disposeOnce(runtime))}},runLoopHooks:async(scope,event,payload)=>(await runtimeOf(scope,!1)).runLoopHooks(event,payload),loopHooks:async(event,payload)=>(await runtimeOf(scopeOf(payload),!1)).runLoopHooks(event,payload),async close(){closed=!0;let open2=[...runtimes.values()];runtimes.clear();let failures=(await Promise.allSettled(open2.map(({runtime})=>runtime.then(opened=>disposeOnce(opened),()=>{})))).flatMap(outcome=>outcome.status==="rejected"?[outcome.reason]:[]);if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,"disposing this hand's runtimes failed")}}}import{randomBytes}from"node:crypto";import{closeSync,fsyncSync,mkdirSync,openSync,readFileSync,renameSync,writeSync}from"node:fs";import{dirname as dirname5}from"node:path";var StateFileCorruptError=class extends Error{constructor(path,what){super(`the state file ${path} is unreadable: ${what}`),this.name="StateFileCorruptError",this.path=path}},isDocument=value=>Array.isArray(value)&&value.length===2&&typeof value[0]=="string";function readState(path){let text;try{text=readFileSync(path,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return createMemoryStoreMedium().current;throw error}let value;try{value=JSON.parse(text)}catch(error){throw new StateFileCorruptError(path,error instanceof Error?error.message:String(error))}let{epoch,documents}=typeof value=="object"&&value!==null?value:{};if(typeof epoch!="number"||!Array.isArray(documents)||!documents.every(isDocument))throw new StateFileCorruptError(path,"missing epoch or documents");return{epoch,records:[],documents:new Map(documents)}}function fsyncPath(path,flags){let fd=openSync(path,flags);try{fsyncSync(fd)}finally{closeSync(fd)}}function writeState(path,state){let temporary=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`,fd=openSync(temporary,"wx",384);try{writeSync(fd,JSON.stringify({epoch:state.epoch,documents:[...state.documents]})),fsyncSync(fd)}finally{closeSync(fd)}renameSync(temporary,path),process.platform!=="win32"&&fsyncPath(dirname5(path),"r")}function openStateFileStore(path){mkdirSync(dirname5(path),{recursive:!0,mode:448});let store=openMemoryStore({get current(){return readState(path)},set current(next){writeState(path,next)}}),locked=async mutate=>{let release=await acquireOwnershipSafeLock(`${path}.lock`);try{return await mutate()}finally{await release()}};return{...store,claim:(expected,next)=>locked(()=>store.claim(expected,next)),commit:(epoch,writes,adopt)=>locked(()=>store.commit(epoch,writes,adopt)),importSnapshot:(epoch,snapshot)=>locked(()=>store.importSnapshot(epoch,snapshot))}}async function claimStateStore(store){for(;;){let epoch=await store.readEpoch()+1;try{return await store.claim(epoch-1,epoch),epoch}catch(error){if(!(error instanceof Error&&"code"in error&&error.code==="stale-epoch"))throw error}}}var HAND_WAKE_LIMITS={perScope:256,total:1024};async function openHandWakeOutbox(path,options={}){let store=openStateFileStore(path),epoch=await claimStateStore(store);return createWakeOutbox({hand:"hand",store,epoch,admission:createAdmissionLine(),clock:options.clock??Date.now,limits:options.limits??HAND_WAKE_LIMITS,...options.onFault===void 0?{}:{onFault:options.onFault}})}function handWakesOver(link){return{offer:(scope,wake)=>{link.offer({scope,...wake})},closeScope:scope=>{link.closeScope(scope)}}}var isRecord5=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function encodeCarrierLine(message){if(!isRecord5(message)||typeof message.lane!="string"||typeof message.seq!="number")return;if(message.kind==="ack")return`${JSON.stringify({kind:"ack",lane:message.lane,seq:message.seq})}
`;if(message.kind!=="data"||!(message.payload instanceof Uint8Array))return;let payload=Buffer.from(message.payload).toString("base64");return`${JSON.stringify({kind:"data",lane:message.lane,seq:message.seq,payload})}
`}function decodeCarrierLine(line){let parsed;try{parsed=JSON.parse(line)}catch{return}if(!(!isRecord5(parsed)||typeof parsed.lane!="string"||typeof parsed.seq!="number")){if(parsed.kind==="ack")return{kind:"ack",lane:parsed.lane,seq:parsed.seq};if(!(parsed.kind!=="data"||typeof parsed.payload!="string"))return{kind:"data",lane:parsed.lane,seq:parsed.seq,payload:new Uint8Array(Buffer.from(parsed.payload,"base64"))}}}function attachSocketCarrier(socket,side,report){let live=!0,reportedError=!1,stopReading=attachJsonlLineReader(socket,line=>{live&&side.message(decodeCarrierLine(line))},{maxLineLength:MAX_RPC_LINE_CHARACTERS}),onDrain=()=>{live&&side.writable()},onError=error=>{if(live&&!reportedError){reportedError=!0;let code=error.code;report(`carrier socket error${code===void 0?"":` ${code}`}: ${error.message}`)}socket.destroy()},detach=()=>{live&&(live=!1,stopReading(),socket.off("drain",onDrain),side.detached())};return socket.on("drain",onDrain),socket.once("close",detach),socket.on("error",onError),side.attached({send:message=>{if(!live||socket.destroyed||socket.writableNeedDrain)return!1;let line=encodeCarrierLine(message);return line!==void 0&&socket.write(line),!0},close:()=>socket.destroy()}),detach}function serveSocketCarrier(server,side,secret,report){let current,take=socket=>{let previous=current;previous?.detach(),previous?.socket.destroy();let detach=attachSocketCarrier(socket,side,report);current={socket,detach},socket.once("close",()=>{current?.socket===socket&&(current=void 0)})};server.on("connection",socket=>{secret===void 0?take(socket):authenticateSocket(socket,secret,()=>take(socket))})}var HAND_LOOP_HOOK_LANE="loop-hooks";function handSocketPath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix2).join(agentDir,"rpc","hand.sock")}function handWakeStorePath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix2).join(agentDir,"rpc","hand-wakes.json")}function handEndpoint(agentDir,platform,secret){return resolveSocketTransportAddress(handSocketPath(agentDir,platform),platform,secret)}function handEndpointSecret(socketPath,platform=process.platform){return platform==="win32"?ensureSocketSecret(socketSecretPath(socketPath)):Promise.resolve(void 0)}function splitLanes(transport,lanes){let handlers=new Map,named=new Set(lanes),REST="";transport.onFrame(frame=>handlers.get(named.has(frame.lane)?frame.lane:REST)?.(frame));let view=key=>({send:(to,payload)=>transport.send(to,payload),onFrame:handler=>{handlers.set(key,handler)},inFlight:to=>transport.inFlight(to),close:()=>transport.close()});return{lane:view,rest:view(REST)}}async function runHand(options){let{agentDir}=options.configuration,report=message=>{process.stderr.write(`senpi hand: ${message}
`)},socketPath=handSocketPath(agentDir);await prepareSocketPath(socketPath);let outbox=await openHandWakeOutbox(handWakeStorePath(agentDir),{onFault:error=>report(`wake fault: ${error.message}`)}),transport=createReliableTransport({clock:{now:()=>Date.now(),setTimer:(callback,ms)=>{let timer=setTimeout(callback,ms);return()=>clearTimeout(timer)}},onHandlerError:error=>report(`frame handler failed: ${String(error)}`)}),lanes=splitLanes(transport,[HAND_LOOP_HOOK_LANE,HAND_WAKE_LANE]),wakeLink=createHandWakeLink({transport:lanes.lane(HAND_WAKE_LANE),outbox,onFault:error=>report(`wake fault: ${String(error)}`)}),hand=createLooplessHand(options.configuration,{twoSidedHome:"hand",...options.extensionFactories===void 0?{}:{extensionFactories:options.extensionFactories},wakes:handWakesOver(wakeLink)}),executor=createRemoteExecutor({authority:{kind:"self"},fileChannel:!0,transport:lanes.rest,openScope:hand.openScope,onFault:error=>report(`call fault: ${String(error)}`)}),loopHooks=serveLoopHooks({transport:lanes.lane(HAND_LOOP_HOOK_LANE),lane:HAND_LOOP_HOOK_LANE,run:hand.loopHooks,onFault:error=>report(`loop hook fault: ${String(error)}`)}),secret=await handEndpointSecret(socketPath),server=createServer();serveSocketCarrier(server,transport,secret,report);let boundIdentity=await listen(server,socketPath,secret);return report(`listening on ${handEndpoint(agentDir,process.platform,secret)}`),new Promise(()=>{let stop=async()=>{let exitCode=0,step=async(name,run)=>{try{await run()}catch(error){exitCode=1,report(`${name} failed during shutdown: ${String(error)}`)}};await step("loop hooks",()=>loopHooks.close()),await step("wake link",()=>wakeLink.close()),await step("transport",()=>transport.close()),await step("listener close",()=>shieldSocketDuringClose(socketPath,()=>closeServer(server))),await step("executor",()=>executor.close()),await step("hand runtimes",()=>hand.close()),await step("socket removal",()=>unlinkOwnedSocket(socketPath,boundIdentity,report)),process.exit(exitCode)};process.once("SIGTERM",()=>{stop()}),process.once("SIGINT",()=>{stop()})})}export{handEndpointSecret,handSocketPath,handWakeStorePath,runHand};