toolroll 0.9.135 → 0.9.137
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 +16 -0
- package/dist/acp-check-repo-schema.js +1 -1
- package/dist/exec.js +4 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,22 @@ Each release opens with one line on its theme, then **New**, **Changed**, **Fixe
|
|
|
4
4
|
the ones it has). Each item is at most two lines and says where to find it. Notes for maintainers (CI, the release
|
|
5
5
|
tooling) go on the GitHub release, not here. Entries before 0.9.104 use the older format.
|
|
6
6
|
|
|
7
|
+
## 0.9.137 — 2026-12-05
|
|
8
|
+
|
|
9
|
+
Gemini (Antigravity) passes its agent check, so it can build.
|
|
10
|
+
|
|
11
|
+
**Fixed**
|
|
12
|
+
- Gemini's check failed "no command the agent started was seen alive": Toolroll looked for a process named `agy`,
|
|
13
|
+
but Homebrew's `agy` wrapper hands off to `antigravity`. Toolroll now follows wrapper scripts like it.
|
|
14
|
+
|
|
15
|
+
## 0.9.136 — 2026-12-04
|
|
16
|
+
|
|
17
|
+
Updating from 0.9.134 works again.
|
|
18
|
+
|
|
19
|
+
**Fixed**
|
|
20
|
+
- 0.9.135 refused to open a database that 0.9.134 had upgraded ("the acp_check_request table has an unknown shape").
|
|
21
|
+
The update stopped before switching and changed nothing; 0.9.136 upgrades it, keeping every row.
|
|
22
|
+
|
|
7
23
|
## 0.9.135 — 2026-12-04
|
|
8
24
|
|
|
9
25
|
Fast mode: on your own Mac, Toolroll never asks for a password or a terminal command. Gemini Neon, Claude and Codex
|
|
@@ -49,4 +49,4 @@ import{catalogOf,rebuildPreserving,tableSql,V195_ACP_PROVIDER_CHECK}from"./acp-p
|
|
|
49
49
|
settle_by TEXT,
|
|
50
50
|
settle_until TEXT,
|
|
51
51
|
repo TEXT
|
|
52
|
-
)`;const canonical=sql=>sql.replace(/\s+/g," ").trim();export function acpCheckRepoShapeProblem(db){const sql=tableSql(db,"acp_check_request");return sql!==null&&canonical(sql)===canonical(V198_ACP_CHECK_REQUEST_DDL)?null:"the acp_check_request table has an unknown shape"}export function adoptAcpCheckRepo(db){if(acpCheckRepoShapeProblem(db)===null)return;const old=tableSql(db,"acp_check_request");if(old===null||canonical(old)!==canonical(V197_ACP_CHECK_REQUEST_DDL))throw Error("the acp_check_request table has an unknown shape");db.exec("ALTER TABLE acp_check_request ADD COLUMN repo TEXT"),rebuildPreserving(db,[{table:"acp_check_request",sql:V198_ACP_CHECK_REQUEST_DDL,before:catalogOf(db,"acp_check_request")}],198)}
|
|
52
|
+
)`;const canonical=sql=>sql.replace(/\s+/g," ").trim().replace(/^CREATE TABLE "acp_check_request" \(/i,"CREATE TABLE acp_check_request (");export function acpCheckRepoShapeProblem(db){const sql=tableSql(db,"acp_check_request");return sql!==null&&canonical(sql)===canonical(V198_ACP_CHECK_REQUEST_DDL)?null:"the acp_check_request table has an unknown shape"}export function adoptAcpCheckRepo(db){if(acpCheckRepoShapeProblem(db)===null)return;const old=tableSql(db,"acp_check_request");if(old===null||canonical(old)!==canonical(V197_ACP_CHECK_REQUEST_DDL))throw Error("the acp_check_request table has an unknown shape");db.exec("ALTER TABLE acp_check_request ADD COLUMN repo TEXT"),rebuildPreserving(db,[{table:"acp_check_request",sql:V198_ACP_CHECK_REQUEST_DDL,before:catalogOf(db,"acp_check_request")}],198)}
|
package/dist/exec.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import{ACP_LINE_CAP,createAcpConversation}from"./acp-client.js";import{linuxFenceAvailable,macosFenceAvailable,sandboxedSpawn}from"./agent-fence.js";import{withoutProtectedEnv}from"./protected-storage.js";import{isLeadTokenEnvName,withoutLeadTokenEnv}from"./names.js";import{execFile,execFileSync,spawn}from"node:child_process";import{readlinkSync,realpathSync}from"node:fs";import{observeProcessTree,stopProcessTree}from"./process-tree.js";import{jsonlDiscriminants}from"./jsonl-discriminants.js";import{createContainer,currentContainment}from"./containment.js";import{claudeLimitsOf,noteLimits}from"./provider-limits.js";import{sleep as defaultSleep}from"./sleep.js";import{primaryResultEvent,topLevelEvent}from"./stream-scope.js";export const CONTAINMENT_REFUSED_CODE=126;const liveProviders=new Set,hardStopped=new WeakSet,ownedChildren=new Map;function registerOwned(owner,child){if(owner===void 0)return;let set=ownedChildren.get(owner);set===void 0&&(set=new Set,ownedChildren.set(owner,set)),set.add(child),child.once("close",()=>{const owned=ownedChildren.get(owner);owned!==void 0&&(owned.delete(child),owned.size===0&&ownedChildren.delete(owner))})}const containers=new WeakMap;export class ContainmentRefusal extends Error{name="ContainmentRefusal"}export function confined(file,args,bag){const fence=bag.fence??[];if(fence.length>0&&bag.confinement!=="required")throw new ContainmentRefusal("This process was given a fence that isn't marked required, so it was not started.");if(fence.length>0&&(macosFenceAvailable()||linuxFenceAvailable()))try{return sandboxedSpawn(file,args,fence,bag.fenceGrants,bag.cwd,bag.temp)}catch(error){throw new ContainmentRefusal(`The sandbox couldn't be made, so nothing was started: ${error instanceof Error?error.message:String(error)}`)}if(bag.confinement==="required")throw new ContainmentRefusal(fence.length===0?"This process must run inside the agent fence, and it was given none.":"This machine can't confine a build (no macOS sandbox, no working bubblewrap), so nothing was started.");return{file,args:[...args],env:{}}}export function withSandboxEnv(env,added,fenced=!1){return fenced?withoutProtectedEnv({...env??process.env,...added}):withoutLeadTokenEnv({...env??process.env,...added})}class SpawnCustodyFailure extends Error{child;reason;name="SpawnCustodyFailure";constructor(child,reason){super(String(reason)),this.child=child,this.reason=reason}}function rejectedChild(error,child){return error instanceof SpawnCustodyFailure?error.child:child}function spawnContained(file,args,spawnOptions,label,bag,contain=!0){const sandboxed=confined(file,args,{...bag,cwd:spawnOptions.cwd,temp:spawnOptions.env?.TMPDIR});({file,args}=sandboxed),spawnOptions={...spawnOptions,env:withSandboxEnv(spawnOptions.env,sandboxed.env,(bag.fence?.length??0)>0)};const effective=contain?currentContainment():null;if(effective!==null&&effective.refusal!==null)throw new ContainmentRefusal(effective.refusal);if(bag.beforeSpawn?.()===!1)throw new Error("the attempt stopped before this process could spawn");const neverStarted=()=>{try{bag.onSpawnFailed?.()}catch{}};let made;try{made=effective===null?{container:null}:createContainer(effective,label)}catch(error){throw neverStarted(),error}if("refused"in made)throw neverStarted(),new ContainmentRefusal(made.refused);const container=made.container;try{container!==null&&bag.onContainer?.({backend:container.backend,id:container.id,...container.identity?{identity:container.identity}:{}})}catch(error){throw container?.release(),neverStarted(),error}let launch;try{launch=container===null?null:container.launch(file,args)}catch(error){throw container?.release(),neverStarted(),error}let child;try{child=spawn(launch===null?file:launch.file,launch===null?[...args]:launch.args,{shell:!1,windowsHide:!0,detached:spawnOptions.detached,stdio:[...spawnOptions.stdio,...launch===null?[]:launch.extraStdio],...spawnOptions.cwd===void 0?{}:{cwd:spawnOptions.cwd},env:spawnOptions.env??withoutLeadTokenEnv(process.env)})}catch(error){try{container!==null&&bag.onContainerEmpty?.()}catch{}throw container?.release(),neverStarted(),error}container!==null&&(containers.set(child,container),child.once("exit",()=>{settleContainer(container,bag).then(empty=>{empty||(child.stdout?.destroy(),child.stderr?.destroy())})}),child.once("error",()=>{settleContainer(container,bag)}));try{child.pid!==void 0?bag.onSpawn?.(child.pid):container===null&&neverStarted()}catch(error){throw new SpawnCustodyFailure(child,error)}const attached=launch===null||child.pid===void 0?Promise.resolve({ok:!0}):launch.attach(child);return{child,container,attached}}const containerSettlements=new WeakMap;function settleContainer(container,bag,timeoutMs=5e3){const existing=containerSettlements.get(container);if(existing!==void 0)return existing;const settling=finishContainer(container,bag,timeoutMs);return containerSettlements.set(container,settling),settling}async function finishContainer(container,bag,timeoutMs){let empty=container.populated()===!1;try{empty||(empty=await container.kill(timeoutMs))}catch{empty=!1}try{empty?bag.onContainerEmpty?.():bag.onUnknown?.()}catch{empty=!1}try{container.release()}catch{}return empty}function containmentOf(container,empty,attachFailure){return attachFailure!==null?{containment:{refused:attachFailure}}:container===null||empty===null?{}:{containment:{backend:container.backend,id:container.id,empty}}}function startStream(file,args,options,stdio,childEnv,resolve){let child,container=null;const attach={failure:null};try{const spawned=spawnStream(file,args,options,stdio,childEnv);child=spawned.child,container=spawned.container,spawned.attached.then(outcome=>{outcome.ok||(attach.failure=outcome.detail)})}catch(error){return reapRejectedSpawn(rejectedChild(error,child),options.processGroup===!0).then(()=>resolve(refusedResult(error))),null}return options.processGroup===!0&&liveProviders.add(child),registerOwned(options.owner,child),options.processGroup===!0&&container===null&&observeProcessTree(child,options),{child,container,attach}}function spawnStream(file,args,options,stdio,childEnv){return spawnContained(file,args,{cwd:options.cwd,env:childEnv,stdio,detached:options.processGroup===!0&&process.platform!=="win32"},options.owner??"stream",{beforeSpawn:options.beforeSpawn,onSpawn:options.onSpawn,onSpawnFailed:options.onSpawnFailed,onContainer:options.onContainer,onContainerEmpty:options.onContainerEmpty,onUnknown:options.onUnknown,fence:options.fence,fenceGrants:options.fenceGrants,confinement:options.confinement},options.processGroup===!0)}function refusedResult(error){return error instanceof ContainmentRefusal?{code:CONTAINMENT_REFUSED_CODE,stdout:"",stderr:error.message,timedOut:!1,notFound:!1,containment:{refused:error.message}}:{code:1,stdout:"",stderr:String(error instanceof SpawnCustodyFailure?error.reason:error),timedOut:!1,notFound:!1}}const databaseOwners=new WeakMap;let memoryDatabaseOwner=0;export function runOwnerTag(store,runId){let owner=databaseOwners.get(store.handle);if(owner===void 0){const file=store.handle.prepare("PRAGMA database_list").all().find(row=>row.name==="main")?.file;owner=typeof file=="string"&&file!==""?`file:${realpathSync(file)}`:`memory:${++memoryDatabaseOwner}`,databaseOwners.set(store.handle,owner)}return JSON.stringify([owner,runId])}export function ownedProcessCount(owner){return ownedChildren.get(owner)?.size??0}export function terminateOwnedProcesses(owner){const owned=ownedChildren.get(owner);if(owned===void 0)return 0;let terminated=0;for(const child of owned)child.exitCode!==null||child.signalCode!==null||(killGroup(child),terminated+=1);return terminated}function killGroup(child){const container=containers.get(child);if(container!==void 0){if(container.kill().catch(()=>{}),container.backend!=="job-object")try{child.kill("SIGKILL")}catch{}return}if(stopProcessTree(child))return;const pid=child.pid;if(pid!==void 0&&process.platform==="win32")try{spawn("taskkill",["/PID",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0,env:withoutLeadTokenEnv(process.env)}).on("error",()=>{})}catch{}if(pid!==void 0&&process.platform!=="win32")try{process.kill(-pid,"SIGKILL");return}catch{}try{child.kill("SIGKILL")}catch{}}export function terminateLiveProviders(){let terminated=0;for(const child of liveProviders)hardStopped.add(child),killGroup(child),terminated+=1;return terminated}export function liveProviderCount(){return liveProviders.size}const CHAT_KEYS_NEVER_INHERITED=["ANTHROPIC_API_KEY"];export function resolveChildEnv(options){const{env,omitEnv,envAllowlist}=options;if(envAllowlist!==void 0){const picked={};for(const name of envAllowlist){const value=process.env[name];value!==void 0&&(picked[name]=value)}Object.assign(picked,env??{});for(const name of omitEnv??[])delete picked[name];for(const name of CHAT_KEYS_NEVER_INHERITED)env?.[name]===void 0&&delete picked[name];for(const name of Object.keys(picked))isLeadTokenEnvName(name)&&delete picked[name];return picked}const merged={...process.env,...env};for(const name of omitEnv??[])delete merged[name];for(const name of CHAT_KEYS_NEVER_INHERITED)env?.[name]===void 0&&delete merged[name];for(const name of Object.keys(merged))isLeadTokenEnvName(name)&&delete merged[name];return merged}export const NOT_FOUND_CODE=127,TIMEOUT_CODE=124;function reapRejectedSpawn(child,group){return child===void 0?Promise.resolve():new Promise(resolve=>{if(group&&liveProviders.add(child),child.once("close",()=>{liveProviders.delete(child);const container=containers.get(child);container===void 0?resolve():settleContainer(container,{}).then(()=>resolve())}),child.on("error",()=>{}),child.stdout?.resume(),child.stderr?.resume(),group)killGroup(child);else try{child.kill("SIGKILL")}catch{}})}export const OVERFLOW_CODE=125,DEFAULT_TIMEOUT_MS=15e3,DEFAULT_MAX_BUFFER=8*1024*1024;function streamWatchdog(options,onTimeout,onIdle){const hardMs=options.timeoutMs??(options.idleTimeoutMs===void 0?DEFAULT_TIMEOUT_MS:void 0),idleMs=options.idleTimeoutMs;let fired=!1,hardTimer,idleTimer;const fire=()=>{fired||(fired=!0,onTimeout())},idle=()=>{let handled=!1;try{handled=onIdle?.()===!0}catch{handled=!1}handled?armIdle():fire()},armIdle=()=>{idleMs!==void 0&&(idleTimer!==void 0&&clearTimeout(idleTimer),idleTimer=setTimeout(idle,idleMs),idleTimer.unref?.())};return hardMs!==void 0&&(hardTimer=setTimeout(fire,hardMs),hardTimer.unref?.()),armIdle(),{touch:armIdle,stop:()=>{hardTimer!==void 0&&clearTimeout(hardTimer),idleTimer!==void 0&&clearTimeout(idleTimer)}}}const MAX_BUFFER_ERROR="ERR_CHILD_PROCESS_STDIO_MAXBUFFER",TRANSIENT_SPAWN_CODES=new Set(["EAGAIN","EMFILE","ENFILE"]);export const SPAWN_RETRY_DELAYS_MS=[50,100,200,400,800];export function isTransientSpawnFailure(error){return error!=null&&typeof error.code=="string"&&TRANSIENT_SPAWN_CODES.has(error.code)}export async function retryTransientSpawn(attempt,delays=SPAWN_RETRY_DELAYS_MS,sleep=defaultSleep){let last=await attempt();for(const delay of delays){if(!last.transient)return last.result;await sleep(delay),last=await attempt()}return last.result}export function run(file,args,options={}){const{cwd,timeoutMs=DEFAULT_TIMEOUT_MS,maxBuffer=DEFAULT_MAX_BUFFER}=options,childEnv=resolveChildEnv(options);if(options.processGroup===!0)return retryTransientSpawn(()=>runBufferedGroup(file,args,{timeoutMs,maxBuffer,...options.signal===void 0?{}:{signal:options.signal},...options.stdin===void 0?{}:{stdin:options.stdin},...cwd===void 0?{}:{cwd},...childEnv===void 0?{}:{childEnv},...options.onSpawn===void 0?{}:{onSpawn:options.onSpawn},...options.onSpawnFailed===void 0?{}:{onSpawnFailed:options.onSpawnFailed},...options.owner===void 0?{}:{owner:options.owner},...options.beforeSpawn===void 0?{}:{beforeSpawn:options.beforeSpawn},...options.onStdout===void 0?{}:{onStdout:options.onStdout},...options.onStderr===void 0?{}:{onStderr:options.onStderr},...options.fence===void 0?{}:{fence:options.fence},...options.fenceGrants===void 0?{}:{fenceGrants:options.fenceGrants},...options.confinement===void 0?{}:{confinement:options.confinement},...options.onDescendant===void 0?{}:{onDescendant:options.onDescendant},...options.onDescendantWriteFailure===void 0?{}:{onDescendantWriteFailure:options.onDescendantWriteFailure},...options.onDescendantExit===void 0?{}:{onDescendantExit:options.onDescendantExit},...options.onUnknown===void 0?{}:{onUnknown:options.onUnknown},...options.onObservationFailure===void 0?{}:{onObservationFailure:options.onObservationFailure},...options.onContainer===void 0?{}:{onContainer:options.onContainer},...options.onContainerEmpty===void 0?{}:{onContainerEmpty:options.onContainerEmpty}}));let wrapped;try{wrapped=confined(file,args,{...options,cwd,temp:childEnv?.TMPDIR})}catch(error){if(!(error instanceof ContainmentRefusal))throw error;return Promise.resolve({code:CONTAINMENT_REFUSED_CODE,stdout:"",stderr:error.message,timedOut:!1,notFound:!1,containment:{refused:error.message}})}return retryTransientSpawn(()=>new Promise(resolve=>{let hardKill;const child=execFile(wrapped.file,wrapped.args,{cwd,timeout:timeoutMs,maxBuffer,encoding:"utf8",shell:!1,windowsHide:!0,env:withSandboxEnv(childEnv,wrapped.env,(options.fence?.length??0)>0)},(error,stdout,stderr)=>{if(hardKill!==void 0&&clearTimeout(hardKill),error===null){resolve({result:{code:0,stdout,stderr,timedOut:!1,notFound:!1},transient:!1});return}resolve({result:describeFailure(error,stdout,stderr),transient:isTransientSpawnFailure(error)})});timeoutMs>0&&(hardKill=setTimeout(()=>{try{child.kill("SIGKILL")}catch{}},timeoutMs+TERM_GRACE_MS),hardKill.unref?.())}))}export const TERM_GRACE_MS=2e3;function runBufferedGroup(file,args,bag){return new Promise(resolve=>{let child,container=null,attached;try{const spawned=spawnContained(file,args,{cwd:bag.cwd,env:bag.childEnv,stdio:[bag.stdin===void 0?"ignore":"pipe","pipe","pipe"],detached:process.platform!=="win32"},bag.owner??"buffered",{beforeSpawn:bag.beforeSpawn,onSpawn:bag.onSpawn,onSpawnFailed:bag.onSpawnFailed,onContainer:bag.onContainer,onContainerEmpty:bag.onContainerEmpty,onUnknown:bag.onUnknown,fence:bag.fence,fenceGrants:bag.fenceGrants,confinement:bag.confinement});child=spawned.child,container=spawned.container,attached=spawned.attached}catch(error){const left=rejectedChild(error,child);reapRejectedSpawn(left,!0).then(()=>{resolve({result:refusedResult(error),transient:left===void 0&&isTransientSpawnFailure(error)})});return}liveProviders.add(child),registerOwned(bag.owner,child),container===null&&observeProcessTree(child,bag);let stdout="",stderr="",timedOut=!1,overflowed=!1,inputFailed=!1,notFound=!1,attachFailure=null;attached.then(outcome=>{outcome.ok||(attachFailure=outcome.detail)});const timer=setTimeout(()=>{timedOut=!0,killGroup(child)},bag.timeoutMs),aborted=()=>{timedOut=!0,killGroup(child)};bag.signal?.aborted===!0?aborted():bag.signal?.addEventListener("abort",aborted,{once:!0}),child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout+=chunk,stdout.length>bag.maxBuffer&&(overflowed=!0,killGroup(child));try{bag.onStdout?.(chunk)}catch{}}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderr.length<bag.maxBuffer&&(stderr+=chunk.slice(0,bag.maxBuffer-stderr.length));try{bag.onStderr?.(chunk)}catch{}});let settled=!1,transient=!1,endSignal=null;const finish=code=>{if(settled)return;settled=!0,clearTimeout(timer),bag.signal?.removeEventListener("abort",aborted),liveProviders.delete(child),(container===null?Promise.resolve(null):settleContainer(container,bag)).then(empty=>{resolve({result:{code:notFound?NOT_FOUND_CODE:overflowed?OVERFLOW_CODE:timedOut?TIMEOUT_CODE:inputFailed?1:attachFailure!==null||empty===!1?CONTAINMENT_REFUSED_CODE:code??1,stdout,stderr:empty===!1?`${stderr}
|
|
1
|
+
import{ACP_LINE_CAP,createAcpConversation}from"./acp-client.js";import{linuxFenceAvailable,macosFenceAvailable,sandboxedSpawn}from"./agent-fence.js";import{withoutProtectedEnv}from"./protected-storage.js";import{isLeadTokenEnvName,withoutLeadTokenEnv}from"./names.js";import{execFile,execFileSync,spawn}from"node:child_process";import{closeSync,constants as fsConstants,fstatSync,openSync,readlinkSync,readSync,realpathSync}from"node:fs";import{observeProcessTree,stopProcessTree}from"./process-tree.js";import{jsonlDiscriminants}from"./jsonl-discriminants.js";import{createContainer,currentContainment}from"./containment.js";import{claudeLimitsOf,noteLimits}from"./provider-limits.js";import{sleep as defaultSleep}from"./sleep.js";import{primaryResultEvent,topLevelEvent}from"./stream-scope.js";export const CONTAINMENT_REFUSED_CODE=126;const liveProviders=new Set,hardStopped=new WeakSet,ownedChildren=new Map;function registerOwned(owner,child){if(owner===void 0)return;let set=ownedChildren.get(owner);set===void 0&&(set=new Set,ownedChildren.set(owner,set)),set.add(child),child.once("close",()=>{const owned=ownedChildren.get(owner);owned!==void 0&&(owned.delete(child),owned.size===0&&ownedChildren.delete(owner))})}const containers=new WeakMap;export class ContainmentRefusal extends Error{name="ContainmentRefusal"}export function confined(file,args,bag){const fence=bag.fence??[];if(fence.length>0&&bag.confinement!=="required")throw new ContainmentRefusal("This process was given a fence that isn't marked required, so it was not started.");if(fence.length>0&&(macosFenceAvailable()||linuxFenceAvailable()))try{return sandboxedSpawn(file,args,fence,bag.fenceGrants,bag.cwd,bag.temp)}catch(error){throw new ContainmentRefusal(`The sandbox couldn't be made, so nothing was started: ${error instanceof Error?error.message:String(error)}`)}if(bag.confinement==="required")throw new ContainmentRefusal(fence.length===0?"This process must run inside the agent fence, and it was given none.":"This machine can't confine a build (no macOS sandbox, no working bubblewrap), so nothing was started.");return{file,args:[...args],env:{}}}export function withSandboxEnv(env,added,fenced=!1){return fenced?withoutProtectedEnv({...env??process.env,...added}):withoutLeadTokenEnv({...env??process.env,...added})}class SpawnCustodyFailure extends Error{child;reason;name="SpawnCustodyFailure";constructor(child,reason){super(String(reason)),this.child=child,this.reason=reason}}function rejectedChild(error,child){return error instanceof SpawnCustodyFailure?error.child:child}function spawnContained(file,args,spawnOptions,label,bag,contain=!0){const sandboxed=confined(file,args,{...bag,cwd:spawnOptions.cwd,temp:spawnOptions.env?.TMPDIR});({file,args}=sandboxed),spawnOptions={...spawnOptions,env:withSandboxEnv(spawnOptions.env,sandboxed.env,(bag.fence?.length??0)>0)};const effective=contain?currentContainment():null;if(effective!==null&&effective.refusal!==null)throw new ContainmentRefusal(effective.refusal);if(bag.beforeSpawn?.()===!1)throw new Error("the attempt stopped before this process could spawn");const neverStarted=()=>{try{bag.onSpawnFailed?.()}catch{}};let made;try{made=effective===null?{container:null}:createContainer(effective,label)}catch(error){throw neverStarted(),error}if("refused"in made)throw neverStarted(),new ContainmentRefusal(made.refused);const container=made.container;try{container!==null&&bag.onContainer?.({backend:container.backend,id:container.id,...container.identity?{identity:container.identity}:{}})}catch(error){throw container?.release(),neverStarted(),error}let launch;try{launch=container===null?null:container.launch(file,args)}catch(error){throw container?.release(),neverStarted(),error}let child;try{child=spawn(launch===null?file:launch.file,launch===null?[...args]:launch.args,{shell:!1,windowsHide:!0,detached:spawnOptions.detached,stdio:[...spawnOptions.stdio,...launch===null?[]:launch.extraStdio],...spawnOptions.cwd===void 0?{}:{cwd:spawnOptions.cwd},env:spawnOptions.env??withoutLeadTokenEnv(process.env)})}catch(error){try{container!==null&&bag.onContainerEmpty?.()}catch{}throw container?.release(),neverStarted(),error}container!==null&&(containers.set(child,container),child.once("exit",()=>{settleContainer(container,bag).then(empty=>{empty||(child.stdout?.destroy(),child.stderr?.destroy())})}),child.once("error",()=>{settleContainer(container,bag)}));try{child.pid!==void 0?bag.onSpawn?.(child.pid):container===null&&neverStarted()}catch(error){throw new SpawnCustodyFailure(child,error)}const attached=launch===null||child.pid===void 0?Promise.resolve({ok:!0}):launch.attach(child);return{child,container,attached}}const containerSettlements=new WeakMap;function settleContainer(container,bag,timeoutMs=5e3){const existing=containerSettlements.get(container);if(existing!==void 0)return existing;const settling=finishContainer(container,bag,timeoutMs);return containerSettlements.set(container,settling),settling}async function finishContainer(container,bag,timeoutMs){let empty=container.populated()===!1;try{empty||(empty=await container.kill(timeoutMs))}catch{empty=!1}try{empty?bag.onContainerEmpty?.():bag.onUnknown?.()}catch{empty=!1}try{container.release()}catch{}return empty}function containmentOf(container,empty,attachFailure){return attachFailure!==null?{containment:{refused:attachFailure}}:container===null||empty===null?{}:{containment:{backend:container.backend,id:container.id,empty}}}function startStream(file,args,options,stdio,childEnv,resolve){let child,container=null;const attach={failure:null};try{const spawned=spawnStream(file,args,options,stdio,childEnv);child=spawned.child,container=spawned.container,spawned.attached.then(outcome=>{outcome.ok||(attach.failure=outcome.detail)})}catch(error){return reapRejectedSpawn(rejectedChild(error,child),options.processGroup===!0).then(()=>resolve(refusedResult(error))),null}return options.processGroup===!0&&liveProviders.add(child),registerOwned(options.owner,child),options.processGroup===!0&&container===null&&observeProcessTree(child,options),{child,container,attach}}function spawnStream(file,args,options,stdio,childEnv){return spawnContained(file,args,{cwd:options.cwd,env:childEnv,stdio,detached:options.processGroup===!0&&process.platform!=="win32"},options.owner??"stream",{beforeSpawn:options.beforeSpawn,onSpawn:options.onSpawn,onSpawnFailed:options.onSpawnFailed,onContainer:options.onContainer,onContainerEmpty:options.onContainerEmpty,onUnknown:options.onUnknown,fence:options.fence,fenceGrants:options.fenceGrants,confinement:options.confinement},options.processGroup===!0)}function refusedResult(error){return error instanceof ContainmentRefusal?{code:CONTAINMENT_REFUSED_CODE,stdout:"",stderr:error.message,timedOut:!1,notFound:!1,containment:{refused:error.message}}:{code:1,stdout:"",stderr:String(error instanceof SpawnCustodyFailure?error.reason:error),timedOut:!1,notFound:!1}}const databaseOwners=new WeakMap;let memoryDatabaseOwner=0;export function runOwnerTag(store,runId){let owner=databaseOwners.get(store.handle);if(owner===void 0){const file=store.handle.prepare("PRAGMA database_list").all().find(row=>row.name==="main")?.file;owner=typeof file=="string"&&file!==""?`file:${realpathSync(file)}`:`memory:${++memoryDatabaseOwner}`,databaseOwners.set(store.handle,owner)}return JSON.stringify([owner,runId])}export function ownedProcessCount(owner){return ownedChildren.get(owner)?.size??0}export function terminateOwnedProcesses(owner){const owned=ownedChildren.get(owner);if(owned===void 0)return 0;let terminated=0;for(const child of owned)child.exitCode!==null||child.signalCode!==null||(killGroup(child),terminated+=1);return terminated}function killGroup(child){const container=containers.get(child);if(container!==void 0){if(container.kill().catch(()=>{}),container.backend!=="job-object")try{child.kill("SIGKILL")}catch{}return}if(stopProcessTree(child))return;const pid=child.pid;if(pid!==void 0&&process.platform==="win32")try{spawn("taskkill",["/PID",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0,env:withoutLeadTokenEnv(process.env)}).on("error",()=>{})}catch{}if(pid!==void 0&&process.platform!=="win32")try{process.kill(-pid,"SIGKILL");return}catch{}try{child.kill("SIGKILL")}catch{}}export function terminateLiveProviders(){let terminated=0;for(const child of liveProviders)hardStopped.add(child),killGroup(child),terminated+=1;return terminated}export function liveProviderCount(){return liveProviders.size}const CHAT_KEYS_NEVER_INHERITED=["ANTHROPIC_API_KEY"];export function resolveChildEnv(options){const{env,omitEnv,envAllowlist}=options;if(envAllowlist!==void 0){const picked={};for(const name of envAllowlist){const value=process.env[name];value!==void 0&&(picked[name]=value)}Object.assign(picked,env??{});for(const name of omitEnv??[])delete picked[name];for(const name of CHAT_KEYS_NEVER_INHERITED)env?.[name]===void 0&&delete picked[name];for(const name of Object.keys(picked))isLeadTokenEnvName(name)&&delete picked[name];return picked}const merged={...process.env,...env};for(const name of omitEnv??[])delete merged[name];for(const name of CHAT_KEYS_NEVER_INHERITED)env?.[name]===void 0&&delete merged[name];for(const name of Object.keys(merged))isLeadTokenEnvName(name)&&delete merged[name];return merged}export const NOT_FOUND_CODE=127,TIMEOUT_CODE=124;function reapRejectedSpawn(child,group){return child===void 0?Promise.resolve():new Promise(resolve=>{if(group&&liveProviders.add(child),child.once("close",()=>{liveProviders.delete(child);const container=containers.get(child);container===void 0?resolve():settleContainer(container,{}).then(()=>resolve())}),child.on("error",()=>{}),child.stdout?.resume(),child.stderr?.resume(),group)killGroup(child);else try{child.kill("SIGKILL")}catch{}})}export const OVERFLOW_CODE=125,DEFAULT_TIMEOUT_MS=15e3,DEFAULT_MAX_BUFFER=8*1024*1024;function streamWatchdog(options,onTimeout,onIdle){const hardMs=options.timeoutMs??(options.idleTimeoutMs===void 0?DEFAULT_TIMEOUT_MS:void 0),idleMs=options.idleTimeoutMs;let fired=!1,hardTimer,idleTimer;const fire=()=>{fired||(fired=!0,onTimeout())},idle=()=>{let handled=!1;try{handled=onIdle?.()===!0}catch{handled=!1}handled?armIdle():fire()},armIdle=()=>{idleMs!==void 0&&(idleTimer!==void 0&&clearTimeout(idleTimer),idleTimer=setTimeout(idle,idleMs),idleTimer.unref?.())};return hardMs!==void 0&&(hardTimer=setTimeout(fire,hardMs),hardTimer.unref?.()),armIdle(),{touch:armIdle,stop:()=>{hardTimer!==void 0&&clearTimeout(hardTimer),idleTimer!==void 0&&clearTimeout(idleTimer)}}}const MAX_BUFFER_ERROR="ERR_CHILD_PROCESS_STDIO_MAXBUFFER",TRANSIENT_SPAWN_CODES=new Set(["EAGAIN","EMFILE","ENFILE"]);export const SPAWN_RETRY_DELAYS_MS=[50,100,200,400,800];export function isTransientSpawnFailure(error){return error!=null&&typeof error.code=="string"&&TRANSIENT_SPAWN_CODES.has(error.code)}export async function retryTransientSpawn(attempt,delays=SPAWN_RETRY_DELAYS_MS,sleep=defaultSleep){let last=await attempt();for(const delay of delays){if(!last.transient)return last.result;await sleep(delay),last=await attempt()}return last.result}export function run(file,args,options={}){const{cwd,timeoutMs=DEFAULT_TIMEOUT_MS,maxBuffer=DEFAULT_MAX_BUFFER}=options,childEnv=resolveChildEnv(options);if(options.processGroup===!0)return retryTransientSpawn(()=>runBufferedGroup(file,args,{timeoutMs,maxBuffer,...options.signal===void 0?{}:{signal:options.signal},...options.stdin===void 0?{}:{stdin:options.stdin},...cwd===void 0?{}:{cwd},...childEnv===void 0?{}:{childEnv},...options.onSpawn===void 0?{}:{onSpawn:options.onSpawn},...options.onSpawnFailed===void 0?{}:{onSpawnFailed:options.onSpawnFailed},...options.owner===void 0?{}:{owner:options.owner},...options.beforeSpawn===void 0?{}:{beforeSpawn:options.beforeSpawn},...options.onStdout===void 0?{}:{onStdout:options.onStdout},...options.onStderr===void 0?{}:{onStderr:options.onStderr},...options.fence===void 0?{}:{fence:options.fence},...options.fenceGrants===void 0?{}:{fenceGrants:options.fenceGrants},...options.confinement===void 0?{}:{confinement:options.confinement},...options.onDescendant===void 0?{}:{onDescendant:options.onDescendant},...options.onDescendantWriteFailure===void 0?{}:{onDescendantWriteFailure:options.onDescendantWriteFailure},...options.onDescendantExit===void 0?{}:{onDescendantExit:options.onDescendantExit},...options.onUnknown===void 0?{}:{onUnknown:options.onUnknown},...options.onObservationFailure===void 0?{}:{onObservationFailure:options.onObservationFailure},...options.onContainer===void 0?{}:{onContainer:options.onContainer},...options.onContainerEmpty===void 0?{}:{onContainerEmpty:options.onContainerEmpty}}));let wrapped;try{wrapped=confined(file,args,{...options,cwd,temp:childEnv?.TMPDIR})}catch(error){if(!(error instanceof ContainmentRefusal))throw error;return Promise.resolve({code:CONTAINMENT_REFUSED_CODE,stdout:"",stderr:error.message,timedOut:!1,notFound:!1,containment:{refused:error.message}})}return retryTransientSpawn(()=>new Promise(resolve=>{let hardKill;const child=execFile(wrapped.file,wrapped.args,{cwd,timeout:timeoutMs,maxBuffer,encoding:"utf8",shell:!1,windowsHide:!0,env:withSandboxEnv(childEnv,wrapped.env,(options.fence?.length??0)>0)},(error,stdout,stderr)=>{if(hardKill!==void 0&&clearTimeout(hardKill),error===null){resolve({result:{code:0,stdout,stderr,timedOut:!1,notFound:!1},transient:!1});return}resolve({result:describeFailure(error,stdout,stderr),transient:isTransientSpawnFailure(error)})});timeoutMs>0&&(hardKill=setTimeout(()=>{try{child.kill("SIGKILL")}catch{}},timeoutMs+TERM_GRACE_MS),hardKill.unref?.())}))}export const TERM_GRACE_MS=2e3;function runBufferedGroup(file,args,bag){return new Promise(resolve=>{let child,container=null,attached;try{const spawned=spawnContained(file,args,{cwd:bag.cwd,env:bag.childEnv,stdio:[bag.stdin===void 0?"ignore":"pipe","pipe","pipe"],detached:process.platform!=="win32"},bag.owner??"buffered",{beforeSpawn:bag.beforeSpawn,onSpawn:bag.onSpawn,onSpawnFailed:bag.onSpawnFailed,onContainer:bag.onContainer,onContainerEmpty:bag.onContainerEmpty,onUnknown:bag.onUnknown,fence:bag.fence,fenceGrants:bag.fenceGrants,confinement:bag.confinement});child=spawned.child,container=spawned.container,attached=spawned.attached}catch(error){const left=rejectedChild(error,child);reapRejectedSpawn(left,!0).then(()=>{resolve({result:refusedResult(error),transient:left===void 0&&isTransientSpawnFailure(error)})});return}liveProviders.add(child),registerOwned(bag.owner,child),container===null&&observeProcessTree(child,bag);let stdout="",stderr="",timedOut=!1,overflowed=!1,inputFailed=!1,notFound=!1,attachFailure=null;attached.then(outcome=>{outcome.ok||(attachFailure=outcome.detail)});const timer=setTimeout(()=>{timedOut=!0,killGroup(child)},bag.timeoutMs),aborted=()=>{timedOut=!0,killGroup(child)};bag.signal?.aborted===!0?aborted():bag.signal?.addEventListener("abort",aborted,{once:!0}),child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout+=chunk,stdout.length>bag.maxBuffer&&(overflowed=!0,killGroup(child));try{bag.onStdout?.(chunk)}catch{}}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderr.length<bag.maxBuffer&&(stderr+=chunk.slice(0,bag.maxBuffer-stderr.length));try{bag.onStderr?.(chunk)}catch{}});let settled=!1,transient=!1,endSignal=null;const finish=code=>{if(settled)return;settled=!0,clearTimeout(timer),bag.signal?.removeEventListener("abort",aborted),liveProviders.delete(child),(container===null?Promise.resolve(null):settleContainer(container,bag)).then(empty=>{resolve({result:{code:notFound?NOT_FOUND_CODE:overflowed?OVERFLOW_CODE:timedOut?TIMEOUT_CODE:inputFailed?1:attachFailure!==null||empty===!1?CONTAINMENT_REFUSED_CODE:code??1,stdout,stderr:empty===!1?`${stderr}
|
|
2
2
|
Native process containment could not prove all descendants exited.`.trim():attachFailure!==null&&stderr===""?attachFailure:stderr,timedOut:timedOut&&!overflowed,notFound,...containmentOf(container,empty,attachFailure),...endSignal===null?{}:{signal:endSignal},...hardStopped.has(child)?{stoppedByPlane:!0}:{}},transient})})};child.on("error",error=>{notFound=error.code==="ENOENT",transient=isTransientSpawnFailure(error),stderr===""&&(stderr=String(error)),finish(null)}),child.on("close",(code,signal)=>{endSignal=code===null?signal??null:null,finish(code)}),bag.stdin!==void 0&&child.stdin!==null&&(child.stdin.on("error",()=>{inputFailed=!0,stderr="prompt input failed: the provider closed its input before delivery completed",killGroup(child)}),child.stdin.end(bag.stdin,"utf8"))})}function describeFailure(error,stdout,stderr){const notFound=error.code==="ENOENT",overflowed=error.code===MAX_BUFFER_ERROR,timedOut=!overflowed&&error.killed===!0;return{code:resolveCode(error,{notFound,overflowed,timedOut}),stdout,stderr:stderr===""?error.message:stderr,timedOut,notFound}}function resolveCode(error,flags){return typeof error.code=="number"?error.code:flags.notFound?NOT_FOUND_CODE:flags.overflowed?OVERFLOW_CODE:flags.timedOut?TIMEOUT_CODE:1}const JSONL_LINE_CAP=64*1024,JSONL_STDERR_CAP=64*1024;function transportSessionId(value){if(typeof value!="string")return null;const id=value.trim();return id===""?null:id}export const JSONL_EVENT_HARD_CAP=512*1024;const JSONL_OVERFLOW_PREFIX_CAP=4*1024;function boundedJsonlFramer(cap,onLine,inspectDiscriminants=!1,tailCap=0){const retained=Buffer.allocUnsafe(cap);let retainedBytes=0,originalBytes=0,nonWhitespace=!1,discriminants=inspectDiscriminants?jsonlDiscriminants():null;const tailSize=Math.max(0,Math.min(tailCap,cap)),tail=tailSize===0?null:Buffer.allocUnsafe(tailSize);let tailBytes=0,tailSeeded=!1;const keepTail=part=>{if(tail===null)return;if(tailSeeded||(tailSeeded=!0,tailBytes=retained.copy(tail,0,retainedBytes-tailSize,retainedBytes)),part.length>=tailSize){tailBytes=part.copy(tail,0,part.length-tailSize);return}const keepOld=Math.min(tailBytes,tailSize-part.length);tail.copyWithin(0,tailBytes-keepOld,tailBytes),tailBytes=keepOld+part.copy(tail,keepOld)},append=part=>{discriminants?.push(part);const before=originalBytes;if(originalBytes+=part.length,!nonWhitespace){for(const byte of part)if(byte!==9&&byte!==10&&byte!==13&&byte!==32){nonWhitespace=!0;break}}retainedBytes<cap&&(retainedBytes+=part.copy(retained,retainedBytes,0,cap-retainedBytes)),tail!==null&&originalBytes>cap&&keepTail(before>=cap?part:part.subarray(cap-before))},emit=()=>{onLine({prefix:retained.subarray(0,retainedBytes),bytesOriginal:originalBytes,overflowed:originalBytes>cap,...discriminants===null?{}:{discriminants:discriminants.finish()},...tail!==null&&originalBytes>cap?{tail:tail.subarray(0,tailBytes)}:{}}),tailBytes=0,tailSeeded=!1,retainedBytes=0,originalBytes=0,nonWhitespace=!1,discriminants=inspectDiscriminants?jsonlDiscriminants():null};return{push(chunk){let start=0;for(;;){const newline=chunk.indexOf(10,start);if(newline===-1){append(chunk.subarray(start));return}append(chunk.subarray(start,newline)),emit(),start=newline+1}},finish(){originalBytes>0&&nonWhitespace&&emit()}}}function overflowReceiptText(transport,line){const rawPrefix=line.prefix.subarray(0,Math.min(line.prefix.length,JSONL_OVERFLOW_PREFIX_CAP));return JSON.stringify({type:"standing-orders.stream-event-overflow",transport,message:`The provider emitted a JSONL event larger than the ${JSONL_EVENT_HARD_CAP}-byte safety limit.`,eventBytesOriginal:line.bytesOriginal,hardCapBytes:JSONL_EVENT_HARD_CAP,prefixBytes:rawPrefix.length,prefix:rawPrefix.toString("utf8"),prefixBase64:rawPrefix.toString("base64")})}function malformedReceiptText(transport,line){const rawPrefix=line.prefix.subarray(0,Math.min(line.prefix.length,JSONL_OVERFLOW_PREFIX_CAP));return JSON.stringify({type:"standing-orders.stream-event-malformed",transport,message:"The provider emitted malformed JSON for a load-bearing stream event after initialization.",eventBytesOriginal:line.bytesOriginal,prefixBytes:rawPrefix.length,prefix:rawPrefix.toString("utf8"),prefixBase64:rawPrefix.toString("base64")})}function codexOverflowLine(line){return JSON.stringify({type:"turn.failed",error:{type:"standing-orders.stream-event-overflow",message:overflowReceiptText("codex",line)}})}function codexMalformedLine(line){return JSON.stringify({type:"turn.failed",error:{type:"standing-orders.stream-event-malformed",message:malformedReceiptText("codex",line)}})}function claudeOverflowLine(line){return JSON.stringify({type:"result",subtype:"standing-orders-stream-event-overflow",is_error:!0,result:overflowReceiptText("claude",line)})}function geminiOverflowLine(line){return JSON.stringify({type:"result",status:"standing-orders-stream-event-overflow",error:{message:overflowReceiptText("gemini",line)}})}function geminiMalformedLine(line){return JSON.stringify({type:"result",status:"standing-orders-stream-event-malformed",error:{message:malformedReceiptText("gemini",line)}})}function leadingJsonObjectType(prefix){return/^\s*\{\s*"type"\s*:\s*"([A-Za-z0-9._-]+)"/.exec(prefix.toString("utf8",0,Math.min(prefix.length,256)))?.[1]??null}function leadingCodexCompletedItemType(prefix){return/^\s*\{\s*"type"\s*:\s*"item\.completed"\s*,\s*"item"\s*:\s*\{\s*"type"\s*:\s*"([A-Za-z0-9._-]+)"/.exec(prefix.toString("utf8",0,Math.min(prefix.length,512)))?.[1]??null}function leadingClaudeSystemSubtype(prefix){return/^\s*\{\s*"type"\s*:\s*"system"\s*,\s*"subtype"\s*:\s*"([A-Za-z0-9._-]+)"/.exec(prefix.toString("utf8",0,Math.min(prefix.length,512)))?.[1]??null}const CLAUDE_RESULT_TAIL_CAP=64*1024;export const CLAUDE_COST_UNKNOWN="standing_orders_cost_unknown";function malformedCodexEventIsLoadBearing(prefix){const type=leadingJsonObjectType(prefix);if(type==="thread.started"||type==="turn.completed"||type==="turn.failed")return!0;if(type!=="item.completed")return!1;const itemType=leadingCodexCompletedItemType(prefix);return itemType===null||itemType==="agent_message"}function malformedGeminiEventIsLoadBearing(prefix){const type=leadingJsonObjectType(prefix);return type==="init"||type==="result"}export function runStreamJsonl(file,args,options={}){const childEnv=resolveChildEnv(options);return new Promise(resolve=>{const started=startStream(file,args,options,[options.stdin===void 0?"ignore":"pipe","pipe","pipe"],childEnv,resolve);if(started===null)return;const{child,container,attach}=started;let startedLine=null,startedIdentityLine=null,conflictingStartedLine=null,startedSessionId=null,completedLine=null,failedLine=null,overflowLine=null,malformedLine=null,lastMessage=null,stderr="",timedOut=!1,notFound=!1,inputFailed=!1;const framing=boundedJsonlFramer(JSONL_EVENT_HARD_CAP,framed=>{if(framed.overflowed){const type=framed.discriminants?.type??null;if(type!==null&&!["thread.started","turn.completed","turn.failed","item.completed"].includes(type))return;if(type==="item.completed"){const itemType=framed.discriminants?.itemType;if(itemType!=null&&["command_execution","mcp_tool_call","web_search","file_change","todo_list"].includes(itemType))return}overflowLine===null&&(overflowLine=codexOverflowLine(framed));return}const line=framed.prefix.toString("utf8");try{const event=JSON.parse(line),type=String(event.type??"");if(type==="thread.started"){startedLine=line;const id=transportSessionId(event.thread_id);if(id!==null&&(startedSessionId===null?(startedSessionId=id,startedIdentityLine=line):id!==startedSessionId&&conflictingStartedLine===null&&(conflictingStartedLine=line),options.onSessionId!==void 0))try{options.onSessionId(id)}catch{}}else if(type==="turn.completed")completedLine=line;else if(type==="turn.failed")failedLine=line;else if(type==="item.completed"){const item=event.item;item!==void 0&&String(item.type??"")==="agent_message"&&(lastMessage=line)}if(options.onStreamEvent!==void 0)try{options.onStreamEvent(event)}catch{}}catch{startedLine!==null&&malformedLine===null&&malformedCodexEventIsLoadBearing(framed.prefix)&&(malformedLine=codexMalformedLine(framed))}},!0),watchdog=streamWatchdog(options,()=>{timedOut=!0,options.processGroup===!0?killGroup(child):child.kill("SIGKILL")});child.stdout?.on("data",chunk=>{watchdog.touch(),framing.push(chunk)}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{watchdog.touch(),stderr.length<JSONL_STDERR_CAP&&(stderr+=chunk.slice(0,JSONL_STDERR_CAP-stderr.length))});let settled=!1;const finish=code=>{if(settled)return;settled=!0,watchdog.stop(),liveProviders.delete(child),framing.finish();const lines=[startedIdentityLine,conflictingStartedLine,startedLine,completedLine,failedLine,overflowLine,malformedLine,lastMessage].filter(line=>line!==null).filter((line,index,all)=>all.indexOf(line)===index);(container===null?Promise.resolve(null):settleContainer(container,options)).then(empty=>resolve({code:notFound?NOT_FOUND_CODE:timedOut?TIMEOUT_CODE:inputFailed?1:attach.failure!==null||empty===!1?CONTAINMENT_REFUSED_CODE:code??1,stdout:lines.join(`
|
|
3
3
|
`),stderr:empty===!1?`${stderr}
|
|
4
4
|
Native process containment could not prove all descendants exited.`.trim():attach.failure!==null&&stderr===""?attach.failure:stderr,timedOut,notFound,...containmentOf(container,empty,attach.failure)}))};child.on("error",error=>{notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error)),finish(null)}),child.on("close",code=>finish(code)),options.stdin!==void 0&&child.stdin!==null&&(child.stdin.on("error",error=>{inputFailed=!0,stderr=`review prompt input failed: ${String(error)}`.slice(0,JSONL_STDERR_CAP),options.processGroup===!0?killGroup(child):child.kill("SIGKILL")}),child.stdin.end(options.stdin,"utf8"))})}export function runGeminiStreamJsonl(file,args,options={}){const childEnv=resolveChildEnv(options);return new Promise(resolve=>{const started=startStream(file,args,options,["ignore","pipe","pipe"],childEnv,resolve);if(started===null)return;const{child,container,attach}=started;let initLine=null,initIdentityLine=null,conflictingInitLine=null,initSessionId=null,errorLine=null,resultLine=null,message="",messageTruncated=!1,stderr="",timedOut=!1,notFound=!1,overflowLine=null,malformedLine=null;const framing=boundedJsonlFramer(JSONL_EVENT_HARD_CAP,framed=>{if(framed.overflowed){const type2=leadingJsonObjectType(framed.prefix);type2!=="tool_use"&&type2!=="tool_result"&&overflowLine===null&&(overflowLine=geminiOverflowLine(framed));return}const line=framed.prefix.toString("utf8");let event;try{event=JSON.parse(line)}catch{initLine!==null&&malformedLine===null&&malformedGeminiEventIsLoadBearing(framed.prefix)&&(malformedLine=geminiMalformedLine(framed));return}if(event===null||typeof event!="object")return;const type=String(event.type??"");if(type==="init"){initLine===null&&(initLine=line);const id=transportSessionId(event.session_id);let identityWitness=!1;if(id!==null&&(initSessionId===null?(initSessionId=id,initIdentityLine=line,identityWitness=!0):id!==initSessionId&&conflictingInitLine===null&&(conflictingInitLine=line,identityWitness=!0),identityWitness&&options.onSessionId!==void 0))try{options.onSessionId(id)}catch{}}else if(type==="result")resultLine=line;else if(type==="error")errorLine===null&&String(event.severity??"")==="error"&&(errorLine=line);else if(type==="message"&&String(event.role??"")==="assistant"){const content=event.content;if(typeof content!="string")return;event.delta===!0?messageTruncated||(message+=content,Buffer.byteLength(message,"utf8")>JSONL_LINE_CAP&&(messageTruncated=!0)):(message=content,messageTruncated=Buffer.byteLength(message,"utf8")>JSONL_LINE_CAP)}if(options.onStreamEvent!==void 0)try{options.onStreamEvent(event)}catch{}}),watchdog=streamWatchdog(options,()=>{timedOut=!0,options.processGroup===!0?killGroup(child):child.kill("SIGKILL")});child.stdout?.on("data",chunk=>{watchdog.touch(),framing.push(chunk)}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{watchdog.touch(),stderr.length<JSONL_STDERR_CAP&&(stderr+=chunk.slice(0,JSONL_STDERR_CAP-stderr.length))});let settled=!1;const finish=code=>{if(settled)return;settled=!0,watchdog.stop(),liveProviders.delete(child),framing.finish();const lines=[initLine,initIdentityLine,conflictingInitLine].filter(line=>line!==null).filter((line,index,all)=>all.indexOf(line)===index);errorLine!==null&&lines.push(errorLine),message!==""&&lines.push(syntheticMessageLine(message,messageTruncated)),resultLine!==null&&lines.push(resultLine),overflowLine!==null&&lines.push(overflowLine),malformedLine!==null&&lines.push(malformedLine),(container===null?Promise.resolve(null):settleContainer(container,options)).then(empty=>resolve({code:notFound?NOT_FOUND_CODE:timedOut?TIMEOUT_CODE:attach.failure!==null||empty===!1?CONTAINMENT_REFUSED_CODE:code??1,stdout:lines.join(`
|
|
5
5
|
`),stderr:empty===!1?`${stderr}
|
|
6
6
|
Native process containment could not prove all descendants exited.`.trim():attach.failure!==null&&stderr===""?attach.failure:stderr,timedOut,notFound,...containmentOf(container,empty,attach.failure)}))};child.on("error",error=>{notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error)),finish(null)}),child.on("close",code=>finish(code))})}function processRows(){try{return execFileSync("/bin/ps",["-axo","pid=,ppid=,pgid=,stat=,comm="],{encoding:"utf8",timeout:2e3,maxBuffer:8*1024*1024,env:withoutLeadTokenEnv(process.env)}).split(`
|
|
7
|
-
`).flatMap(line=>{const parts=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);return parts===null?[]:[{pid:Number(parts[1]),parent:Number(parts[2]),group:Number(parts[3]),state:parts[4],name:parts[5].trim()}]})}catch{return null}}function liveUnderAgent(root,names,rootIsWrapper=!1){const rows=processRows();if(rows===null)return null;const children=new Map;for(const row of rows)children.set(row.parent,[...children.get(row.parent)??[],row]);const self=rows.find(row=>row.pid===root),named=row=>agentNamed(row,names);let agent=!rootIsWrapper&&self!==void 0&&named(self)?root:null;const pending=[...children.get(root)??[]];for(;agent===null&&pending.length>0;){const row=pending.shift();named(row)?agent=row.pid:pending.push(...children.get(row.pid)??[])}if(agent===null)return[];const found=[],below=[...children.get(agent)??[]];for(;below.length>0;){const row=below.pop();row.state.startsWith("Z")||found.push({pid:row.pid,group:row.group}),below.push(...children.get(row.pid)??[])}return found}function linuxProgramOf(pid){if(process.platform!=="linux")return null;try{return readlinkSync(`/proc/${pid}/exe`).replace(/ \(deleted\)$/,"").split("/").pop()||null}catch{return null}}
|
|
8
|
-
`);const
|
|
7
|
+
`).flatMap(line=>{const parts=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);return parts===null?[]:[{pid:Number(parts[1]),parent:Number(parts[2]),group:Number(parts[3]),state:parts[4],name:parts[5].trim()}]})}catch{return null}}function liveUnderAgent(root,names,rootIsWrapper=!1){const rows=processRows();if(rows===null)return null;const children=new Map;for(const row of rows)children.set(row.parent,[...children.get(row.parent)??[],row]);const self=rows.find(row=>row.pid===root),named=row=>agentNamed(row,names);let agent=!rootIsWrapper&&self!==void 0&&named(self)?root:null;const pending=[...children.get(root)??[]];for(;agent===null&&pending.length>0;){const row=pending.shift();named(row)?agent=row.pid:pending.push(...children.get(row.pid)??[])}if(agent===null)return[];const found=[],below=[...children.get(agent)??[]];for(;below.length>0;){const row=below.pop();row.state.startsWith("Z")||found.push({pid:row.pid,group:row.group}),below.push(...children.get(row.pid)??[])}return found}function linuxProgramOf(pid){if(process.platform!=="linux")return null;try{return readlinkSync(`/proc/${pid}/exe`).replace(/ \(deleted\)$/,"").split("/").pop()||null}catch{return null}}const SHELL_SHEBANG=/^#!\s*(?:\/usr\/bin\/env\s+)?(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:sh|bash|zsh|dash|ksh)(?:\s|$)/,EXEC_LINE=/^\s*(?:[A-Za-z_][A-Za-z0-9_]*=(?:"[^"\n$`\\]*"|'[^'\n]*'|[^\s"'$`\\;&|]*)\s+)*exec\s+(?:"(\/[^"\n$`\\]+)"|'(\/[^'\n]+)'|(\/[^\s"'$`\\;&|<>()]+))(?=\s|$)/;export function execTargetOf(path){let fd=null;try{fd=openSync(path,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK);const stat=fstatSync(fd);if(!stat.isFile()||stat.size>4096)return null;const buffer=Buffer.alloc(4097),read=readSync(fd,buffer,0,buffer.length,0);if(read>4096)return null;const lines=buffer.subarray(0,read).toString("utf8").split(`
|
|
8
|
+
`);if(!SHELL_SHEBANG.test(lines[0]??""))return null;const commands=lines.slice(1).filter(line=>line.trim()!==""&&!/^\s*#/.test(line));if(commands.length!==1)return null;const match=EXEC_LINE.exec(commands[0]);return match===null?null:match[1]??match[2]??match[3]??null}catch{return null}finally{if(fd!==null)try{closeSync(fd)}catch{}}}export function agentNamed(row,names,programOf=linuxProgramOf){if(names.some(name=>row.name===name||row.name.endsWith(`/${name}`)))return!0;const program=programOf(row.pid);return program!==null&&names.includes(program)}export const ACP_SHUTDOWN_MS={close:2e3,eof:5e3,term:5e3},ACP_HANDSHAKE_MS=3e4,ACP_PIPES_AFTER_EXIT_MS=5e3;function termGroup(child){const pid=child.pid;try{pid!==void 0&&process.platform!=="win32"?process.kill(-pid,"SIGTERM"):child.kill("SIGTERM")}catch{}}export function runAcpSession(file,args,options={}){const acp=options.acp;if(acp===void 0)return Promise.resolve({code:CONTAINMENT_REFUSED_CODE,stdout:"",stderr:"an ACP run needs its conversation terms",timedOut:!1,notFound:!1});const childEnv=resolveChildEnv(options);return new Promise(resolve=>{const started=acp.startGate===!0?startStream("/bin/sh",["-c",'IFS= read -r turn_gate || exit 125; [ "$turn_gate" = start ] || exit 125; exec "$@"',"toolroll-chat-gate",file,...args],options,["pipe","pipe","pipe"],childEnv,resolve):startStream(file,args,options,["pipe","pipe","pipe"],childEnv,resolve);if(started===null)return;const{child,container,attach}=started;acp.startGate===!0&&child.stdin?.write(`start
|
|
9
|
+
`);const conversation=createAcpConversation({cwd:options.cwd??process.cwd(),prompt:acp.prompt,model:acp.model,expect:acp.expect,authMethod:acp.authMethod??null,...acp.mcpOffer===void 0?{}:{mcpOffer:acp.mcpOffer},...acp.resumeSession==null?{}:{resumeSession:acp.resumeSession}}),launched=[file,...args.slice(0,2)].filter(one=>one.startsWith("/")),agentNames=[...new Set([...launched,...launched.flatMap(one=>{const target=execTargetOf(one);return target===null?[]:[target]})].map(one=>one.split("/").pop()).filter(one=>one!==""))];let stderr="",timedOut=!1,notFound=!1,settled=!1,shuttingDown=!1,termAfterTerminal=!1,killAfterTerminal=!1,endedBy="self",announced=null;const timers=[],later=(ms,fn)=>{const timer=setTimeout(fn,ms);timer.unref?.(),timers.push(timer)},write=lines=>{for(const one of lines){if(child.stdin===null||child.stdin.destroyed||child.stdin.writableEnded)return;try{child.stdin.write(`${one}
|
|
9
10
|
`)}catch{}}},forceKill=()=>{endedBy="kill",options.processGroup===!0?killGroup(child):child.kill("SIGKILL")};let handshakePhase=null;const armHandshake=()=>{const phase=conversation.phase();if(phase===handshakePhase||phase!=="initialize"&&phase!=="authenticate"&&phase!=="session"&&phase!=="model")return;handshakePhase=phase;const limit=acp.handshakeMs??ACP_HANDSHAKE_MS;later(limit,()=>{if(settled||conversation.phase()!==phase)return;const stepName=phase==="initialize"?"initialize":phase==="authenticate"?"authenticate":phase==="session"?acp.resumeSession?"session/load":"session/new":"the model choice";conversation.refuse(`the agent took more than ${limit/1e3} s to answer ${stepName}`),forceKill()})},exited=()=>child.exitCode!==null||child.signalCode!==null,shutdown=()=>{if(shuttingDown)return;if(shuttingDown=!0,conversation.phase()==="failed"){forceKill();return}const endInput=()=>{if(!exited()){try{child.stdin?.end()}catch{}endedBy="eof",later(ACP_SHUTDOWN_MS.eof,()=>{exited()||(termAfterTerminal=conversation.phase()==="ended",endedBy="term",termGroup(child),later(ACP_SHUTDOWN_MS.term,()=>{exited()||(killAfterTerminal=conversation.phase()==="ended",forceKill())}))})}},close=conversation.close();if(close.length===0){endInput();return}write(close);const started2=Date.now(),waitClose=()=>{conversation.closeAnswered()||Date.now()-started2>=ACP_SHUTDOWN_MS.close||exited()?endInput():later(50,waitClose)};waitClose()},framing=boundedJsonlFramer(ACP_LINE_CAP,framed=>{if(settled)return;armHandshake();const reaction=framed.overflowed?(conversation.refuse("the agent wrote a line too long to read"),{send:[],live:[]}):conversation.receive(framed.prefix.toString("utf8"));write(reaction.send);const id=conversation.sessionId();if(id!==null&&announced===null){announced=id;try{options.onSessionId?.(id)}catch{}}for(const update of reaction.live)try{options.onStreamEvent?.({acp:update})}catch{}const phase=conversation.phase();phase==="failed"||phase==="ended"?shutdown():armHandshake()}),watchdog=streamWatchdog(options,()=>{timedOut=!0,forceKill()});child.stdout?.on("data",chunk=>{watchdog.touch(),framing.push(chunk)}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{watchdog.touch(),stderr.length<JSONL_STDERR_CAP&&(stderr+=chunk.slice(0,JSONL_STDERR_CAP-stderr.length))}),child.stdin?.on("error",()=>{}),write(conversation.start()),armHandshake();try{acp.onControl?.({cancel:deadlineMs=>{write(conversation.cancel()),deadlineMs!==void 0&&later(deadlineMs,()=>{settled||conversation.terminal()!==null||(conversation.refuse(`the agent didn't answer the cancel within ${Math.round(deadlineMs/1e3)} s`),forceKill())})},stop:graceMs=>{if(!(settled||exited())){if(conversation.phase()!=="prompt"){forceKill();return}write(conversation.cancel()),later(graceMs,()=>{!settled&&!exited()&&forceKill()})}},liveDescendants:()=>process.platform==="win32"?null:exited()||child.pid===void 0?[]:liveUnderAgent(child.pid,agentNames,child.spawnargs.some(arg=>arg.endsWith("sandbox-launch.js")))})}catch{}let leftover=!1;child.on("exit",()=>{if(options.processGroup===!0&&container===null&&child.pid!==void 0&&process.platform!=="win32"){try{process.kill(-child.pid,0),leftover=!0}catch{leftover=!1}try{process.kill(-child.pid,"SIGKILL")}catch{}}later(ACP_PIPES_AFTER_EXIT_MS,()=>{if(!settled)for(const pipe of[child.stdout,child.stderr,child.stdin])try{pipe?.destroy()}catch{}})});const finish=(code,signal)=>{if(settled)return;framing.finish(),settled=!0;for(const timer of timers)clearTimeout(timer);watchdog.stop(),liveProviders.delete(child);const terminal=conversation.terminal(),exitCode=terminal!==null&&"stopReason"in terminal&&terminal.stopReason==="end_turn"&&conversation.failure()===null&&!timedOut&&(code===0||(termAfterTerminal&&(signal==="SIGTERM"||code===143)||killAfterTerminal&&(signal==="SIGKILL"||code===137)))?0:code??1;(container===null?Promise.resolve(null):settleContainer(container,options)).then(empty=>resolve({code:notFound?NOT_FOUND_CODE:timedOut?TIMEOUT_CODE:attach.failure!==null||empty===!1?CONTAINMENT_REFUSED_CODE:exitCode,stdout:`${conversation.retained()}${JSON.stringify({type:"acp.exit",how:endedBy,leftover:leftover||empty===!1,timedOut})}
|
|
10
11
|
`,stderr:empty===!1?`${stderr}
|
|
11
12
|
Native process containment could not prove all descendants exited.`.trim():attach.failure!==null&&stderr===""?attach.failure:stderr,timedOut,notFound,...containmentOf(container,empty,attach.failure)}))};child.on("error",error=>{endedBy="error",notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error)),finish(null,null)}),child.on("close",(code,signal)=>finish(code,signal))})}const TRUNCATION_MARKER="…[truncated]";function syntheticMessageLine(content,truncated){let body=content,marked=truncated;for(;;){const line=JSON.stringify(marked?{type:"synthetic_message",content:body+TRUNCATION_MARKER,truncated:!0}:{type:"synthetic_message",content:body}),over=Buffer.byteLength(line,"utf8")-JSONL_LINE_CAP;if(over<=0)return line;marked=!0;const cut=Math.max(1,over);body=body.slice(0,Math.max(0,body.length-cut))}}const LIVE_SUMMED_USAGE=["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"];export function cumulativeLiveResult(previous,latest){const count=value=>typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null,usageOf=event=>event.usage!==null&&typeof event.usage=="object"&&!Array.isArray(event.usage)?event.usage:null,before=usageOf(previous),now=usageOf(latest),usage={...now};for(const key of LIVE_SUMMED_USAGE){const a=before===null?null:count(before[key]),b=now===null?null:count(now[key]);(a!==null||b!==null)&&(usage[key]=(a??0)+(b??0))}const turnsBefore=count(previous.num_turns),turnsNow=count(latest.num_turns);return{...latest,...before===null&&now===null?{}:{usage},...turnsBefore===null&&turnsNow===null?{}:{num_turns:(turnsBefore??0)+(turnsNow??0)}}}export const STREAM_INPUT=Symbol.for("toolroll.streamInput"),streamsInput=runner=>typeof runner=="function"&&runner[STREAM_INPUT]===!0;export function runClaudeStreamJsonl(file,args,options={}){const childEnv=resolveChildEnv(options),live=options.liveInput??null;return new Promise(resolve=>{const started=startStream(file,args,options,[live===null?"ignore":"pipe","pipe","pipe"],childEnv,resolve);if(started===null)return;const{child,container,attach}=started;let initLine=null,initIdentityLine=null,conflictingInitLine=null,initModel=null,initModelLine=null,modelConflictLine=null,initSessionId=null,resultLine=null,resultOverflowed=!1,account=null,costUnknown=!1,overflowLine=null,receiptFired=!1,stderr="",timedOut=!1,notFound=!1;const fireReceipt=()=>{if(receiptFired||options.onReceipt===void 0){receiptFired=!0;return}receiptFired=!0;try{options.onReceipt()}catch{}},tally=(event,line)=>{const before=account;account=account===null||live===null?event:{...line===null?account:{},...cumulativeLiveResult(account,event)};const cost=event.total_cost_usd,readable=typeof cost=="number"&&Number.isFinite(cost)&&cost>=0,prior=before?.total_cost_usd;readable&&typeof prior=="number"&&prior>cost&&(account={...account,total_cost_usd:prior}),line===null?costUnknown=!readable:readable&&(costUnknown=!1),!resultOverflowed&&(line!==null&&account===event?resultLine=line:(line!==null||resultLine!==null)&&(resultLine=JSON.stringify(account)))},keep=framed=>{if(framed.overflowed){const type2=leadingJsonObjectType(framed.prefix);if(type2!==null&&type2!=="result"){if(type2!=="system")return;const subtype=leadingClaudeSystemSubtype(framed.prefix);if(subtype!==null&&subtype!=="init")return;overflowLine===null&&(overflowLine=claudeOverflowLine(framed));return}const scanned={primary:!0,account:{}};(live!==null||resultLine===null)&&tally(scanned.account,null),resultLine===null?(resultLine=claudeOverflowLine(framed),resultOverflowed=!0):overflowLine===null&&(overflowLine=claudeOverflowLine(framed)),live!==null&&scanned.primary&&live.close("settled");return}const line=framed.prefix.toString("utf8");let event;try{event=JSON.parse(line)}catch{return}if(event===null||typeof event!="object")return;const type=String(event.type??"");if(type==="system"&&String(event.subtype??"")==="init"&&topLevelEvent(event)){initLine===null&&(initLine=line);const model=typeof event.model=="string"?event.model:null;model!==null&&(initModel===null?(initModel=model,initModelLine=line):model!==initModel&&modelConflictLine===null&&(modelConflictLine=line));const id=transportSessionId(event.session_id);let identityWitness=!1;if(id!==null&&(initSessionId===null?(initSessionId=id,initIdentityLine=line,identityWitness=!0):id!==initSessionId&&conflictingInitLine===null&&(conflictingInitLine=line,identityWitness=!0),identityWitness&&options.onSessionId!==void 0))try{options.onSessionId(id)}catch{}}else type==="assistant"?topLevelEvent(event)&&fireReceipt():type==="rate_limit_event"?noteLimits(claudeLimitsOf(event)):type==="result"&&(resultLine===null||live!==null)&&primaryResultEvent(event)&&(tally(event,line),event.is_error!==!0&&String(event.subtype??"")==="success"&&fireReceipt());if(options.onStreamEvent!==void 0)try{options.onStreamEvent(event)}catch{}live!==null&&live.observe(event)},accountedResultLine=()=>{if(resultLine===null||!resultOverflowed&&!costUnknown)return resultLine;const kept=JSON.parse(resultLine),counted={};if(resultOverflowed&&account!==null)for(const key of["total_cost_usd","usage","num_turns"])account[key]!==void 0&&(counted[key]=account[key]);return JSON.stringify({...kept,...counted,...costUnknown?{[CLAUDE_COST_UNKNOWN]:!0}:{}})},framing=boundedJsonlFramer(JSONL_EVENT_HARD_CAP,keep,!1,CLAUDE_RESULT_TAIL_CAP),watchdog=streamWatchdog(options,()=>{timedOut=!0,options.processGroup===!0?killGroup(child):child.kill("SIGKILL")},live===null?void 0:()=>live.idleLimit());child.stdout?.on("data",chunk=>{watchdog.touch(),framing.push(chunk)}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{watchdog.touch(),stderr.length<JSONL_STDERR_CAP&&(stderr+=chunk.slice(0,JSONL_STDERR_CAP-stderr.length))});let settled=!1;const finish=code=>{if(settled)return;settled=!0,watchdog.stop(),liveProviders.delete(child),framing.finish(),live?.detach();const lines=[initLine,initIdentityLine,conflictingInitLine,initModelLine,modelConflictLine,accountedResultLine(),overflowLine].filter(one=>one!==null).filter((line,index,all)=>all.indexOf(line)===index);(container===null?Promise.resolve(null):settleContainer(container,options)).then(empty=>resolve({code:notFound?NOT_FOUND_CODE:timedOut?TIMEOUT_CODE:attach.failure!==null||empty===!1?CONTAINMENT_REFUSED_CODE:code??1,stdout:lines.join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toolroll",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.137",
|
|
4
4
|
"description": "Your agents build. You decide. A control plane for coding agents — Claude Code, Codex, Gemini: approve the exact scope once, get results back Ready with the diff, the passing check and screenshots. Runs on your machine.",
|
|
5
5
|
"directories": {
|
|
6
6
|
"doc": "docs"
|