toolroll 0.9.138 → 0.9.139
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 +11 -0
- package/dist/exec.js +11 -5
- package/dist/protected-storage.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,17 @@ 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.139 — 2026-12-06
|
|
8
|
+
|
|
9
|
+
Toolroll's worker never stalls behind a command that already finished.
|
|
10
|
+
|
|
11
|
+
**Fixed**
|
|
12
|
+
- Tasks could stop for hours with nothing running: a finished git command whose helper still held its output kept
|
|
13
|
+
the repository's checkout lock forever. Every command runner now closes held output 10 s after the command exits
|
|
14
|
+
(and says so in its result), and the check of other apps' data always settles.
|
|
15
|
+
- Faster CI for maintainers: Rust builds reuse caches, types are checked once per run, Playwright's browser is
|
|
16
|
+
cached.
|
|
17
|
+
|
|
7
18
|
## 0.9.138 — 2026-12-05
|
|
8
19
|
|
|
9
20
|
Reviews start the moment a build is saved.
|
package/dist/exec.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
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
|
-
|
|
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),drainPipesAfterExit(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,heldOutput=!1,settledRun=!1,seenOut="",seenErr="";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,rawStderr)=>{if(hardKill!==void 0&&clearTimeout(hardKill),settledRun)return;settledRun=!0;const stderr=heldOutput?`${rawStderr}
|
|
2
|
+
${PIPES_HELD_NOTE}`.trim():rawStderr;if(error===null){resolve({result:{code:0,stdout,stderr,timedOut:!1,notFound:!1,...heldOutput?{heldOutput:!0}:{}},transient:!1});return}resolve({result:{...describeFailure(error,stdout,stderr),...heldOutput?{heldOutput:!0}:{}},transient:isTransientSpawnFailure(error)})});drainPipesAfterExit(child,()=>{heldOutput=!0});const keep=into=>chunk=>{const text=String(chunk);into==="out"?seenOut.length<maxBuffer&&(seenOut+=text.slice(0,maxBuffer-seenOut.length)):seenErr.length<maxBuffer&&(seenErr+=text.slice(0,maxBuffer-seenErr.length))};child.stdout?.on("data",keep("out")),child.stderr?.on("data",keep("err")),timeoutMs>0&&(hardKill=setTimeout(()=>{try{child.kill("SIGKILL")}catch{}setTimeout(()=>{if(settledRun)return;settledRun=!0;const note=`the command didn't exit after it was killed (${TERM_GRACE_MS} ms grace)`;resolve({result:{code:TIMEOUT_CODE,stdout:seenOut,stderr:seenErr===""?note:`${seenErr}
|
|
3
|
+
${note}`,timedOut:!0,notFound:!1},transient:!1})},TERM_GRACE_MS).unref?.()},timeoutMs+TERM_GRACE_MS),hardKill.unref?.())}))}export const TERM_GRACE_MS=2e3,PIPES_AFTER_EXIT_MS=1e4,PIPES_HELD_NOTE="Toolroll closed this command's output 10 s after it exited: something it started was still holding it, so later output is missing.";export function drainPipesAfterExit(child,onForced=()=>{},ms=PIPES_AFTER_EXIT_MS){let timer,closed=!1;child.once("close",()=>{closed=!0,timer!==void 0&&clearTimeout(timer)}),child.once("exit",()=>{closed||timer!==void 0||(timer=setTimeout(()=>{if(!closed){try{onForced()}catch{}for(const pipe of[child.stdout,child.stderr,child.stdin])try{pipe?.destroy()}catch{}}},ms),timer.unref?.())})}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}
|
|
4
|
+
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)}),drainPipesAfterExit(child,()=>{stderr=`${stderr}
|
|
5
|
+
${PIPES_HELD_NOTE}`.trim()}),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
6
|
`),stderr:empty===!1?`${stderr}
|
|
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)),
|
|
7
|
+
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)),drainPipesAfterExit(child,()=>{stderr=`${stderr}
|
|
8
|
+
${PIPES_HELD_NOTE}`.trim()}),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
9
|
`),stderr:empty===!1?`${stderr}
|
|
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))
|
|
10
|
+
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)),drainPipesAfterExit(child,()=>{stderr=`${stderr}
|
|
11
|
+
${PIPES_HELD_NOTE}`.trim()})})}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
12
|
`).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
13
|
`);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
14
|
`);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}
|
|
@@ -11,4 +16,5 @@ Native process containment could not prove all descendants exited.`.trim():attac
|
|
|
11
16
|
`,stderr:empty===!1?`${stderr}
|
|
12
17
|
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(`
|
|
13
18
|
`),stderr:empty===!1?`${stderr}
|
|
14
|
-
Native process containment could not prove all descendants exited.`.trim():attach.failure!==null&&stderr===""?attach.failure:stderr,timedOut,notFound,...containmentOf(container,empty,attach.failure)}))};if(child.on("error",error=>{notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error)),finish(null)}),child.on("close",code=>finish(code)),
|
|
19
|
+
Native process containment could not prove all descendants exited.`.trim():attach.failure!==null&&stderr===""?attach.failure:stderr,timedOut,notFound,...containmentOf(container,empty,attach.failure)}))};if(child.on("error",error=>{notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error)),finish(null)}),child.on("close",code=>finish(code)),drainPipesAfterExit(child,()=>{stderr=`${stderr}
|
|
20
|
+
${PIPES_HELD_NOTE}`.trim()}),live!==null&&child.stdin!==null){const input=child.stdin;input.on("error",()=>live.detach("input-failed")),live.attach({write:line=>{input.write(line,"utf8")},end:()=>{input.end()}})}})}runClaudeStreamJsonl[STREAM_INPUT]=!0;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{spawn}from"node:child_process";import{closeSync,existsSync,fstatSync,lstatSync,openSync,constants as fsConstants,readSync,readdirSync,readlinkSync,realpathSync}from"node:fs";import{homedir}from"node:os";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{fileURLToPath}from"node:url";import{isLeadTokenEnvName,withoutLeadTokenEnv}from"./names.js";const AS="Library/Application Support",CONTAINERS="Library/Containers",GROUPS="Library/Group Containers";export const PROTECTED_STORAGE=[{app:"Slack",darwin:[`${AS}/Slack`,`${CONTAINERS}/com.tinyspeck.slackmacgap`],linux:[".config/Slack","snap/slack",".var/app/com.slack.Slack"]},{app:"Telegram",darwin:[`${AS}/Telegram Desktop`,`${CONTAINERS}/org.telegram.desktop`,`${GROUPS}/6N38VWS5BX.ru.keepcoder.Telegram`,`${CONTAINERS}/ru.keepcoder.Telegram`],linux:[".local/share/TelegramDesktop","snap/telegram-desktop",".var/app/org.telegram.desktop"]},{app:"Discord",darwin:[`${AS}/discord`,`${AS}/discordptb`,`${AS}/discordcanary`],linux:[".config/discord",".config/discordptb",".config/discordcanary","snap/discord",".var/app/com.discordapp.Discord"]},{app:"Teams",darwin:[`${CONTAINERS}/com.microsoft.teams2`,`${GROUPS}/UBF8T346G9.com.microsoft.teams`,`${AS}/Microsoft/Teams`,`${GROUPS}/UBF8T346G9.com.microsoft.oneauth`],linux:[".config/Microsoft/Microsoft Teams",".config/teams-for-linux"]},{app:"WhatsApp",darwin:[`${CONTAINERS}/net.whatsapp.WhatsApp`,`${GROUPS}/group.net.whatsapp.WhatsApp.shared`,`${GROUPS}/group.net.whatsapp.WhatsApp.private`,`${GROUPS}/group.net.whatsapp.family`],linux:[]},{app:"1Password",darwin:[`${GROUPS}/2BUA8C4S2C.com.1password`,`${GROUPS}/group.2BUA8C4S2C.com.1password`,`${GROUPS}/2BUA8C4S2C.com.agilebits`,`${CONTAINERS}/com.1password.1password`,`${CONTAINERS}/com.1password.1password-launcher`,`${CONTAINERS}/com.1password.browser-support`,`${CONTAINERS}/2BUA8C4S2C.com.1password.browser-helper`,`${CONTAINERS}/com.1password.1password.autofill-extension`,`${AS}/1Password`,".config/1Password",".config/op",".op"],linux:[".config/1Password","snap/1password",".var/app/com.onepassword.OnePassword",".config/op",".op"]},{app:"Bitwarden",darwin:[`${AS}/Bitwarden`,`${CONTAINERS}/com.bitwarden.desktop`,`${GROUPS}/LTZ2PFU5D6.com.bitwarden.desktop`,`${AS}/Bitwarden CLI`],linux:[".config/Bitwarden","snap/bitwarden",".var/app/com.bitwarden.desktop",".config/Bitwarden CLI"]},{app:"Chrome",darwin:[`${AS}/Google/Chrome`,`${AS}/Google/Chrome Beta`,`${AS}/Google/Chrome Canary`,`${AS}/Google/Chrome Dev`],linux:[".config/google-chrome",".config/google-chrome-beta",".config/google-chrome-unstable",".var/app/com.google.Chrome"]},{app:"Chromium",darwin:[`${AS}/Chromium`],linux:[".config/chromium","snap/chromium",".var/app/org.chromium.Chromium"]},{app:"Brave",darwin:[`${AS}/BraveSoftware`],linux:[".config/BraveSoftware","snap/brave",".var/app/com.brave.Browser"]},{app:"Edge",darwin:[`${AS}/Microsoft Edge`,`${AS}/Microsoft Edge Beta`,`${AS}/Microsoft Edge Dev`,`${AS}/Microsoft Edge Canary`],linux:[".config/microsoft-edge",".config/microsoft-edge-beta",".config/microsoft-edge-dev",".var/app/com.microsoft.Edge"]},{app:"Arc",darwin:[`${AS}/Arc`],linux:[]},{app:"Firefox",darwin:[`${AS}/Firefox`],linux:[".mozilla/firefox","snap/firefox",".var/app/org.mozilla.firefox"]},{app:"Zen",darwin:[`${AS}/zen`],linux:[".zen",".var/app/app.zen_browser.zen"]},{app:"Vivaldi",darwin:[`${AS}/Vivaldi`,`${AS}/Vivaldi Snapshot`],linux:[".config/vivaldi",".config/vivaldi-snapshot"]},{app:"Opera",darwin:[`${AS}/com.operasoftware.Opera`],linux:[".config/opera"]},{app:"Toolroll shared browser",darwin:[".local/share/toolroll/browser-profiles"],linux:[".local/share/toolroll/browser-profiles"]},{app:"Orion",darwin:[`${AS}/Orion`],linux:[]},{app:"Safari",darwin:["Library/Safari",`${CONTAINERS}/com.apple.Safari`,`${CONTAINERS}/com.apple.Safari.WebApp`,"Library/Cookies","Library/HTTPStorages","Library/WebKit"],linux:[]}];const PROFILE_INDEXES={darwin:[`${AS}/Firefox`,`${AS}/zen`],linux:[".mozilla/firefox","snap/firefox/common/.mozilla/firefox",".var/app/org.mozilla.firefox/.mozilla/firefox",".zen"]},PROTECTED_ENV_PREFIXES=["SLACK_","TELEGRAM_","DISCORD_","TEAMS_","OP_","BW_","BITWARDENCLI_"];export function isProtectedEnvName(name){if(isLeadTokenEnvName(name))return!0;const upper=name.toUpperCase();return PROTECTED_ENV_PREFIXES.some(prefix=>upper.startsWith(prefix))}export function withoutProtectedEnv(env){const out={...env};for(const name of Object.keys(out))isProtectedEnvName(name)&&delete out[name];return out}const PROTECTED_WALK={depth:4,entries:5e3},real=path=>{try{return realpathSync(path)}catch{return resolve(path)}},within=(child,parent)=>{const rel=relative(parent,child);return rel!==""&&!rel.startsWith("..")&&!isAbsolute(rel)},platformOf=platform=>platform==="darwin"?"darwin":platform==="linux"?"linux":null;function tooWide(path,home){return!isAbsolute(path)||path===dirname(path)||path===home||within(home,path)}export function protectedStorageNames(home=homedir(),env=process.env,platform=process.platform){const os=platformOf(platform);if(os===null)return[];const base=real(home),names=new Set,add=path=>{tooWide(path,base)||names.add(path)},relatives=PROTECTED_STORAGE.flatMap(row=>row[os]);for(const one of relatives)add(join(base,one));if(os==="linux"){const absolute=name=>{const value=env[name];return value!==void 0&&isAbsolute(value)?value:null},config=absolute("XDG_CONFIG_HOME"),data=absolute("XDG_DATA_HOME");for(const one of relatives)config!==null&&one.startsWith(".config/")&&add(join(config,one.slice(8))),data!==null&&one.startsWith(".local/share/")&&add(join(data,one.slice(13)))}for(const name of["OP_CONFIG_DIR","BITWARDENCLI_APPDATA_DIR"]){const value=env[name];value!==void 0&&isAbsolute(value)&&add(resolve(value))}for(const index of PROFILE_INDEXES[os])for(const profile of profilesElsewhere(join(base,index)))add(profile);return[...names].sort()}function profilesElsewhere(root){return(profilesIniHere(join(root,"profiles.ini"))??"").split(/\r?\n/).map(line=>/^\s*Path\s*=\s*(.+?)\s*$/i.exec(line)?.[1]??null).filter(path=>path!==null&&isAbsolute(path))}function profilesIniHere(file){try{lstatSync(file)}catch{return null}let fd;try{fd=openSync(file,fsConstants.O_RDONLY|(fsConstants.O_NOFOLLOW??0))}catch{return null}try{const held=fstatSync(fd);if(!held.isFile())return null;const buffer=Buffer.alloc(Math.min(held.size,64*1024));return buffer.subarray(0,readSync(fd,buffer,0,buffer.length,0)).toString("utf8")}catch{return null}finally{closeSync(fd)}}const unwalkedSaid=new Set;export function protectedStorageHere(home=homedir(),env=process.env,platform=process.platform,say=()=>{},list=path=>readdirSync(path,{withFileTypes:!0}),at=()=>{}){const base=real(home),names=protectedStorageNames(base,env,platform),out=new Set,add=path=>{tooWide(path,base)||out.add(path)},unfinished=[];for(const name of names){add(name);try{lstatSync(name)}catch{continue}const root=real(name);add(root),at(root);const walked={complete:!0};for(const target of outwardLinks(name,root,base,say,list,walked))add(target);!walked.complete&&!unfinished.includes(root)&&unfinished.push(root)}return{names,denies:[...out].sort(),unfinished}}export function protectedStorageDenies(home=homedir(),env=process.env,platform=process.platform,say,list){return protectedStorageHere(home,env,platform,say,list).denies}function outwardLinks(name,root,home,say,list,walked){const found=[];let seen=0;const queue=[{path:root,depth:0}];for(;queue.length>0;){const{path,depth}=queue.shift();let entries;try{entries=list(path)}catch(error){walked!==void 0&&!ANSWERED.has(error?.code??"")&&(walked.complete=!1);continue}for(const entry of entries){if(++seen>PROTECTED_WALK.entries)return unwalkedSaid.has(root)||(unwalkedSaid.add(root),say(`toolroll: fence: ${name} holds more than ${PROTECTED_WALK.entries.toLocaleString("en-US")} entries; links past that weren't checked (not fully walked)`)),found;const child=join(path,entry.name);if(entry.isSymbolicLink()){let spelled;try{spelled=resolve(dirname(child),readlinkSync(child))}catch{continue}if(systemMirror(child,root,spelled,home))continue;const target=real(spelled);if(target===root||within(target,root))continue;found.push(target),spelled!==target&&found.push(spelled)}else entry.isDirectory()&&depth+1<PROTECTED_WALK.depth&&queue.push({path:child,depth:depth+1})}}return found}const CONTAINER_MIRRORS=new Set([".CFUserTextEncoding","Desktop","Downloads","Movies","Music","Pictures",...["Audio","Calendars","ColorPickers","ColorSync","Colors","Components","Compositions","Dictionaries","Favorites","Filters","FontCollections","Fonts","Input Methods","KeyBindings","Keyboard Layouts","Keychains","Mail","PDF Services","QuickLook","Sounds","Spelling","Images/People","Application Support/AddressBook","Application Support/iCloud","Application Support/SyncServices","Preferences/com.apple.security.plist","Preferences/com.apple.security_common.plist"].map(one=>`Library/${one}`)]);function systemMirror(link,root,target,home){const app=dirname(root)===real(join(home,CONTAINERS)),group=dirname(root)===real(join(home,GROUPS));if(!app&&!group)return!1;const rel=relative(root,link).split(sep);if(app&&rel[0]!=="Data")return!1;const under=app?rel.slice(1):rel,named=under.join("/");return(CONTAINER_MIRRORS.has(named)||named===`Library/Application Scripts/${root.split(sep).at(-1)}`)&&target===join(home,...under)}const ANSWERED=new Set(["ENOENT","ENOTDIR","EPERM","EACCES"]),STORAGE_LOOK_MS=1e4,LOOK_OUTPUT_MAX=8*1024*1024,STORAGE_ENV=["XDG_CONFIG_HOME","XDG_DATA_HOME","OP_CONFIG_DIR","BITWARDENCLI_APPDATA_DIR"];export class ProtectedStorageRefusal extends Error{apps;why;code="protected-storage";constructor(apps,why,message){super(message),this.apps=apps,this.why=why,this.name="ProtectedStorageRefusal"}}export function storageRefusalOf(error){return error instanceof ProtectedStorageRefusal?error:null}function appsOf(roots,home){const names=roots.map(root=>PROTECTED_STORAGE.find(row=>[...row.darwin,...row.linux].some(one=>real(join(home,one))===root||join(home,one)===root))?.app??basename(root));return[...new Set(names)]}export function storageAccessHolder(env=process.env,execPath=process.execPath,versions=process.versions){if(versions.electron!==void 0)return"the Toolroll app";const service=env.XPC_SERVICE_NAME;if(service!==void 0&&service!==""&&service!=="0")return`the program that keeps Toolroll running (${execPath})`;const terminal=env.TERM_PROGRAM;return terminal!==void 0&&terminal!==""?`the terminal app Toolroll was started from (${terminal.replace(/\.app$/,"")})`:`the program Toolroll runs as (${execPath})`}export function storageRefusalWords(apps,why,holder){const named=apps.length===0?"other apps":apps.length===1?apps[0]:`${apps.slice(0,-1).join(", ")} and ${apps.at(-1)}`,reason=why==="timed-out"?` (the check didn't finish within ${STORAGE_LOOK_MS/1e3} seconds)`:why==="unfinished"?" (some of its folders couldn't be read)":" (the check stopped with an error)";return`Nothing was started: Toolroll couldn't finish checking ${apps.length===0?"other apps'":`${named}'s`} data for links to keep out of the build${reason}. macOS may need to let ${holder} read it: in System Settings → Privacy & Security → Full Disk Access, turn it on for ${holder}, then try again.`}const inFlight=new Map;export async function prepareProtectedStorage(home=homedir(),env=process.env,platform=process.platform,look=lookInChild,holder=storageAccessHolder(env)){const base=real(home),request={home:base,env:Object.fromEntries(STORAGE_ENV.flatMap(name=>env[name]===void 0?[]:[[name,env[name]]])),platform};let answer;if(platform!=="darwin"){const here=protectedStorageHere(base,env,platform,line=>process.stderr.write(`${line}
|
|
2
2
|
`));answer={kind:"done",storage:{names:here.names,denies:here.denies},unfinished:here.unfinished}}else{const key=JSON.stringify(request);let pending=inFlight.get(key);pending===void 0&&(pending=look(request).finally(()=>inFlight.delete(key)),inFlight.set(key,pending)),answer=await pending}if(answer.kind==="timed-out"){const apps=answer.at===null?[]:appsOf([answer.at],base);throw new ProtectedStorageRefusal(apps,"timed-out",storageRefusalWords(apps,"timed-out",holder))}if(answer.kind==="failed")throw new ProtectedStorageRefusal([],"failed",storageRefusalWords([],"failed",holder));if(answer.unfinished.length>0){const apps=appsOf(answer.unfinished,base);throw new ProtectedStorageRefusal(apps,"unfinished",storageRefusalWords(apps,"unfinished",holder))}return answer.storage}export function storageLookScript(){const beside=fileURLToPath(new URL("./protected-storage-look.js",import.meta.url));return existsSync(beside)?beside:fileURLToPath(new URL("../dist/protected-storage-look.js",import.meta.url))}async function lookInChild(request){return readLook(await spawnLook(process.execPath,[storageLookScript(),JSON.stringify(request)],STORAGE_LOOK_MS))}export function readLook(ran){const lines=ran.stdout.split(`
|
|
3
|
-
`),last=[...lines].reverse().find(line=>line.startsWith("at ")),at=last===void 0?null:(()=>{try{const root=JSON.parse(last.slice(3));return typeof root=="string"&&isAbsolute(root)?root:null}catch{return null}})();if(ran.outcome==="timed-out")return{kind:"timed-out",at};if(ran.outcome==="failed")return{kind:"failed",detail:ran.detail};const done=lines.find(line=>line.startsWith("done "));if(done===void 0)return{kind:"failed",detail:"the check gave no answer"};try{const value=JSON.parse(done.slice(5)),paths=one=>Array.isArray(one)&&one.every(path=>typeof path=="string"&&isAbsolute(path))?one:null,names=paths(value.names),denies=paths(value.denies),unfinished=paths(value.unfinished);return names===null||denies===null||unfinished===null?{kind:"failed",detail:"the check's answer can't be read"}:{kind:"done",storage:{names,denies},unfinished}}catch{return{kind:"failed",detail:"the check's answer can't be read"}}}export function spawnLook(command,args,limitMs){return new Promise(settle=>{let stdout="",over=!1,timedOut=!1,settled=!1;const finish=(outcome,detail)=>{settled||(settled=!0,clearTimeout(timer),settle({stdout,outcome,detail}))};let child;try{child=spawn(command,[...args],{stdio:["ignore","pipe","ignore"],env:withoutLeadTokenEnv({...process.env,ELECTRON_RUN_AS_NODE:"1"})})}catch(error){settle({stdout:"",outcome:"failed",detail:error instanceof Error?error.message:String(error)});return}const timer=setTimeout(()=>{timedOut=!0,
|
|
3
|
+
`),last=[...lines].reverse().find(line=>line.startsWith("at ")),at=last===void 0?null:(()=>{try{const root=JSON.parse(last.slice(3));return typeof root=="string"&&isAbsolute(root)?root:null}catch{return null}})();if(ran.outcome==="timed-out")return{kind:"timed-out",at};if(ran.outcome==="failed")return{kind:"failed",detail:ran.detail};const done=lines.find(line=>line.startsWith("done "));if(done===void 0)return{kind:"failed",detail:"the check gave no answer"};try{const value=JSON.parse(done.slice(5)),paths=one=>Array.isArray(one)&&one.every(path=>typeof path=="string"&&isAbsolute(path))?one:null,names=paths(value.names),denies=paths(value.denies),unfinished=paths(value.unfinished);return names===null||denies===null||unfinished===null?{kind:"failed",detail:"the check's answer can't be read"}:{kind:"done",storage:{names,denies},unfinished}}catch{return{kind:"failed",detail:"the check's answer can't be read"}}}export function spawnLook(command,args,limitMs){return new Promise(settle=>{let stdout="",over=!1,timedOut=!1,settled=!1,backstop;const finish=(outcome,detail)=>{settled||(settled=!0,clearTimeout(timer),backstop!==void 0&&clearTimeout(backstop),settle({stdout,outcome,detail}))};let child;try{child=spawn(command,[...args],{stdio:["ignore","pipe","ignore"],env:withoutLeadTokenEnv({...process.env,ELECTRON_RUN_AS_NODE:"1"})})}catch(error){settle({stdout:"",outcome:"failed",detail:error instanceof Error?error.message:String(error)});return}const killAndSettle=(outcome,detail)=>{try{child.kill("SIGKILL")}catch{}backstop===void 0&&(backstop=setTimeout(()=>{try{child.stdout?.destroy()}catch{}finish(outcome,detail)},2e3),backstop.unref?.())},timer=setTimeout(()=>{timedOut=!0,killAndSettle("timed-out","")},limitMs);child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout.length+chunk.length>LOOK_OUTPUT_MAX?(over=!0,killAndSettle("failed","the check said too much")):stdout+=chunk}),child.on("error",error=>finish("failed",error.message)),child.on("close",(code,signal)=>{timedOut?finish("timed-out",""):over?finish("failed","the check said too much"):code===0&&signal===null?finish("done",""):finish("failed",signal===null?`the check exited with ${code}`:`the check was stopped (${signal})`)})})}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toolroll",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.139",
|
|
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"
|