toolroll 0.9.139 → 0.9.141

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/dist/exec.js CHANGED
@@ -1,6 +1,6 @@
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}
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{drainPipesAfterExit,PIPES_HELD_NOTE}from"./pipes-after-exit.js";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
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}
3
+ ${note}`,timedOut:!0,notFound:!1},transient:!1})},TERM_GRACE_MS).unref?.()},timeoutMs+TERM_GRACE_MS),hardKill.unref?.())}))}export const TERM_GRACE_MS=2e3;export{drainPipesAfterExit,PIPES_AFTER_EXIT_MS,PIPES_HELD_NOTE}from"./pipes-after-exit.js";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
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
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(`
6
6
  `),stderr:empty===!1?`${stderr}
@@ -1,4 +1,4 @@
1
- import{inReadOnlyRequest}from"./read-only-request.js";import{spawn}from"node:child_process";import{createHash}from"node:crypto";import{lstat,readFile,realpath,stat}from"node:fs/promises";import{createRequire}from"node:module";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{isProtectedWork}from"./approval-policy.js";import{dollarWords as dollars,scheduleWords,unattendedBudgetOf,unattendedRunsOf,UNATTENDED_RULE_WORDS,unattendedCoverWords,unattendedEndWords,unattendedHeadWords,unattendedLimitWords,untilWords}from"./flow-unattended-words.js";import{MODE_MAX_DAYS}from"./modes.js";import{accountReachesSql}from"./project-access.js";import{canonicalJson}from"./canonical-json.js";import{withoutLeadTokenEnv}from"./names.js";export const FLOW_ACCEPTANCE={report:[{id:"c1",statement:"The report answers the request, citing where in the repository each point comes from",how:null,evidence:["manual-review"]}],task:[{id:"c1",statement:"The requested change is made and the project's existing checks still pass",how:null,evidence:["manual-review"]}]};export{UNATTENDED_MAX_RUNS}from"./flow-unattended-words.js";export const unattendedTermsJson=terms=>canonicalJson(terms);export function unattendedDigestOf(terms){return createHash("sha256").update(`standing-orders:flow-unattended:${unattendedTermsJson(terms)}`,"utf8").digest("hex").slice(0,32)}function criteria(value){if(!Array.isArray(value)||value.length===0)return null;const out=[];for(const one of value){if(one===null||typeof one!="object")return null;const c=one;if(typeof c.id!="string"||typeof c.statement!="string"||c.statement.trim()===""||!(c.how===null||typeof c.how=="string")||!Array.isArray(c.evidence)||!c.evidence.every(e=>typeof e=="string"))return null;out.push({id:c.id,statement:c.statement,how:c.how,evidence:[...c.evidence]})}return out}const hex32=v=>typeof v=="string"&&/^[0-9a-f]{32}$/.test(v);function signedScript(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const s=value,file=s.file;if(s.provenance!==2||typeof s.name!="string"||s.name===""||!(typeof s.version=="number"&&Number.isSafeInteger(s.version)&&s.version>0)||!hex32(s.digest)||!(file===null||typeof file=="string"&&file!=="")||!Array.isArray(s.files))return null;const files=[];for(const one of s.files){if(one===null||typeof one!="object"||Array.isArray(one))return null;const f=one;if(typeof f.path!="string"||f.path===""||!hex32(f.digest)||files.length>0&&files.at(-1).path>=f.path)return null;files.push({path:f.path,digest:f.digest})}return(file===null?files.length>0:!files.some(one=>one.path===file))?null:{provenance:2,name:s.name,version:s.version,digest:s.digest,file,files}}function coveredTriggers(value){if(!Array.isArray(value)||value.length===0)return null;const out=[];for(const one of value){if(one===null||typeof one!="object")return null;const t=one;if(!(typeof t.id=="number"&&Number.isSafeInteger(t.id)&&t.id>0)||!(t.kind==="schedule"||t.kind==="script"||t.kind==="plane-review")||!hex32(t.digest)||typeof t.words!="string")return null;if(t.kind!=="script"){if(t.script!==void 0)return null;out.push({id:t.id,kind:t.kind,digest:t.digest,words:t.words});continue}const script=signedScript(t.script);if(script===null)return null;out.push({id:t.id,kind:"script",digest:t.digest,words:t.words,script})}return out}function unattendedTermsFromJson(json){if(json===null)return null;let t;try{const parsed=JSON.parse(json);if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))return null;t=parsed}catch{return null}const int=v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>0,acceptance=t.acceptance,report=acceptance!=null&&typeof acceptance=="object"?criteria(acceptance.report):null,task=acceptance!=null&&typeof acceptance=="object"?criteria(acceptance.task):null,budget=t.perAttemptBudgetMicrousd,cap=t.dailyRunCap,triggers=coveredTriggers(t.triggers);return!int(t.flow)||!(typeof t.flowRevision=="number"&&Number.isSafeInteger(t.flowRevision))||typeof t.repo!="string"||typeof t.owner!="string"||triggers===null||t.permissions!=="safe"||report===null||task===null||!(budget===null||int(budget))||!(cap===null||int(cap))||typeof t.absoluteExpiry!="string"||Number.isNaN(Date.parse(t.absoluteExpiry))?null:{flow:t.flow,flowRevision:t.flowRevision,repo:t.repo,owner:t.owner,triggers,permissions:"safe",acceptance:{report,task},perAttemptBudgetMicrousd:budget,dailyRunCap:cap,absoluteExpiry:t.absoluteExpiry}}export{untilWords};export function unattendedWords(terms){return[...unattendedHeadWords(terms.owner,terms.acceptance),unattendedCoverWords(terms.triggers),...unattendedLimitWords(terms.perAttemptBudgetMicrousd,terms.dailyRunCap),...UNATTENDED_RULE_WORDS,unattendedEndWords(terms.absoluteExpiry)]}const unprotectedSql=repos=>`NOT EXISTS (SELECT 1 FROM approval_policy ug_rules WHERE ug_rules.repo IN (${repos})
1
+ import{inReadOnlyRequest}from"./read-only-request.js";import{spawn}from"node:child_process";import{createHash}from"node:crypto";import{lstat,readFile,realpath,stat}from"node:fs/promises";import{createRequire}from"node:module";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{isProtectedWork}from"./approval-policy.js";import{dollarWords as dollars,scheduleWords,unattendedBudgetOf,unattendedRunsOf,UNATTENDED_RULE_WORDS,unattendedCoverWords,unattendedEndWords,unattendedHeadWords,unattendedLimitWords,untilWords}from"./flow-unattended-words.js";import{MODE_MAX_DAYS}from"./modes.js";import{accountReachesSql}from"./project-access.js";import{canonicalJson}from"./canonical-json.js";import{withoutLeadTokenEnv}from"./names.js";import{drainPipesAfterExit}from"./pipes-after-exit.js";export const FLOW_ACCEPTANCE={report:[{id:"c1",statement:"The report answers the request, citing where in the repository each point comes from",how:null,evidence:["manual-review"]}],task:[{id:"c1",statement:"The requested change is made and the project's existing checks still pass",how:null,evidence:["manual-review"]}]};export{UNATTENDED_MAX_RUNS}from"./flow-unattended-words.js";export const unattendedTermsJson=terms=>canonicalJson(terms);export function unattendedDigestOf(terms){return createHash("sha256").update(`standing-orders:flow-unattended:${unattendedTermsJson(terms)}`,"utf8").digest("hex").slice(0,32)}function criteria(value){if(!Array.isArray(value)||value.length===0)return null;const out=[];for(const one of value){if(one===null||typeof one!="object")return null;const c=one;if(typeof c.id!="string"||typeof c.statement!="string"||c.statement.trim()===""||!(c.how===null||typeof c.how=="string")||!Array.isArray(c.evidence)||!c.evidence.every(e=>typeof e=="string"))return null;out.push({id:c.id,statement:c.statement,how:c.how,evidence:[...c.evidence]})}return out}const hex32=v=>typeof v=="string"&&/^[0-9a-f]{32}$/.test(v);function signedScript(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const s=value,file=s.file;if(s.provenance!==2||typeof s.name!="string"||s.name===""||!(typeof s.version=="number"&&Number.isSafeInteger(s.version)&&s.version>0)||!hex32(s.digest)||!(file===null||typeof file=="string"&&file!=="")||!Array.isArray(s.files))return null;const files=[];for(const one of s.files){if(one===null||typeof one!="object"||Array.isArray(one))return null;const f=one;if(typeof f.path!="string"||f.path===""||!hex32(f.digest)||files.length>0&&files.at(-1).path>=f.path)return null;files.push({path:f.path,digest:f.digest})}return(file===null?files.length>0:!files.some(one=>one.path===file))?null:{provenance:2,name:s.name,version:s.version,digest:s.digest,file,files}}function coveredTriggers(value){if(!Array.isArray(value)||value.length===0)return null;const out=[];for(const one of value){if(one===null||typeof one!="object")return null;const t=one;if(!(typeof t.id=="number"&&Number.isSafeInteger(t.id)&&t.id>0)||!(t.kind==="schedule"||t.kind==="script"||t.kind==="plane-review")||!hex32(t.digest)||typeof t.words!="string")return null;if(t.kind!=="script"){if(t.script!==void 0)return null;out.push({id:t.id,kind:t.kind,digest:t.digest,words:t.words});continue}const script=signedScript(t.script);if(script===null)return null;out.push({id:t.id,kind:"script",digest:t.digest,words:t.words,script})}return out}function unattendedTermsFromJson(json){if(json===null)return null;let t;try{const parsed=JSON.parse(json);if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))return null;t=parsed}catch{return null}const int=v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>0,acceptance=t.acceptance,report=acceptance!=null&&typeof acceptance=="object"?criteria(acceptance.report):null,task=acceptance!=null&&typeof acceptance=="object"?criteria(acceptance.task):null,budget=t.perAttemptBudgetMicrousd,cap=t.dailyRunCap,triggers=coveredTriggers(t.triggers);return!int(t.flow)||!(typeof t.flowRevision=="number"&&Number.isSafeInteger(t.flowRevision))||typeof t.repo!="string"||typeof t.owner!="string"||triggers===null||t.permissions!=="safe"||report===null||task===null||!(budget===null||int(budget))||!(cap===null||int(cap))||typeof t.absoluteExpiry!="string"||Number.isNaN(Date.parse(t.absoluteExpiry))?null:{flow:t.flow,flowRevision:t.flowRevision,repo:t.repo,owner:t.owner,triggers,permissions:"safe",acceptance:{report,task},perAttemptBudgetMicrousd:budget,dailyRunCap:cap,absoluteExpiry:t.absoluteExpiry}}export{untilWords};export function unattendedWords(terms){return[...unattendedHeadWords(terms.owner,terms.acceptance),unattendedCoverWords(terms.triggers),...unattendedLimitWords(terms.perAttemptBudgetMicrousd,terms.dailyRunCap),...UNATTENDED_RULE_WORDS,unattendedEndWords(terms.absoluteExpiry)]}const unprotectedSql=repos=>`NOT EXISTS (SELECT 1 FROM approval_policy ug_rules WHERE ug_rules.repo IN (${repos})
2
2
  AND (ug_rules.protect_project = 1 OR NOT json_valid(ug_rules.protected_paths) OR json_array_length(ug_rules.protected_paths) > 0))`;export const grantStandsSql=(digest,now,repo)=>`EXISTS (SELECT 1 FROM flow_unattended_grant ug
3
3
  JOIN approver ug_signer ON ug_signer.name = ug.signed_by
4
4
  JOIN flow ug_flow ON ug_flow.id = ug.flow
@@ -14,7 +14,7 @@ const tried = f => { try { return f(); } catch { return null; } };
14
14
  const named = to => isBuiltin(to) ? "builtin" : to.startsWith("file:") ? fileURLToPath(to) : to.startsWith("/") ? to : null;
15
15
  process.stdout.write(JSON.stringify(JSON.parse(readFileSync(0, "utf8")).map(([spec, from]) => ({
16
16
  esm: tried(() => named(import.meta.resolve(spec, pathToFileURL(from).href))),
17
- cjs: tried(() => named(createRequire(from).resolve(spec))) }))));`;async function resolveAsNode(pairs){return new Promise(resolve2=>{const child=spawn(process.execPath,["--preserve-symlinks","--experimental-import-meta-resolve","--no-warnings","--input-type=module","-e",NODE_RESOLVER],{stdio:["pipe","pipe","ignore"],env:withoutLeadTokenEnv(process.env)});let output="";child.stdout.setEncoding("utf8"),child.stdout.on("data",part=>{output+=part,output.length>16*1024*1024&&child.kill()}),child.on("error",()=>resolve2(null)),child.stdin.on("error",()=>{}),child.on("close",code=>{if(code!==0)return resolve2(null);try{const parsed=JSON.parse(output);resolve2(Array.isArray(parsed)&&parsed.length===pairs.length?parsed:null)}catch{resolve2(null)}}),child.stdin.end(JSON.stringify(pairs))})}const graphCache=new Map,fileIdentity=value=>[value.dev,value.ino,value.size,value.mtimeNs,value.ctimeNs].join(":");async function pathIdentity(path){try{return fileIdentity(await lstat(path,{bigint:!0}))}catch{return"missing"}}const graphNodes=new Map;function lastScript(store,repo,name){const row=store.flowScript(repo,name);if(row===null||row.held!==null)return null;if(row.file===null)return{provenance:2,name,version:row.version,digest:row.digest,file:null,files:[]};const raw=store.handle.prepare("SELECT snapshot FROM flow_script_provenance WHERE repo = ? AND name = ?").get(repo,name)?.snapshot;try{const saved=typeof raw=="string"?signedScript(JSON.parse(raw)):null;return saved?.version===row.version&&saved.digest===row.digest?saved:null}catch{return null}}const inside=(base,full)=>{const path=relative(base,full);return path!==""&&path!==".."&&!path.startsWith("../")&&!isAbsolute(path)?path:null};async function nodeModuleGraphOf(base,entry,fresh){const cached=graphCache.get(entry);if(!fresh&&cached&&(await Promise.all([...cached.watched].map(async([path,identity])=>await pathIdentity(path)===identity))).every(Boolean))return cached.files;const watched=new Map,watch=async path=>{watched.has(path)||watched.set(path,await pathIdentity(path))},watchResolution=async file=>{await watch(file);for(let folder=dirname(file);folder===base||inside(base,folder)!==null;folder=dirname(folder))await watch(folder),await watch(join(folder,"package.json")),await watch(join(folder,"node_modules"))},pinned=new Map;for(let layer=[entry];layer.length>0;){const pairs=[];for(const file of layer){await watchResolution(file);const metadata=await stat(file,{bigint:!0}),identity=fileIdentity(metadata);let node=graphNodes.get(file);if(fresh||node?.identity!==identity){const bytes=await readFile(file),imports=SOURCE_FILE.test(file)?typescript().preProcessFile(bytes.toString("utf8"),!0,!0).importedFiles.map(one=>one.fileName):[];if(SOURCE_FILE.test(file)){const source=typescript().createSourceFile(file,bytes.toString("utf8"),typescript().ScriptTarget.Latest,!0),visit=child=>{if(typescript().isCallExpression(child)&&typescript().isCallExpression(child.expression)&&/(?:^|\.)createRequire$/.test(child.expression.expression.getText(source))){const arg=child.arguments[0];arg&&typescript().isStringLiteralLike(arg)&&imports.push(arg.text)}typescript().forEachChild(child,visit)};visit(source)}node={identity,digest:bytesDigest(bytes),imports},graphNodes.delete(file),graphNodes.set(file,node),graphNodes.size>MAX_SCRIPT_FILES&&graphNodes.delete(graphNodes.keys().next().value)}pinned.set(file,node.digest);for(const spec of node.imports)pairs.push([spec,file])}if(pinned.size>MAX_SCRIPT_FILES)return null;const answers=pairs.length===0?[]:await resolveAsNode(pairs);if(answers===null)return null;const next=new Set;for(const[index,{esm,cjs}]of answers.entries()){const[spec,from]=pairs[index];if(spec.startsWith(".")){const lexical=resolve(dirname(from),spec);await watchResolution(lexical);try{if(inside(base,lexical)!==null&&inside(base,await realpath(lexical))===null)return null}catch{}}let found=!1;for(const one of new Set([esm,cjs])){if(one==="builtin"){found=!0;continue}if(one===null)continue;await watchResolution(one);let full;try{if(!(await stat(one)).isFile())continue;full=await realpath(one)}catch{continue}if(found=!0,inside(base,full)===null){if(inside(base,one)!==null)return null;continue}pinned.has(full)||next.add(full)}if(!found)return null}layer=[...next]}const files=[...pinned].map(([full,digest])=>({path:inside(base,full),digest})).sort((a,b)=>a.path<b.path?-1:1);return(await Promise.all([...watched].map(async([path,identity])=>await pathIdentity(path)===identity))).every(Boolean)?(graphCache.delete(entry),graphCache.set(entry,{files,watched}),graphCache.size>32&&graphCache.delete(graphCache.keys().next().value),files):null}export async function scriptProvenanceOf(store,repo,name,fresh=!0){const script=store.flowScript(repo,name);let result=null;try{if(script!==null&&script.held===null){if(script.file===null)result={provenance:2,name,version:script.version,digest:script.digest,file:null,files:[]};else if(!isAbsolute(script.file)&&!script.file.split(/[\\/]/).includes("..")){const base=await realpath(repo),lexical=join(base,script.file),full=await realpath(lexical);if(!(await lstat(lexical)).isSymbolicLink()&&full===lexical&&inside(base,full)!==null&&(await stat(full)).isFile()){const files=script.language==="node"?await nodeModuleGraphOf(base,full,fresh):[{path:script.file,digest:bytesDigest(await readFile(full))}];files!==null&&(result={provenance:2,name,version:script.version,digest:script.digest,file:script.file,files})}}}}catch{result=null}return store.handle.prepare("INSERT INTO flow_script_provenance (repo, name, snapshot) VALUES (?, ?, ?) ON CONFLICT(repo, name) DO UPDATE SET snapshot = excluded.snapshot").run(repo,name,result===null?null:JSON.stringify(result)),result}export async function prepareUnattendedCandidates(store,flowId){const flow=store.getFlow(flowId);if(flow!==null){for(const trigger of store.flowTriggers(flowId))if(!(trigger.kind!=="schedule"||trigger.state!=="active"))try{const config=JSON.parse(trigger.configJson);typeof config.script=="string"&&await scriptProvenanceOf(store,flow.repo,config.script,!1)}catch{}}}export function scriptRanDigestOf(before,after,ran){return before===null||after===null||canonicalJson(before)!==canonicalJson(after)||before.version!==ran.version||before.digest!==ran.digest?null:ranDigestOf(before)}const ranDigestOf=script=>createHash("sha256").update(`standing-orders:flow-unattended-script-ran:${canonicalJson(script)}`,"utf8").digest("hex").slice(0,32);export function grantSignsScriptOf(store,flowId,triggerId,now){const trigger=store.getFlowTrigger(triggerId),flow=store.getFlow(flowId),grant=activeUnattendedGrant(store,flowId,now);return trigger!==null&&trigger.state==="active"&&flow!==null&&grant!==null&&flow.revision===grant.terms.flowRevision&&coverageProblem(store,flow,grant.signedBy,[flow.repo])===null&&grant.terms.triggers.some(one=>one.id===triggerId&&one.kind==="script"&&one.digest===triggerDigestOf(trigger))}function scriptsUnchanged(store,terms){return terms.triggers.every(one=>one.kind!=="script"||one.script!==void 0&&canonicalJson(lastScript(store,terms.repo,one.script.name))===canonicalJson(one.script))}function endIfScriptsChanged(store,grant,now){return scriptsUnchanged(store,grant.terms)?!1:(store.transact(()=>{const row=store.handle.prepare("SELECT * FROM flow_unattended_grant WHERE id = ? AND revoked_at IS NULL").get(grant.id);row!==void 0&&closeGrant(store,row,"flow","script changed",now)}),!0)}export function unattendedCandidates(store,flowId){const out=[],flowRepo=store.getFlow(flowId)?.repo;if(flowRepo===void 0)return out;for(const trigger of store.flowTriggers(flowId)){if(trigger.kind!=="schedule"||trigger.state!=="active")continue;const digest=triggerDigestOf(trigger);let config;try{config=JSON.parse(trigger.configJson)}catch{continue}if(digest===null||config===null||typeof config!="object"||typeof config.schedule!="string"||config.order!==void 0)continue;const when=scheduleWords(config.schedule);if(config.kind==="plane-review")out.push({id:trigger.id,kind:"plane-review",digest,words:`Plane review, ${when}`,optional:"Its cards come from what the plane saw."});else{if(config.kind!=="schedule")continue;if(typeof config.script=="string"){const script=lastScript(store,flowRepo,config.script);script!==null&&out.push({id:trigger.id,kind:"script",digest,words:`the ${config.script} script, ${when}`,script,optional:"Its cards come from what the script prints, which can be outside text, and wait for you unless it ran the code you signed. Files it loads by a computed name aren't checked."})}else typeof config.title=="string"&&out.push({id:trigger.id,kind:"schedule",digest,words:`“${config.title}”, ${when}`,optional:null})}}return out}function unreadableScriptSchedules(store,flowId){const offered=new Set(unattendedCandidates(store,flowId).map(one=>one.id));return store.flowTriggers(flowId).filter(one=>{if(one.kind!=="schedule"||one.state!=="active"||offered.has(one.id))return!1;try{return typeof JSON.parse(one.configJson).script=="string"}catch{return!1}}).map(one=>one.id)}const UNREADABLE_SCRIPT="can't be read safely (it's missing, waiting for approval, or a project file it runs or imports can't be read)";export const candidatesDigestOf=candidates=>createHash("sha256").update(`standing-orders:flow-unattended-candidates:${canonicalJson(candidates)}`,"utf8").digest("hex").slice(0,32);export function unattendedSignProblem(store,flow,signer){return unattendedCandidates(store,flow.id).length===0?unreadableScriptSchedules(store,flow.id).length>0?`This flow's script ${UNREADABLE_SCRIPT}, so nothing would run on its own.`:"This flow has no schedule, so nothing would run on its own.":coverageProblem(store,flow,signer,workReposOf(flow))}export function parseUnattendedAsk(input){const text=v=>typeof v=="string"?v.trim():typeof v=="number"?String(v):"",days=Number(text(input.days));if(!Number.isInteger(days)||days<1||days>MODE_MAX_DAYS)return{ok:!1,message:`Choose 1 to ${MODE_MAX_DAYS} days: it always ends.`};const budget=unattendedBudgetOf(text(input.budget));if(!budget.ok)return budget;const runs=unattendedRunsOf(text(input.runs));if(!runs.ok)return runs;const budgetMicrousd=budget.value,dailyRunCap=runs.value,includeText=Array.isArray(input.include)?input.include.map(text).join(","):text(input.include),include=includeText===""?[]:includeText.split(/[\s,]+/).filter(one=>one!=="").map(Number);return include.some(id=>!Number.isSafeInteger(id)||id<1)?{ok:!1,message:"Name the schedules to include by their trigger ids, like 12,14."}:{ok:!0,ask:{days,budgetMicrousd,dailyRunCap,...include.length===0?{}:{include:[...new Set(include)]}}}}function unattendedTermsFor(flow,owner,ask,triggers,now){return{flow:flow.id,flowRevision:flow.revision,repo:flow.repo,owner,triggers:triggers.map(({id,kind,digest,words,script})=>({id,kind,digest,words,...kind==="script"&&script!==void 0?{script:structuredClone(script)}:{}})),permissions:"safe",acceptance:structuredClone(FLOW_ACCEPTANCE),perAttemptBudgetMicrousd:ask.budgetMicrousd,dailyRunCap:ask.dailyRunCap,absoluteExpiry:new Date(now.getTime()+ask.days*24*60*6e4).toISOString()}}export async function signUnattended(store,input,now){const revision=store.getFlow(input.flow)?.revision,schedules=canonicalJson(store.flowTriggers(input.flow));await prepareUnattendedCandidates(store,input.flow);const prepared=candidatesDigestOf(unattendedCandidates(store,input.flow));return sealUnattended(store,input,now,{revision,schedules,prepared})}export function sealUnattended(store,input,now,before){return store.transact(()=>{const flow=store.getFlow(input.flow);if(flow===null)return{ok:!1,message:"No such flow."};if(before!==void 0&&(before.revision!==flow.revision||before.schedules!==canonicalJson(store.flowTriggers(input.flow))||before.prepared!==candidatesDigestOf(unattendedCandidates(store,input.flow))))return{ok:!1,message:"This flow changed while preparing its scripts. Read the terms again."};if(input.sawRevision!==void 0&&input.sawRevision!==flow.revision)return{ok:!1,message:"This flow changed while you were reading. Read the terms again."};const problem=unattendedSignProblem(store,flow,input.signer);if(problem!==null)return{ok:!1,message:problem};const candidates=unattendedCandidates(store,flow.id);if(input.sawSchedules!==void 0&&input.sawSchedules!==candidatesDigestOf(candidates))return{ok:!1,message:"This flow's schedules changed while you were reading. Read the terms again."};const include=input.ask.include??[],unknown=include.find(id2=>!candidates.some(one=>one.id===id2));if(unknown!==void 0)return{ok:!1,message:unreadableScriptSchedules(store,flow.id).includes(unknown)?`Trigger ${unknown} runs a script that ${UNREADABLE_SCRIPT}, so it can't be covered.`:`Trigger ${unknown} isn't one of this flow's active schedules.`};const covered=candidates.filter(one=>one.optional===null||include.includes(one.id));if(covered.length===0)return{ok:!1,message:"Choose a schedule to include: this flow's schedules bring in outside content, so none is covered unless you pick it."};const terms=unattendedTermsFor(flow,input.signer,input.ask,covered,now),digest=unattendedDigestOf(terms),previous=store.handle.prepare("SELECT * FROM flow_unattended_grant WHERE flow = ? AND revoked_at IS NULL").get(flow.id);previous!==void 0&&closeGrant(store,previous,input.signer,"renewed",now);const id=Number(store.handle.prepare(`INSERT INTO flow_unattended_grant (flow, repo, flow_revision, terms_json, digest, signed_by, signed_at, absolute_expiry)
17
+ cjs: tried(() => named(createRequire(from).resolve(spec))) }))));`;async function resolveAsNode(pairs){return new Promise(resolve2=>{const child=spawn(process.execPath,["--preserve-symlinks","--experimental-import-meta-resolve","--no-warnings","--input-type=module","-e",NODE_RESOLVER],{stdio:["pipe","pipe","ignore"],env:withoutLeadTokenEnv(process.env)});let output="";child.stdout.setEncoding("utf8"),child.stdout.on("data",part=>{output+=part,output.length>16*1024*1024&&child.kill()}),drainPipesAfterExit(child),child.on("error",()=>resolve2(null)),child.stdin.on("error",()=>{}),child.on("close",code=>{if(code!==0)return resolve2(null);try{const parsed=JSON.parse(output);resolve2(Array.isArray(parsed)&&parsed.length===pairs.length?parsed:null)}catch{resolve2(null)}}),child.stdin.end(JSON.stringify(pairs))})}const graphCache=new Map,fileIdentity=value=>[value.dev,value.ino,value.size,value.mtimeNs,value.ctimeNs].join(":");async function pathIdentity(path){try{return fileIdentity(await lstat(path,{bigint:!0}))}catch{return"missing"}}const graphNodes=new Map;function lastScript(store,repo,name){const row=store.flowScript(repo,name);if(row===null||row.held!==null)return null;if(row.file===null)return{provenance:2,name,version:row.version,digest:row.digest,file:null,files:[]};const raw=store.handle.prepare("SELECT snapshot FROM flow_script_provenance WHERE repo = ? AND name = ?").get(repo,name)?.snapshot;try{const saved=typeof raw=="string"?signedScript(JSON.parse(raw)):null;return saved?.version===row.version&&saved.digest===row.digest?saved:null}catch{return null}}const inside=(base,full)=>{const path=relative(base,full);return path!==""&&path!==".."&&!path.startsWith("../")&&!isAbsolute(path)?path:null};async function nodeModuleGraphOf(base,entry,fresh){const cached=graphCache.get(entry);if(!fresh&&cached&&(await Promise.all([...cached.watched].map(async([path,identity])=>await pathIdentity(path)===identity))).every(Boolean))return cached.files;const watched=new Map,watch=async path=>{watched.has(path)||watched.set(path,await pathIdentity(path))},watchResolution=async file=>{await watch(file);for(let folder=dirname(file);folder===base||inside(base,folder)!==null;folder=dirname(folder))await watch(folder),await watch(join(folder,"package.json")),await watch(join(folder,"node_modules"))},pinned=new Map;for(let layer=[entry];layer.length>0;){const pairs=[];for(const file of layer){await watchResolution(file);const metadata=await stat(file,{bigint:!0}),identity=fileIdentity(metadata);let node=graphNodes.get(file);if(fresh||node?.identity!==identity){const bytes=await readFile(file),imports=SOURCE_FILE.test(file)?typescript().preProcessFile(bytes.toString("utf8"),!0,!0).importedFiles.map(one=>one.fileName):[];if(SOURCE_FILE.test(file)){const source=typescript().createSourceFile(file,bytes.toString("utf8"),typescript().ScriptTarget.Latest,!0),visit=child=>{if(typescript().isCallExpression(child)&&typescript().isCallExpression(child.expression)&&/(?:^|\.)createRequire$/.test(child.expression.expression.getText(source))){const arg=child.arguments[0];arg&&typescript().isStringLiteralLike(arg)&&imports.push(arg.text)}typescript().forEachChild(child,visit)};visit(source)}node={identity,digest:bytesDigest(bytes),imports},graphNodes.delete(file),graphNodes.set(file,node),graphNodes.size>MAX_SCRIPT_FILES&&graphNodes.delete(graphNodes.keys().next().value)}pinned.set(file,node.digest);for(const spec of node.imports)pairs.push([spec,file])}if(pinned.size>MAX_SCRIPT_FILES)return null;const answers=pairs.length===0?[]:await resolveAsNode(pairs);if(answers===null)return null;const next=new Set;for(const[index,{esm,cjs}]of answers.entries()){const[spec,from]=pairs[index];if(spec.startsWith(".")){const lexical=resolve(dirname(from),spec);await watchResolution(lexical);try{if(inside(base,lexical)!==null&&inside(base,await realpath(lexical))===null)return null}catch{}}let found=!1;for(const one of new Set([esm,cjs])){if(one==="builtin"){found=!0;continue}if(one===null)continue;await watchResolution(one);let full;try{if(!(await stat(one)).isFile())continue;full=await realpath(one)}catch{continue}if(found=!0,inside(base,full)===null){if(inside(base,one)!==null)return null;continue}pinned.has(full)||next.add(full)}if(!found)return null}layer=[...next]}const files=[...pinned].map(([full,digest])=>({path:inside(base,full),digest})).sort((a,b)=>a.path<b.path?-1:1);return(await Promise.all([...watched].map(async([path,identity])=>await pathIdentity(path)===identity))).every(Boolean)?(graphCache.delete(entry),graphCache.set(entry,{files,watched}),graphCache.size>32&&graphCache.delete(graphCache.keys().next().value),files):null}export async function scriptProvenanceOf(store,repo,name,fresh=!0){const script=store.flowScript(repo,name);let result=null;try{if(script!==null&&script.held===null){if(script.file===null)result={provenance:2,name,version:script.version,digest:script.digest,file:null,files:[]};else if(!isAbsolute(script.file)&&!script.file.split(/[\\/]/).includes("..")){const base=await realpath(repo),lexical=join(base,script.file),full=await realpath(lexical);if(!(await lstat(lexical)).isSymbolicLink()&&full===lexical&&inside(base,full)!==null&&(await stat(full)).isFile()){const files=script.language==="node"?await nodeModuleGraphOf(base,full,fresh):[{path:script.file,digest:bytesDigest(await readFile(full))}];files!==null&&(result={provenance:2,name,version:script.version,digest:script.digest,file:script.file,files})}}}}catch{result=null}return store.handle.prepare("INSERT INTO flow_script_provenance (repo, name, snapshot) VALUES (?, ?, ?) ON CONFLICT(repo, name) DO UPDATE SET snapshot = excluded.snapshot").run(repo,name,result===null?null:JSON.stringify(result)),result}export async function prepareUnattendedCandidates(store,flowId){const flow=store.getFlow(flowId);if(flow!==null){for(const trigger of store.flowTriggers(flowId))if(!(trigger.kind!=="schedule"||trigger.state!=="active"))try{const config=JSON.parse(trigger.configJson);typeof config.script=="string"&&await scriptProvenanceOf(store,flow.repo,config.script,!1)}catch{}}}export function scriptRanDigestOf(before,after,ran){return before===null||after===null||canonicalJson(before)!==canonicalJson(after)||before.version!==ran.version||before.digest!==ran.digest?null:ranDigestOf(before)}const ranDigestOf=script=>createHash("sha256").update(`standing-orders:flow-unattended-script-ran:${canonicalJson(script)}`,"utf8").digest("hex").slice(0,32);export function grantSignsScriptOf(store,flowId,triggerId,now){const trigger=store.getFlowTrigger(triggerId),flow=store.getFlow(flowId),grant=activeUnattendedGrant(store,flowId,now);return trigger!==null&&trigger.state==="active"&&flow!==null&&grant!==null&&flow.revision===grant.terms.flowRevision&&coverageProblem(store,flow,grant.signedBy,[flow.repo])===null&&grant.terms.triggers.some(one=>one.id===triggerId&&one.kind==="script"&&one.digest===triggerDigestOf(trigger))}function scriptsUnchanged(store,terms){return terms.triggers.every(one=>one.kind!=="script"||one.script!==void 0&&canonicalJson(lastScript(store,terms.repo,one.script.name))===canonicalJson(one.script))}function endIfScriptsChanged(store,grant,now){return scriptsUnchanged(store,grant.terms)?!1:(store.transact(()=>{const row=store.handle.prepare("SELECT * FROM flow_unattended_grant WHERE id = ? AND revoked_at IS NULL").get(grant.id);row!==void 0&&closeGrant(store,row,"flow","script changed",now)}),!0)}export function unattendedCandidates(store,flowId){const out=[],flowRepo=store.getFlow(flowId)?.repo;if(flowRepo===void 0)return out;for(const trigger of store.flowTriggers(flowId)){if(trigger.kind!=="schedule"||trigger.state!=="active")continue;const digest=triggerDigestOf(trigger);let config;try{config=JSON.parse(trigger.configJson)}catch{continue}if(digest===null||config===null||typeof config!="object"||typeof config.schedule!="string"||config.order!==void 0)continue;const when=scheduleWords(config.schedule);if(config.kind==="plane-review")out.push({id:trigger.id,kind:"plane-review",digest,words:`Plane review, ${when}`,optional:"Its cards come from what the plane saw."});else{if(config.kind!=="schedule")continue;if(typeof config.script=="string"){const script=lastScript(store,flowRepo,config.script);script!==null&&out.push({id:trigger.id,kind:"script",digest,words:`the ${config.script} script, ${when}`,script,optional:"Its cards come from what the script prints, which can be outside text, and wait for you unless it ran the code you signed. Files it loads by a computed name aren't checked."})}else typeof config.title=="string"&&out.push({id:trigger.id,kind:"schedule",digest,words:`“${config.title}”, ${when}`,optional:null})}}return out}function unreadableScriptSchedules(store,flowId){const offered=new Set(unattendedCandidates(store,flowId).map(one=>one.id));return store.flowTriggers(flowId).filter(one=>{if(one.kind!=="schedule"||one.state!=="active"||offered.has(one.id))return!1;try{return typeof JSON.parse(one.configJson).script=="string"}catch{return!1}}).map(one=>one.id)}const UNREADABLE_SCRIPT="can't be read safely (it's missing, waiting for approval, or a project file it runs or imports can't be read)";export const candidatesDigestOf=candidates=>createHash("sha256").update(`standing-orders:flow-unattended-candidates:${canonicalJson(candidates)}`,"utf8").digest("hex").slice(0,32);export function unattendedSignProblem(store,flow,signer){return unattendedCandidates(store,flow.id).length===0?unreadableScriptSchedules(store,flow.id).length>0?`This flow's script ${UNREADABLE_SCRIPT}, so nothing would run on its own.`:"This flow has no schedule, so nothing would run on its own.":coverageProblem(store,flow,signer,workReposOf(flow))}export function parseUnattendedAsk(input){const text=v=>typeof v=="string"?v.trim():typeof v=="number"?String(v):"",days=Number(text(input.days));if(!Number.isInteger(days)||days<1||days>MODE_MAX_DAYS)return{ok:!1,message:`Choose 1 to ${MODE_MAX_DAYS} days: it always ends.`};const budget=unattendedBudgetOf(text(input.budget));if(!budget.ok)return budget;const runs=unattendedRunsOf(text(input.runs));if(!runs.ok)return runs;const budgetMicrousd=budget.value,dailyRunCap=runs.value,includeText=Array.isArray(input.include)?input.include.map(text).join(","):text(input.include),include=includeText===""?[]:includeText.split(/[\s,]+/).filter(one=>one!=="").map(Number);return include.some(id=>!Number.isSafeInteger(id)||id<1)?{ok:!1,message:"Name the schedules to include by their trigger ids, like 12,14."}:{ok:!0,ask:{days,budgetMicrousd,dailyRunCap,...include.length===0?{}:{include:[...new Set(include)]}}}}function unattendedTermsFor(flow,owner,ask,triggers,now){return{flow:flow.id,flowRevision:flow.revision,repo:flow.repo,owner,triggers:triggers.map(({id,kind,digest,words,script})=>({id,kind,digest,words,...kind==="script"&&script!==void 0?{script:structuredClone(script)}:{}})),permissions:"safe",acceptance:structuredClone(FLOW_ACCEPTANCE),perAttemptBudgetMicrousd:ask.budgetMicrousd,dailyRunCap:ask.dailyRunCap,absoluteExpiry:new Date(now.getTime()+ask.days*24*60*6e4).toISOString()}}export async function signUnattended(store,input,now){const revision=store.getFlow(input.flow)?.revision,schedules=canonicalJson(store.flowTriggers(input.flow));await prepareUnattendedCandidates(store,input.flow);const prepared=candidatesDigestOf(unattendedCandidates(store,input.flow));return sealUnattended(store,input,now,{revision,schedules,prepared})}export function sealUnattended(store,input,now,before){return store.transact(()=>{const flow=store.getFlow(input.flow);if(flow===null)return{ok:!1,message:"No such flow."};if(before!==void 0&&(before.revision!==flow.revision||before.schedules!==canonicalJson(store.flowTriggers(input.flow))||before.prepared!==candidatesDigestOf(unattendedCandidates(store,input.flow))))return{ok:!1,message:"This flow changed while preparing its scripts. Read the terms again."};if(input.sawRevision!==void 0&&input.sawRevision!==flow.revision)return{ok:!1,message:"This flow changed while you were reading. Read the terms again."};const problem=unattendedSignProblem(store,flow,input.signer);if(problem!==null)return{ok:!1,message:problem};const candidates=unattendedCandidates(store,flow.id);if(input.sawSchedules!==void 0&&input.sawSchedules!==candidatesDigestOf(candidates))return{ok:!1,message:"This flow's schedules changed while you were reading. Read the terms again."};const include=input.ask.include??[],unknown=include.find(id2=>!candidates.some(one=>one.id===id2));if(unknown!==void 0)return{ok:!1,message:unreadableScriptSchedules(store,flow.id).includes(unknown)?`Trigger ${unknown} runs a script that ${UNREADABLE_SCRIPT}, so it can't be covered.`:`Trigger ${unknown} isn't one of this flow's active schedules.`};const covered=candidates.filter(one=>one.optional===null||include.includes(one.id));if(covered.length===0)return{ok:!1,message:"Choose a schedule to include: this flow's schedules bring in outside content, so none is covered unless you pick it."};const terms=unattendedTermsFor(flow,input.signer,input.ask,covered,now),digest=unattendedDigestOf(terms),previous=store.handle.prepare("SELECT * FROM flow_unattended_grant WHERE flow = ? AND revoked_at IS NULL").get(flow.id);previous!==void 0&&closeGrant(store,previous,input.signer,"renewed",now);const id=Number(store.handle.prepare(`INSERT INTO flow_unattended_grant (flow, repo, flow_revision, terms_json, digest, signed_by, signed_at, absolute_expiry)
18
18
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(flow.id,flow.repo,flow.revision,unattendedTermsJson(terms),digest,input.signer,now.toISOString(),terms.absoluteExpiry).lastInsertRowid);return store.recordAction({at:now.toISOString(),actor:input.signer,repo:flow.repo,taskId:null,runId:null,source:"policy",action:`flow runs on its own: ${previous===void 0?"signed":"renewed"}`,outcome:previous===void 0?"signed":"renewed",detail:`${flow.name} (flow #${flow.id}) · until ${terms.absoluteExpiry.slice(0,16).replace("T"," ")} UTC${terms.perAttemptBudgetMicrousd===null?"":` · ${dollars(terms.perAttemptBudgetMicrousd)} per attempt`}${terms.dailyRunCap===null?"":` · ${terms.dailyRunCap} runs a day`}${input.road===void 0?"":` · grant #${id} · ${input.road}`}`}),{ok:!0,grant:{id,flow:flow.id,repo:flow.repo,terms,digest,signedBy:input.signer,signedAt:now.toISOString(),absoluteExpiry:terms.absoluteExpiry}}})}export function revokeUnattended(store,flowId,by,now){return store.transact(()=>{const row=store.handle.prepare("SELECT * FROM flow_unattended_grant WHERE flow = ? AND revoked_at IS NULL").get(flowId);if(row===void 0)return!1;const expired=Date.parse(String(row.absolute_expiry))<=now.getTime();return closeGrant(store,row,expired?"the-clock":by,expired?"expired":"revoked",now),!expired})}export function cardFromSignedSchedule(store,grant,cardId,requireScript=!0){return store.handle.prepare(`SELECT t.id, t.flow, t.kind, t.state, t.config_json, e.at, e.ran_script FROM flow_trigger_event e JOIN flow_trigger t ON t.id = e.trigger
19
19
  WHERE e.card = ? AND t.flow = ? AND e.on_time = 1`).all(cardId,grant.flow).some(row=>String(row.at)>=grant.signedAt&&String(row.state)==="active"&&grant.terms.triggers.some(one=>one.id===Number(row.id)&&one.digest===triggerDigestOf({id:Number(row.id),flow:Number(row.flow),kind:String(row.kind),configJson:String(row.config_json)})&&(!requireScript||one.kind!=="script"||one.script!==void 0&&row.ran_script===ranDigestOf(one.script))))?store.handle.prepare("SELECT 1 AS hit FROM flow_event WHERE card = ? AND ((outcome = 'moved' AND actor <> 'flow') OR outcome = 'sent-back') LIMIT 1").get(cardId)===void 0:!1}const utcDay=now=>now.toISOString().slice(0,10);function unattendedRunsToday(store,grantId,now){return Number(store.handle.prepare("SELECT COUNT(*) AS n FROM flow_unattended_run WHERE grant_id = ? AND day = ?").get(grantId,utcDay(now))?.n??0)}export function unattendedCoverageFor(store,flow,card,repo,now){const grant=activeUnattendedGrant(store,flow.id,now);return grant===null||grant.terms.flow!==flow.id||grant.terms.flowRevision!==flow.revision||grant.terms.repo!==flow.repo||grant.terms.owner!==grant.signedBy||coverageProblem(store,flow,grant.signedBy,[repo])!==null||!cardFromSignedSchedule(store,grant,card.id,!1)||endIfScriptsChanged(store,grant,now)||!cardFromSignedSchedule(store,grant,card.id)||grant.terms.dailyRunCap!==null&&unattendedRunsToday(store,grant.id,now)>=grant.terms.dailyRunCap?null:grant}export function reserveUnattendedRun(store,grant,taskId,now){const{changes}=store.handle.prepare(`INSERT OR IGNORE INTO flow_unattended_run (grant_id, day, task_id, at)
20
20
  SELECT ?, ?, ?, ? WHERE ? IS NULL OR (SELECT COUNT(*) FROM flow_unattended_run WHERE grant_id = ? AND day = ?) < ?`).run(grant.id,utcDay(now),taskId,now.toISOString(),grant.terms.dailyRunCap,grant.id,utcDay(now),grant.terms.dailyRunCap);return Number(changes)===1}export function releaseUnattendedRun(store,grant,taskId){store.handle.prepare("DELETE FROM flow_unattended_run WHERE grant_id = ? AND task_id = ?").run(grant.id,taskId)}export function unattendedGrantStands(store,digest,signer,taskRepo,touches,now){const row=store.handle.prepare("SELECT * FROM flow_unattended_grant WHERE digest = ? AND revoked_at IS NULL").get(digest);if(row===void 0||taskRepo===null)return!1;const grant=activeUnattendedGrant(store,Number(row.flow),now),flow=grant===null?null:store.getFlow(grant.flow);return grant===null||flow===null||grant.digest!==digest||grant.signedBy!==signer||grant.terms.flowRevision!==flow.revision||coverageProblem(store,flow,signer,[taskRepo])!==null||endIfScriptsChanged(store,grant,now)?!1:!isProtectedWork(store.approvalRules(taskRepo),[...touches])}export function unattendedViewOf(store,flow,viewer,now){const grant=activeUnattendedGrant(store,flow.id,now),live=grant!==null&&grant.terms.flowRevision===flow.revision&&grant.signedBy===flow.owner?grant:null,problem=viewer.approver?unattendedSignProblem(store,flow,viewer.name):"Only an approver can change this.",candidates=unattendedCandidates(store,flow.id);return{active:live===null?null:{until:live.absoluteExpiry,untilWords:untilWords(live.absoluteExpiry),signedBy:live.signedBy,budgetMicrousd:live.terms.perAttemptBudgetMicrousd,dailyRunCap:live.terms.dailyRunCap,runsToday:unattendedRunsToday(store,live.id,now),words:unattendedWords(live.terms),covers:live.terms.triggers.map(one=>one.words)},canSign:problem===null,problem,maxDays:MODE_MAX_DAYS,scheduled:candidates.length>0,terms:{head:unattendedHeadWords(viewer.name,FLOW_ACCEPTANCE),rules:[...UNATTENDED_RULE_WORDS]},schedules:candidates.map(one=>({id:one.id,words:one.words,optional:one.optional})),schedulesDigest:candidatesDigestOf(candidates),ended:live===null?unattendedEndedOf(store,flow.id,now):null}}const ENDED_WORDS={"flow changed":"the flow changed","script changed":"a script it runs changed","schedule changed":"a schedule changed","project protected":"the project's approval rules changed","access changed":"its signer's access changed"};function unattendedEndedOf(store,flowId,now){const row=store.handle.prepare("SELECT revoked_at, revoke_reason, absolute_expiry FROM flow_unattended_grant WHERE flow = ? ORDER BY id DESC LIMIT 1").get(flowId);if(row===void 0||row.revoked_at==null)return null;const why=ENDED_WORDS[String(row.revoke_reason)];return why===void 0||Date.parse(String(row.absolute_expiry))<=now.getTime()?null:{why,at:String(row.revoked_at)}}function flowStepRunsScript(store,flowId,name){const flow=store.getFlow(flowId);if(flow===null)return!1;let drawn;try{drawn=JSON.parse(flow.definitionJson)}catch{return!0}const stages=drawn!==null&&typeof drawn=="object"&&!Array.isArray(drawn)?drawn.stages:void 0;return!Array.isArray(stages)||!stages.every(stage=>stage!==null&&typeof stage=="object"&&!Array.isArray(stage))?!0:stages.some(stage=>stage.kind==="check"&&stage.script===name)}
package/dist/onboard.js CHANGED
@@ -1,3 +1,3 @@
1
- import{mkdirSync,openSync,closeSync,writeSync,rmSync,constants as fsConstants}from"node:fs";import{basename,dirname,join}from"node:path";import{spawn}from"node:child_process";import{withoutLeadTokenEnv}from"./names.js";const COMPONENT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;export function parseGithubRepo(raw){let text=raw.trim();if(text.length===0||text.length>512)return{ok:!1,problem:"name a repository as owner/name or a github.com link"};if(text.startsWith("https://")||text.startsWith("http://")){let url;try{url=new URL(text)}catch{return{ok:!1,problem:"that link is not a URL"}}if(url.protocol!=="https:"||url.hostname!=="github.com"||url.port!==""||url.username!==""||url.password!==""||url.search!==""||url.hash!=="")return{ok:!1,problem:"only plain https://github.com/owner/name links are accepted"};const segments=url.pathname.split("/").filter(one=>one!=="");if(segments.length!==2)return{ok:!1,problem:"a repository link has exactly two path segments: owner/name"};text=`${segments[0]}/${segments[1]?.replace(/\.git$/,"")}`}const parts=text.split("/");if(parts.length!==2)return{ok:!1,problem:"name a repository as owner/name"};const[owner="",name=""]=parts;for(const part of[owner,name])if(!COMPONENT.test(part)||part==="."||part===".."||part.startsWith("-")||part.startsWith("."))return{ok:!1,problem:"owner and name are letters, digits, dots, dashes, and underscores — nothing else"};return{ok:!0,owner,name}}const GH_ENV={GH_PROMPT_DISABLED:"1",GH_NO_UPDATE_NOTIFIER:"1",GIT_LFS_SKIP_SMUDGE:"1",GIT_TERMINAL_PROMPT:"0"};function runGhTree(args,options){return new Promise(resolve=>{if(process.platform==="win32"){resolve({code:1,stdout:"",stderr:"onboarding is not supported on Windows yet",timedOut:!1,notFound:!0,treeGone:!0});return}let child;try{child=spawn("gh",[...args],{cwd:options.cwd,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:withoutLeadTokenEnv({...process.env,...GH_ENV})})}catch(error){resolve({code:1,stdout:"",stderr:String(error),timedOut:!1,notFound:!1,treeGone:!0});return}const pid=child.pid;let stdout="",stderr="",timedOut=!1,notFound=!1;const timer=setTimeout(()=>{if(timedOut=!0,pid!==void 0)try{process.kill(-pid,"SIGKILL")}catch{}},options.timeoutMs);child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout.length<256*1024&&(stdout+=chunk)}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderr.length<64*1024&&(stderr+=chunk)}),child.on("error",error=>{notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error))}),child.on("close",code=>{clearTimeout(timer);const settle=treeGone=>resolve({code:notFound?127:timedOut?124:code??1,stdout,stderr,timedOut,notFound,treeGone});if(pid===void 0){settle(!0);return}const deadline=Date.now()+5e3,poll=()=>{try{process.kill(-pid,0)}catch{settle(!0);return}if(Date.now()>deadline){settle(!1);return}setTimeout(poll,100)};poll()})})}function ghWords(stderr){return(stderr.split(`
1
+ import{mkdirSync,openSync,closeSync,writeSync,rmSync,constants as fsConstants}from"node:fs";import{basename,dirname,join}from"node:path";import{spawn}from"node:child_process";import{withoutLeadTokenEnv}from"./names.js";import{drainPipesAfterExit}from"./pipes-after-exit.js";const COMPONENT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;export function parseGithubRepo(raw){let text=raw.trim();if(text.length===0||text.length>512)return{ok:!1,problem:"name a repository as owner/name or a github.com link"};if(text.startsWith("https://")||text.startsWith("http://")){let url;try{url=new URL(text)}catch{return{ok:!1,problem:"that link is not a URL"}}if(url.protocol!=="https:"||url.hostname!=="github.com"||url.port!==""||url.username!==""||url.password!==""||url.search!==""||url.hash!=="")return{ok:!1,problem:"only plain https://github.com/owner/name links are accepted"};const segments=url.pathname.split("/").filter(one=>one!=="");if(segments.length!==2)return{ok:!1,problem:"a repository link has exactly two path segments: owner/name"};text=`${segments[0]}/${segments[1]?.replace(/\.git$/,"")}`}const parts=text.split("/");if(parts.length!==2)return{ok:!1,problem:"name a repository as owner/name"};const[owner="",name=""]=parts;for(const part of[owner,name])if(!COMPONENT.test(part)||part==="."||part===".."||part.startsWith("-")||part.startsWith("."))return{ok:!1,problem:"owner and name are letters, digits, dots, dashes, and underscores — nothing else"};return{ok:!0,owner,name}}const GH_ENV={GH_PROMPT_DISABLED:"1",GH_NO_UPDATE_NOTIFIER:"1",GIT_LFS_SKIP_SMUDGE:"1",GIT_TERMINAL_PROMPT:"0"};function runGhTree(args,options){return new Promise(resolve=>{if(process.platform==="win32"){resolve({code:1,stdout:"",stderr:"onboarding is not supported on Windows yet",timedOut:!1,notFound:!0,treeGone:!0});return}let child;try{child=spawn("gh",[...args],{cwd:options.cwd,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:withoutLeadTokenEnv({...process.env,...GH_ENV})})}catch(error){resolve({code:1,stdout:"",stderr:String(error),timedOut:!1,notFound:!1,treeGone:!0});return}const pid=child.pid;let stdout="",stderr="",timedOut=!1,notFound=!1;const timer=setTimeout(()=>{if(timedOut=!0,pid!==void 0)try{process.kill(-pid,"SIGKILL")}catch{}},options.timeoutMs);child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout.length<256*1024&&(stdout+=chunk)}),child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderr.length<64*1024&&(stderr+=chunk)}),child.on("error",error=>{notFound=error.code==="ENOENT",stderr===""&&(stderr=String(error))}),drainPipesAfterExit(child,()=>{if(pid!==void 0)try{process.kill(-pid,"SIGKILL")}catch{}}),child.on("close",code=>{clearTimeout(timer);const settle=treeGone=>resolve({code:notFound?127:timedOut?124:code??1,stdout,stderr,timedOut,notFound,treeGone});if(pid===void 0){settle(!0);return}const deadline=Date.now()+5e3,poll=()=>{try{process.kill(-pid,0)}catch{settle(!0);return}if(Date.now()>deadline){settle(!1);return}setTimeout(poll,100)};poll()})})}function ghWords(stderr){return(stderr.split(`
2
2
  `).find(one=>one.trim()!=="")??"").replace(/[\x00-\x1f\x7f]/g," ").slice(0,200).trim()}const LARGE_REPO_KIB=1048576;export function isLargeRepo(preview){return preview.diskUsageKib===null||preview.diskUsageKib>=LARGE_REPO_KIB}export async function previewGithubRepo(owner,name){const answer=await runGhTree(["repo","view",`github.com/${owner}/${name}`,"--json","nameWithOwner,visibility,diskUsage,description"],{timeoutMs:3e4});if(answer.notFound)return{ok:!1,reason:"gh-missing",message:"the GitHub CLI is not installed on this machine — install gh where serve runs"};if(answer.timedOut)return{ok:!1,reason:"gh-timeout",message:"GitHub did not answer in time — nothing was written"};if(answer.code===4)return{ok:!1,reason:"gh-auth",message:"gh is not signed in — run `gh auth login --hostname github.com` where serve runs"};if(answer.code!==0)return{ok:!1,reason:"gh-said-no",message:`GitHub said no — ${ghWords(answer.stderr)||"the repository may not exist, or this account cannot see it"}; nothing was written`};let parsed;try{parsed=JSON.parse(answer.stdout)}catch{return{ok:!1,reason:"malformed",message:"GitHub's answer was not the JSON gh promises — nothing was written"}}const nameWithOwner=parsed.nameWithOwner;if(typeof nameWithOwner!="string"||!parseGithubRepo(nameWithOwner).ok)return{ok:!1,reason:"malformed",message:"GitHub named a repository shape this console refuses — nothing was written"};const disk=parsed.diskUsage,description=typeof parsed.description=="string"?parsed.description:"";return{ok:!0,preview:{nameWithOwner,visibility:typeof parsed.visibility=="string"?parsed.visibility.toLowerCase():"unknown",diskUsageKib:typeof disk=="number"&&disk>=0?disk:null,description:description.replace(/[\x00-\x1f\x7f]/g," ").slice(0,200)}}}export async function listGithubRepos(limit=100){const answer=await runGhTree(["repo","list","--json","nameWithOwner,isPrivate,updatedAt,description","--limit",String(Math.max(1,Math.min(200,limit)))],{timeoutMs:3e4});if(answer.notFound)return{ok:!1,reason:"gh-missing",message:"the GitHub CLI is not installed on this machine — install gh where serve runs"};if(answer.timedOut)return{ok:!1,reason:"gh-timeout",message:"GitHub did not answer in time"};if(answer.code===4)return{ok:!1,reason:"gh-auth",message:"gh is not signed in — run `gh auth login --hostname github.com` where serve runs"};if(answer.code!==0)return{ok:!1,reason:"gh-said-no",message:`GitHub said no — ${ghWords(answer.stderr)||"the account's repositories could not be listed"}`};let parsed;try{parsed=JSON.parse(answer.stdout)}catch{return{ok:!1,reason:"malformed",message:"GitHub's answer was not the JSON gh promises"}}if(!Array.isArray(parsed))return{ok:!1,reason:"malformed",message:"GitHub's answer was not the JSON gh promises"};const repos=[];for(const raw of parsed){if(raw===null||typeof raw!="object")continue;const row=raw,nameWithOwner=row.nameWithOwner;if(typeof nameWithOwner!="string"||!parseGithubRepo(nameWithOwner).ok)continue;const description=typeof row.description=="string"?row.description:"";repos.push({nameWithOwner,isPrivate:row.isPrivate===!0,updatedAt:typeof row.updatedAt=="string"&&/^\d{4}-\d{2}-\d{2}T[0-9:.]+Z?$/.test(row.updatedAt)?row.updatedAt:"",description:description.replace(/[\x00-\x1f\x7f]/g," ").slice(0,120)})}return{ok:!0,repos}}export async function cloneGithubRepo(nameWithOwner,root,gitVerify){const shape=parseGithubRepo(nameWithOwner);if(!shape.ok)return{ok:!1,reason:"clone-failed",message:shape.problem};const target=join(root,shape.name);if(dirname(target)!==root||basename(target)!==shape.name)return{ok:!1,reason:"clone-failed",message:"the target escaped its root — refused"};try{mkdirSync(target)}catch{return{ok:!1,reason:"exists",message:`nothing was written by this request — a directory already exists at ${target}; if it is empty and nobody is cloning, it is an abandoned claim: inspect and remove it by hand`}}const marker=join(target,".so-claim");try{const fd=openSync(marker,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL,384);writeSync(fd,`claimed by standing-orders onboarding
3
3
  `),closeSync(fd),rmSync(marker)}catch{}const answer=await runGhTree(["repo","clone",`github.com/${nameWithOwner}`,target,"--","--no-tags","--no-recurse-submodules"],{timeoutMs:10*6e4}),cleanOwn=()=>{if(!answer.treeGone)return!1;try{return rmSync(target,{recursive:!0,force:!0}),!0}catch{return!1}};if(answer.notFound)return cleanOwn(),{ok:!1,reason:"gh-missing",message:"the GitHub CLI is not installed on this machine — the claimed directory was removed"};if(answer.code===4)return{ok:!1,reason:"gh-auth",message:`gh is not signed in — run \`gh auth login --hostname github.com\` where serve runs; ${cleanOwn()?"the claimed directory was removed":`a residual remains at ${target}`}`};if(answer.timedOut||answer.code!==0){const removed=cleanOwn(),said=answer.timedOut?"the clone ran past ten minutes and was stopped":`the clone failed — ${ghWords(answer.stderr)||"git said no"}`;return{ok:!1,reason:answer.timedOut?"gh-timeout":"clone-failed",message:`${said}; ${removed?"this request's partial copy was removed":`a residual remains at ${target} — remove it by hand`}`}}if(!answer.treeGone)return{ok:!1,reason:"residual",message:`the clone finished but its helpers could not be proven gone — inspect ${target} before using it`};const top=await gitVerify(target);if(top.code!==0||top.stdout.trim()!==target){const removed=(()=>{try{return rmSync(target,{recursive:!0,force:!0}),!0}catch{return!1}})();return{ok:!1,reason:"verify-failed",message:`what landed did not verify as a repository at ${target}; ${removed?"it was removed":"a residual remains — remove it by hand"}`}}return{ok:!0,target}}
@@ -1,4 +1,4 @@
1
- import{currentActor}from"./actor.js";import{INSTALL_MODE_ACTION}from"./install-mode.js";import{activeRemote}from"./remote-run.js";import{PASSWORDLESS_ACTION}from"./passwordless.js";import{currentLocalOwner,localBindingStands,localModeOn,localOwnerInFlight,localOwnerStandsNow}from"./local-owner.js";import{isTailnetAddress}from"./public-access.js";const SESSION_IDLE_MS=720*6e4,SESSION_ABSOLUTE_MS=10080*6e4,withinSessionLifetime=(session,now)=>now-session.lastSeen<=SESSION_IDLE_MS&&now-session.createdAt<=SESSION_ABSOLUTE_MS,OWNER_MODE_ACTION="owner mode changed",TAILSCALE_LOGIN_ACTION="owner tailscale login changed";export const OWNER_MODE_WARNING="Agents run with your sign-ins. A task's checkout isn't a security sandbox. Choose Secure to restrict them.",OWNER_MODE_OTHER_ACCESS_WORDS="Fast mode is off: another person has access";const CHAT_IDENTITIES="SELECT DISTINCT provider, installation, team, member FROM chat_binding WHERE revoked IS NULL",TAILSCALE_LOGIN=/^[a-z0-9._@+-]{1,254}$/i;function safeCount(store,sql,...args){const n=Number(store.handle.prepare(sql).get(...args)?.n);if(!Number.isSafeInteger(n)||n<0)throw new Error("owner mode: unreadable count");return n}function registeredTailscaleLogins(store){try{const row=store.handle.prepare("SELECT detail FROM action_ledger WHERE repo IS NULL AND task_id IS NULL AND action = ? ORDER BY id DESC LIMIT 1").get(TAILSCALE_LOGIN_ACTION);if(row===void 0||typeof row.detail!="string")return[];const parsed=JSON.parse(row.detail),raw=Array.isArray(parsed)?parsed:parsed!==null&&typeof parsed=="object"&&Array.isArray(parsed.logins)?parsed.logins:null;return raw===null?[]:[...new Set(raw.filter(one=>typeof one=="string").map(one=>one.trim().toLowerCase()).filter(one=>TAILSCALE_LOGIN.test(one)))]}catch{return[]}}export function setRegisteredTailscaleLogins(store,logins,by,now){const normalized=[...new Set(logins.map(one=>one.trim().toLowerCase()).filter(one=>TAILSCALE_LOGIN.test(one)))];return store.transact(()=>{store.recordAction({at:now.toISOString(),actor:by,repo:null,taskId:null,runId:null,action:TAILSCALE_LOGIN_ACTION,outcome:normalized.length===0?"cleared":"set",source:"policy",detail:JSON.stringify({v:1,logins:normalized})}),store.bumpWake()}),normalized}export function liveInstallOwner(store,now=new Date){try{const stamp=now.toISOString(),active=store.handle.prepare("SELECT name, role, projects_json FROM approver WHERE revoked_at IS NULL").all();if(active.length!==1||active[0]?.role!=="approver"||active[0]?.projects_json!=null)return{ok:!1,reason:"other-access"};const owner=String(active[0].name);return safeCount(store,"SELECT count(*) AS n FROM invite WHERE consumed_at IS NULL AND revoked_at IS NULL AND expires_at > ?",stamp)>0?{ok:!1,reason:"other-access"}:safeCount(store,`SELECT count(*) AS n FROM (${CHAT_IDENTITIES})`)>1?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM chat_binding WHERE revoked IS NULL AND approver <> ?",owner)>0?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM chat_pair WHERE consumed IS NULL AND expires > ? AND approver <> ?",stamp,owner)>0?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM chat_room WHERE revoked IS NULL AND kind = 'group'")>0?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM credential WHERE revoked_at IS NULL AND (account IS NOT ? OR created_by IS NOT ?)",owner,owner)>0?{ok:!1,reason:"other-access"}:{ok:!0,owner}}catch{return{ok:!1,reason:"unreadable"}}}function hasSoloDeclaration(store){const row=store.handle.prepare(`SELECT outcome, detail FROM action_ledger
1
+ import{currentActor}from"./actor.js";import{INSTALL_MODE_ACTION}from"./install-mode.js";import{activeRemote}from"./remote-run.js";import{PASSWORDLESS_ACTION}from"./passwordless.js";import{currentLocalOwner,localBindingStands,localModeOn,localOwnerInFlight,localOwnerStandsNow}from"./local-owner.js";import{isTailnetAddress}from"./public-access.js";import{baseStoreOf,countsWritesOf,dataVersionThisTurn,writesSoFar}from"./sqlite-telemetry.js";const SESSION_IDLE_MS=720*6e4,SESSION_ABSOLUTE_MS=10080*6e4,withinSessionLifetime=(session,now)=>now-session.lastSeen<=SESSION_IDLE_MS&&now-session.createdAt<=SESSION_ABSOLUTE_MS,OWNER_MODE_ACTION="owner mode changed",TAILSCALE_LOGIN_ACTION="owner tailscale login changed";export const OWNER_MODE_WARNING="Agents run with your sign-ins. A task's checkout isn't a security sandbox. Choose Secure to restrict them.",OWNER_MODE_OTHER_ACCESS_WORDS="Fast mode is off: another person has access";const CHAT_IDENTITIES="SELECT DISTINCT provider, installation, team, member FROM chat_binding WHERE revoked IS NULL",TAILSCALE_LOGIN=/^[a-z0-9._@+-]{1,254}$/i;function safeCount(store,sql,...args){const n=Number(store.handle.prepare(sql).get(...args)?.n);if(!Number.isSafeInteger(n)||n<0)throw new Error("owner mode: unreadable count");return n}function registeredTailscaleLogins(store){try{const row=store.handle.prepare("SELECT detail FROM action_ledger WHERE repo IS NULL AND task_id IS NULL AND action = ? ORDER BY id DESC LIMIT 1").get(TAILSCALE_LOGIN_ACTION);if(row===void 0||typeof row.detail!="string")return[];const parsed=JSON.parse(row.detail),raw=Array.isArray(parsed)?parsed:parsed!==null&&typeof parsed=="object"&&Array.isArray(parsed.logins)?parsed.logins:null;return raw===null?[]:[...new Set(raw.filter(one=>typeof one=="string").map(one=>one.trim().toLowerCase()).filter(one=>TAILSCALE_LOGIN.test(one)))]}catch{return[]}}export function setRegisteredTailscaleLogins(store,logins,by,now){const normalized=[...new Set(logins.map(one=>one.trim().toLowerCase()).filter(one=>TAILSCALE_LOGIN.test(one)))];return store.transact(()=>{store.recordAction({at:now.toISOString(),actor:by,repo:null,taskId:null,runId:null,action:TAILSCALE_LOGIN_ACTION,outcome:normalized.length===0?"cleared":"set",source:"policy",detail:JSON.stringify({v:1,logins:normalized})}),store.bumpWake()}),normalized}export function liveInstallOwner(store,now=new Date){try{const stamp=now.toISOString(),active=store.handle.prepare("SELECT name, role, projects_json FROM approver WHERE revoked_at IS NULL").all();if(active.length!==1||active[0]?.role!=="approver"||active[0]?.projects_json!=null)return{ok:!1,reason:"other-access"};const owner=String(active[0].name);return safeCount(store,"SELECT count(*) AS n FROM invite WHERE consumed_at IS NULL AND revoked_at IS NULL AND expires_at > ?",stamp)>0?{ok:!1,reason:"other-access"}:safeCount(store,`SELECT count(*) AS n FROM (${CHAT_IDENTITIES})`)>1?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM chat_binding WHERE revoked IS NULL AND approver <> ?",owner)>0?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM chat_pair WHERE consumed IS NULL AND expires > ? AND approver <> ?",stamp,owner)>0?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM chat_room WHERE revoked IS NULL AND kind = 'group'")>0?{ok:!1,reason:"other-access"}:safeCount(store,"SELECT count(*) AS n FROM credential WHERE revoked_at IS NULL AND (account IS NOT ? OR created_by IS NOT ?)",owner,owner)>0?{ok:!1,reason:"other-access"}:{ok:!0,owner}}catch{return{ok:!1,reason:"unreadable"}}}function hasSoloDeclaration(store){const row=store.handle.prepare(`SELECT outcome, detail FROM action_ledger
2
2
  WHERE action = ? AND source = 'access' AND repo IS NULL AND task_id IS NULL AND run_id IS NULL
3
- ORDER BY id DESC LIMIT 1`).get(INSTALL_MODE_ACTION);if(row===void 0||row.outcome!=="solo")return!1;try{const parsed=JSON.parse(String(row.detail??"null"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&parsed.v===2}catch{return!1}}const ownerModeCache=new WeakMap;export function ownerModeSetting(store,now=new Date){const handle=store.handle;if(store.handle?.isTransaction!==!1)return readOwnerModeSetting(store,now);let key=null;try{const row=store.handle.prepare("SELECT total_changes() AS t, (SELECT data_version FROM pragma_data_version) AS d").get();key=`${String(row?.t)}|${String(row?.d)}|${Math.floor(now.getTime()/6e4)}`}catch{key=null}const cached=ownerModeCache.get(handle);if(cached!==void 0&&key!==null&&cached.key===key)return cached.read;const read=readOwnerModeSetting(store,now);return key!==null&&ownerModeCache.set(handle,{key,read}),read}function readOwnerModeSetting(store,now){try{const live=liveInstallOwner(store,now);if(!live.ok&&live.reason==="unreadable")return{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"unreadable",owner:null,otherAccess:!1};const saved=store.handle.prepare("SELECT mode, updated_by, updated_at FROM owner_mode WHERE id = 1").get();if(saved!==void 0){const mode=saved.mode,updatedBy=typeof saved.updated_by=="string"?saved.updated_by:null,updatedAt=typeof saved.updated_at=="string"?saved.updated_at:null;return mode!=="fast"&&mode!=="secure"?{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"unreadable",owner:null,otherAccess:!1}:mode==="secure"?{mode:"secure",explicit:!0,updatedBy,updatedAt,reason:"explicit",owner:live.ok?live.owner:null,otherAccess:!live.ok}:live.ok?{mode:"fast",explicit:!0,updatedBy,updatedAt,reason:"explicit",owner:live.owner,otherAccess:!1}:{mode:"secure",explicit:!0,updatedBy,updatedAt,reason:"other-access",owner:null,otherAccess:!0}}if(!live.ok)return{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"other-access",owner:null,otherAccess:!0};const pw=store.handle.prepare("SELECT outcome FROM action_ledger WHERE repo IS NULL AND task_id IS NULL AND action = ? ORDER BY id DESC LIMIT 1").get(PASSWORDLESS_ACTION);return pw!==void 0?pw.outcome!=="on"?{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"passwordless-off",owner:live.owner,otherAccess:!1}:{mode:"fast",explicit:!1,updatedBy:null,updatedAt:null,reason:"passwordless-on",owner:live.owner,otherAccess:!1}:hasSoloDeclaration(store)?{mode:"fast",explicit:!1,updatedBy:null,updatedAt:null,reason:"solo-now",owner:live.owner,otherAccess:!1}:{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"not-solo",owner:live.owner,otherAccess:!1}}catch{return{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"unreadable",owner:null,otherAccess:!1}}}export function ownerMode(store,now=new Date){return ownerModeSetting(store,now).mode}export function hasExplicitPlanner(store,repo=null){return repo!==null&&(store.phaseConfig(repo,"plan")!==null||store.phaseTierConfig(repo,"plan","strong")!==null)}export function defaultChainFor(store,repo=null,now=new Date){return ownerMode(store,now)==="fast"?hasExplicitPlanner(store,repo)?"plan-first":"just-code":"plan-first"}export function setOwnerMode(store,mode,by,now){return store.transact(()=>{const before=ownerModeSetting(store,now),stamp=now.toISOString();store.handle.prepare(`INSERT INTO owner_mode (id, mode, updated_by, updated_at) VALUES (1, ?, ?, ?)
3
+ ORDER BY id DESC LIMIT 1`).get(INSTALL_MODE_ACTION);if(row===void 0||row.outcome!=="solo")return!1;try{const parsed=JSON.parse(String(row.detail??"null"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&parsed.v===2}catch{return!1}}const ownerModeCache=new WeakMap;export function ownerModeSetting(store,now=new Date){const handle=baseStoreOf(store).handle;if(store.handle?.isTransaction!==!1)return readOwnerModeSetting(store,now);const minute=Math.floor(now.getTime()/6e4);let key=null;const base=handle;if(countsWritesOf(base)){const version=dataVersionThisTurn(base);key=version===null?null:`w${writesSoFar()}|${version}|${minute}`}else try{const row=store.handle.prepare("SELECT total_changes() AS t, (SELECT data_version FROM pragma_data_version) AS d").get();key=`${String(row?.t)}|${String(row?.d)}|${minute}`}catch{key=null}const cached=ownerModeCache.get(handle);if(cached!==void 0&&key!==null&&cached.key===key)return cached.read;const read=readOwnerModeSetting(store,now);return key!==null&&ownerModeCache.set(handle,{key,read}),read}function readOwnerModeSetting(store,now){try{const live=liveInstallOwner(store,now);if(!live.ok&&live.reason==="unreadable")return{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"unreadable",owner:null,otherAccess:!1};const saved=store.handle.prepare("SELECT mode, updated_by, updated_at FROM owner_mode WHERE id = 1").get();if(saved!==void 0){const mode=saved.mode,updatedBy=typeof saved.updated_by=="string"?saved.updated_by:null,updatedAt=typeof saved.updated_at=="string"?saved.updated_at:null;return mode!=="fast"&&mode!=="secure"?{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"unreadable",owner:null,otherAccess:!1}:mode==="secure"?{mode:"secure",explicit:!0,updatedBy,updatedAt,reason:"explicit",owner:live.ok?live.owner:null,otherAccess:!live.ok}:live.ok?{mode:"fast",explicit:!0,updatedBy,updatedAt,reason:"explicit",owner:live.owner,otherAccess:!1}:{mode:"secure",explicit:!0,updatedBy,updatedAt,reason:"other-access",owner:null,otherAccess:!0}}if(!live.ok)return{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"other-access",owner:null,otherAccess:!0};const pw=store.handle.prepare("SELECT outcome FROM action_ledger WHERE repo IS NULL AND task_id IS NULL AND action = ? ORDER BY id DESC LIMIT 1").get(PASSWORDLESS_ACTION);return pw!==void 0?pw.outcome!=="on"?{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"passwordless-off",owner:live.owner,otherAccess:!1}:{mode:"fast",explicit:!1,updatedBy:null,updatedAt:null,reason:"passwordless-on",owner:live.owner,otherAccess:!1}:hasSoloDeclaration(store)?{mode:"fast",explicit:!1,updatedBy:null,updatedAt:null,reason:"solo-now",owner:live.owner,otherAccess:!1}:{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"not-solo",owner:live.owner,otherAccess:!1}}catch{return{mode:"secure",explicit:!1,updatedBy:null,updatedAt:null,reason:"unreadable",owner:null,otherAccess:!1}}}export function ownerMode(store,now=new Date){return ownerModeSetting(store,now).mode}export function hasExplicitPlanner(store,repo=null){return repo!==null&&(store.phaseConfig(repo,"plan")!==null||store.phaseTierConfig(repo,"plan","strong")!==null)}export function defaultChainFor(store,repo=null,now=new Date){return ownerMode(store,now)==="fast"?hasExplicitPlanner(store,repo)?"plan-first":"just-code":"plan-first"}export function setOwnerMode(store,mode,by,now){return store.transact(()=>{const before=ownerModeSetting(store,now),stamp=now.toISOString();store.handle.prepare(`INSERT INTO owner_mode (id, mode, updated_by, updated_at) VALUES (1, ?, ?, ?)
4
4
  ON CONFLICT(id) DO UPDATE SET mode = excluded.mode, updated_by = excluded.updated_by, updated_at = excluded.updated_at`).run(mode,by,stamp);const changed=!before.explicit||before.mode!==mode;return store.recordAction({at:stamp,actor:by,repo:null,taskId:null,runId:null,action:OWNER_MODE_ACTION,outcome:mode,source:"policy",detail:mode==="fast"?"Fast mode on: single-owner actions run without password prompts; builds get your sign-ins":"Secure mode on: setup, widening and approvals require your password; builds are restricted"}),store.bumpWake(),{before:before.mode,after:mode,changed}})}export const FAST_OWNER_ACTS=Object.freeze(["project-network","check-access","sandbox","chat-approval","phone-settings","lead-config","mode-sign","models","review-switch","task-route","check-agent","accept","land","pr-merge","direct-chat","take-over","local-plugin-install"]);const FAST_OWNER_ACT_SET=new Set(FAST_OWNER_ACTS);function isFastOwnerAct(value){return typeof value=="string"&&FAST_OWNER_ACT_SET.has(value)}export function fastOwnerTransportAllowed(store,transport,authority="full"){return transport==null?!1:transport.kind==="loopback"?!0:authority==="local-owner"?!1:transport.kind==="tailscale-serve"?registeredTailscaleLogins(store).includes(transport.userLogin.trim().toLowerCase()):transport.kind==="tailscale-direct"?isTailnetAddress(transport.peerAddress)&&isTailnetAddress(transport.localAddress):!1}export function fastPrincipalOf(store,who,sessionHash=null,transport={kind:"other"}){return who==null?null:who.via!=="cookie"||who.session===void 0?{store,name:who.name,via:who.via,...who.role===void 0?{}:{role:who.role},...who.authority===void 0?{}:{authority:who.authority},...who.generation===void 0?{}:{generation:who.generation},transport,live:!1}:{store,name:who.name,via:"cookie",authority:who.session.authority,...who.role===void 0?{}:{role:who.role},generation:who.session.generation,localGeneration:who.session.localGeneration,sessionHash,createdAt:who.session.createdAt,lastSeen:who.session.lastSeen,transport,live:!0}}export function fastOwnerMay(act,principal,now=new Date){if(!isFastOwnerAct(act)||principal==null||activeRemote()!==null||currentActor()?.lead===!0||principal.via!=="cookie"||principal.live===!1||principal.authority!=="full"&&principal.authority!=="local-owner")return!1;try{const{store}=principal;if(!fastOwnerTransportAllowed(store,principal.transport,principal.authority))return!1;const setting=ownerModeSetting(store,now);if(setting.mode!=="fast"||setting.owner===null||setting.owner!==principal.name)return!1;const account=store.accountOf(principal.name);if(account===null||account.revokedAt!==null||account.role!=="approver"||!store.isInstanceOperator(principal.name)||principal.generation!==void 0&&account.generation!==principal.generation||principal.createdAt!==void 0&&principal.lastSeen!==void 0&&!withinSessionLifetime({createdAt:principal.createdAt,lastSeen:principal.lastSeen},now.getTime())||principal.sessionHash!=null&&store.webSession(principal.sessionHash)===null)return!1;if(principal.authority==="local-owner"){const local=currentLocalOwner();if(local!==null){if(local.account!==principal.name||!localOwnerInFlight(local)||!localOwnerStandsNow(store,local))return!1}else{if(!localModeOn(store))return!1;const row=store.handle.prepare("SELECT owner, generation, enabled, initialized_at, changed_at FROM local_mode WHERE id = 1").get();if(row===void 0)return!1;const localMode={owner:String(row.owner),generation:Number(row.generation),enabled:Number(row.enabled)===1,initializedAt:String(row.initialized_at),changedAt:String(row.changed_at)};if(!localBindingStands(localMode,{account:principal.name,localGeneration:principal.localGeneration??null}))return!1}}return!0}catch{return!1}}
@@ -0,0 +1 @@
1
+ export const 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=1e4){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?.())})}
@@ -1,4 +1,4 @@
1
- import{shownText}from"./shown-text.js";import{spawn}from"node:child_process";import{checkLinuxDependencies,cleanupBwrapMountPoints,getLinuxDependencyStatus,initializeLinuxNetworkBridge,wrapCommandWithSandboxLinux}from"@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js";import{SANDBOX_LAUNCH_SPEC,shellQuote,withRuntimeTemp}from"./sandbox-runtime.js";import{isLinuxSandboxTools,sandboxToolExclusions,verifyLinuxSandboxTools}from"./sandbox-tools.js";import{withoutLeadTokenEnv}from"./names.js";const REFUSED=126,STOPPED=143,pathsOf=tools=>({bwrapPath:tools.bwrap.real,socatPath:tools.socat.real,seccompConfig:{applyPath:tools.seccomp.real}});function missing(tools,exclusions){const changed=verifyLinuxSandboxTools(tools,{exclusions});if(changed!==null)return changed;const paths=pathsOf(tools),checked=checkLinuxDependencies(paths);return checked.errors.length>0?checked.errors.join("; "):getLinuxDependencyStatus(paths).hasSeccompApply?null:"the sandbox runtime's seccomp helper isn't available"}function toolsProblem(spec){const tools=spec.tools;return isLinuxSandboxTools(tools)?verifyLinuxSandboxTools(tools,{exclusions:sandboxToolExclusions(spec.terms,spec.cwd)}):"the sandbox's programs weren't given by checked paths"}async function main(){const raw=process.env[SANDBOX_LAUNCH_SPEC];if(delete process.env[SANDBOX_LAUNCH_SPEC],raw===void 0)return process.stderr.write(`toolroll sandbox: no launch was given
1
+ import{shownText}from"./shown-text.js";import{spawn}from"node:child_process";import{checkLinuxDependencies,cleanupBwrapMountPoints,getLinuxDependencyStatus,initializeLinuxNetworkBridge,wrapCommandWithSandboxLinux}from"@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js";import{SANDBOX_LAUNCH_SPEC,shellQuote,withRuntimeTemp}from"./sandbox-runtime.js";import{isLinuxSandboxTools,sandboxToolExclusions,verifyLinuxSandboxTools}from"./sandbox-tools.js";import{withoutLeadTokenEnv}from"./names.js";import{drainPipesAfterExit}from"./pipes-after-exit.js";const REFUSED=126,STOPPED=143,pathsOf=tools=>({bwrapPath:tools.bwrap.real,socatPath:tools.socat.real,seccompConfig:{applyPath:tools.seccomp.real}});function missing(tools,exclusions){const changed=verifyLinuxSandboxTools(tools,{exclusions});if(changed!==null)return changed;const paths=pathsOf(tools),checked=checkLinuxDependencies(paths);return checked.errors.length>0?checked.errors.join("; "):getLinuxDependencyStatus(paths).hasSeccompApply?null:"the sandbox runtime's seccomp helper isn't available"}function toolsProblem(spec){const tools=spec.tools;return isLinuxSandboxTools(tools)?verifyLinuxSandboxTools(tools,{exclusions:sandboxToolExclusions(spec.terms,spec.cwd)}):"the sandbox's programs weren't given by checked paths"}async function main(){const raw=process.env[SANDBOX_LAUNCH_SPEC];if(delete process.env[SANDBOX_LAUNCH_SPEC],raw===void 0)return process.stderr.write(`toolroll sandbox: no launch was given
2
2
  `),REFUSED;const spec=JSON.parse(raw),problem=toolsProblem(spec);if(problem!==null)return process.stderr.write(`toolroll sandbox: nothing was started: ${shownText(problem)}
3
- `),REFUSED;const tools=spec.tools,exclusions=sandboxToolExclusions(spec.terms,spec.cwd),launchEnv=withoutLeadTokenEnv({...process.env});process.env.PATH=tools.whichFolder,process.chdir(spec.cwd);let stopping=!1,child=null;for(const signal of["SIGTERM","SIGINT","SIGHUP"])process.on(signal,()=>{stopping=!0;try{child?.kill(signal)}catch{}});const network=spec.terms.network;let bridge=null;const stopBridge=async()=>{await Promise.all([bridge?.httpBridgeProcess,bridge?.socksBridgeProcess].map(one=>new Promise(done=>{if(one===void 0||one.exitCode!==null||one.signalCode!==null){done();return}const force=setTimeout(()=>{try{one.kill("SIGKILL")}catch{}},1e3);one.once("exit",()=>{clearTimeout(force),done()});try{one.kill("SIGTERM")}catch{clearTimeout(force),done()}})))};try{network.kind==="proxy"&&(bridge=await initializeLinuxNetworkBridge(network.httpPort,network.socksPort??network.httpPort,tools.socat.real)),spec.temp!==void 0?process.env.CLAUDE_CODE_TMPDIR=spec.temp:withRuntimeTemp(void 0,()=>{});const started=`printf 1 >&3 || exit 125; exec 3>&-; exec ${shellQuote([spec.file,...spec.args])}`;for(let attempt=1;;attempt++){if(stopping)return STOPPED;const gone=missing(tools,exclusions);if(gone!==null)throw new Error(`the sandbox can't be made here: ${gone}`);const command=await wrapCommandWithSandboxLinux({command:started,needsNetworkRestriction:network.kind==="proxy",...bridge===null||network.kind!=="proxy"?{}:{httpSocketPath:bridge.httpSocketPath,socksSocketPath:bridge.socksSocketPath,httpProxyPort:network.httpPort,...network.socksPort===void 0?{}:{socksProxyPort:network.socksPort},...network.token===void 0?{}:{proxyAuthToken:network.token}},readConfig:spec.terms.readConfig,writeConfig:spec.terms.writeConfig,...pathsOf(tools),binShell:tools.bash.real,ripgrepConfig:{command:tools.rg.real}});if(!/\bbwrap\b/.test(command)||![tools.bwrap.real,tools.seccomp.real,tools.bash.real].every(path=>command.includes(path))||!command.includes("apply-seccomp"))throw new Error("the sandbox runtime returned a command without its sandbox, its seccomp filter or the programs it was handed");if(stopping)return STOPPED;const run=spawn("/bin/sh",["-c",command],{stdio:["inherit","inherit","pipe","pipe"],env:launchEnv});child=run;let ran=!1;const held=[];run.stdio[3].on("data",()=>{if(!ran){ran=!0;for(const one of held.splice(0))process.stderr.write(one)}}),run.stdio[3].on("error",()=>{}),run.stderr.on("data",chunk=>{ran?process.stderr.write(chunk):held.push(chunk)});const status=await new Promise(done=>{run.on("error",()=>done(REFUSED)),run.on("close",(code,signal)=>done(code??(signal===null?1:128+({SIGKILL:9,SIGTERM:15,SIGINT:2,SIGHUP:1}[signal]??1))))});if(!ran&&stopping)return STOPPED;if(ran||attempt>=3){if(!ran)for(const one of held)process.stderr.write(one);return status}try{cleanupBwrapMountPoints()}catch{}await new Promise(done=>setTimeout(done,50*attempt))}}catch(error){return child===null?(process.stderr.write(`toolroll sandbox: nothing was started: ${shownText(error instanceof Error?error.message:String(error))}
3
+ `),REFUSED;const tools=spec.tools,exclusions=sandboxToolExclusions(spec.terms,spec.cwd),launchEnv=withoutLeadTokenEnv({...process.env});process.env.PATH=tools.whichFolder,process.chdir(spec.cwd);let stopping=!1,child=null;for(const signal of["SIGTERM","SIGINT","SIGHUP"])process.on(signal,()=>{stopping=!0;try{child?.kill(signal)}catch{}});const network=spec.terms.network;let bridge=null;const stopBridge=async()=>{await Promise.all([bridge?.httpBridgeProcess,bridge?.socksBridgeProcess].map(one=>new Promise(done=>{if(one===void 0||one.exitCode!==null||one.signalCode!==null){done();return}const force=setTimeout(()=>{try{one.kill("SIGKILL")}catch{}},1e3);one.once("exit",()=>{clearTimeout(force),done()});try{one.kill("SIGTERM")}catch{clearTimeout(force),done()}})))};try{network.kind==="proxy"&&(bridge=await initializeLinuxNetworkBridge(network.httpPort,network.socksPort??network.httpPort,tools.socat.real)),spec.temp!==void 0?process.env.CLAUDE_CODE_TMPDIR=spec.temp:withRuntimeTemp(void 0,()=>{});const started=`printf 1 >&3 || exit 125; exec 3>&-; exec ${shellQuote([spec.file,...spec.args])}`;for(let attempt=1;;attempt++){if(stopping)return STOPPED;const gone=missing(tools,exclusions);if(gone!==null)throw new Error(`the sandbox can't be made here: ${gone}`);const command=await wrapCommandWithSandboxLinux({command:started,needsNetworkRestriction:network.kind==="proxy",...bridge===null||network.kind!=="proxy"?{}:{httpSocketPath:bridge.httpSocketPath,socksSocketPath:bridge.socksSocketPath,httpProxyPort:network.httpPort,...network.socksPort===void 0?{}:{socksProxyPort:network.socksPort},...network.token===void 0?{}:{proxyAuthToken:network.token}},readConfig:spec.terms.readConfig,writeConfig:spec.terms.writeConfig,...pathsOf(tools),binShell:tools.bash.real,ripgrepConfig:{command:tools.rg.real}});if(!/\bbwrap\b/.test(command)||![tools.bwrap.real,tools.seccomp.real,tools.bash.real].every(path=>command.includes(path))||!command.includes("apply-seccomp"))throw new Error("the sandbox runtime returned a command without its sandbox, its seccomp filter or the programs it was handed");if(stopping)return STOPPED;const run=spawn("/bin/sh",["-c",command],{stdio:["inherit","inherit","pipe","pipe"],env:launchEnv});child=run;let ran=!1;const held=[];run.stdio[3].on("data",()=>{if(!ran){ran=!0;for(const one of held.splice(0))process.stderr.write(one)}}),run.stdio[3].on("error",()=>{}),run.stderr.on("data",chunk=>{ran?process.stderr.write(chunk):held.push(chunk)}),drainPipesAfterExit(run,()=>{try{run.stdio[3]?.destroy()}catch{}});const status=await new Promise(done=>{run.on("error",()=>done(REFUSED)),run.on("close",(code,signal)=>done(code??(signal===null?1:128+({SIGKILL:9,SIGTERM:15,SIGINT:2,SIGHUP:1}[signal]??1))))});if(!ran&&stopping)return STOPPED;if(ran||attempt>=3){if(!ran)for(const one of held)process.stderr.write(one);return status}try{cleanupBwrapMountPoints()}catch{}await new Promise(done=>setTimeout(done,50*attempt))}}catch(error){return child===null?(process.stderr.write(`toolroll sandbox: nothing was started: ${shownText(error instanceof Error?error.message:String(error))}
4
4
  `),REFUSED):1}finally{try{cleanupBwrapMountPoints()}catch{}await stopBridge()}}main().then(code=>process.exit(code));
@@ -1 +1 @@
1
- import{StatementCache}from"./statement-cache.js";let writes=0;export const writesSoFar=()=>writes;const ownTemp=op=>/^(?:CREATE\s+TEMP\s+TABLE\s+"so_work_ranked_\d+"|(?:DROP\s+TABLE\s+IF\s+EXISTS|DELETE\s+FROM)\s+temp\."so_work_ranked_\d+"$|INSERT\s+INTO\s+temp\."so_work_ranked_\d+"\s)/i.test(op),opening=op=>/^(?:BEGIN(?:\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE))?(?:\s+TRANSACTION)?|SAVEPOINT\s+\w+)\s*;?$/i.test(op),settingOnly=op=>/^PRAGMA\s+busy_timeout\s*=\s*\d+\s*;?$/i.test(op),ending=op=>/^(?:COMMIT|END|ROLLBACK|RELEASE)\b[^;]*;?\s*$/i.test(op),states=new WeakMap;export function measureWriteWait(db,body){const state=states.get(db);if(!state||state.measuringWait)return body();const started=state.telemetry.clock();state.measuringWait=!0;try{return body()}finally{state.measuringWait=!1,state.telemetry.writeWait.observe((state.telemetry.clock()-started)/1e3)}}export function instrumentDatabase(db,telemetry,options={}){const state={telemetry,measuringWait:!1};let heldAt=null;const elapsed=at=>(telemetry.clock()-at)/1e3,operation=sql=>sql.replace(/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)+/,"").trim(),writing=sql=>/^(?:INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER)\b/i.test(sql)||/^WITH\b[\s\S]*\b(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql),standalone=(write,body)=>{if(!write||heldAt!==null)return body();const at=telemetry.clock();try{return body()}finally{telemetry.writeStatement.observe(elapsed(at))}},finish=()=>{heldAt!==null&&(telemetry.writeHold.observe(elapsed(heldAt)),heldAt=null)};let openedAt=null;const native=db,counted=(counts2,body)=>{counts2&&writes++;try{return body()}catch(error){throw writes++,error}},execNow=(sql,op)=>{if(/^BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)\b/i.test(op)){const at=telemetry.clock();try{db.exec(sql),heldAt=telemetry.clock()}finally{state.measuringWait||telemetry.writeWait.observe(elapsed(at))}}else/^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op)?(db.exec(sql),finish()):standalone(writing(op),()=>db.exec(sql))},counts=(op,path,write)=>ownTemp(op)||settingOnly(op)?!1:opening(op)?(openedAt===null&&native.isTransaction!==!0&&(openedAt=writes),!1):ending(op)?openedAt===null||writes!==openedAt:path!=="read"||write,settled=op=>{(native.isTransaction===!1||native.isTransaction===void 0&&/^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op))&&(openedAt=null)},tracked=(op,path,write,body)=>{try{return counted(counts(op,path,write),body)}finally{settled(op)}},methods={exec(sql){const op=operation(sql);try{tracked(op,"exec",!0,()=>execNow(sql,op))}finally{cache?.executed(sql)}},prepare(sql){return cache===null?compile(sql):cache.prepare(sql)},close(){cache?.clear();try{db.close()}finally{finish()}}};function compile(sql){const op=operation(sql),statement=db.prepare(sql),write=writing(op),methods2={run:(...params)=>tracked(op,"run",write,()=>standalone(write,()=>statement.run(...params))),get:(...params)=>tracked(op,"read",write,()=>standalone(write,()=>statement.get(...params))),all:(...params)=>tracked(op,"read",write,()=>standalone(write,()=>statement.all(...params)))},rows=statement;return typeof rows.iterate=="function"&&Object.assign(methods2,{iterate:(...params)=>tracked(op,"read",write,()=>rows.iterate(...params))}),preservingNative(statement,methods2)}const cache=options.cacheStatements===!0?new StatementCache(compile):null;cache!==null&&Object.assign(methods,{prepareUncached:sql=>cache.prepareUncached(sql),statementCacheStats:()=>({...cache.stats})});const wrapped=preservingNative(db,methods);return states.set(wrapped,state),wrapped}function preservingNative(native,methods){return new Proxy(methods,{get(target,property){if(Object.hasOwn(target,property))return Reflect.get(target,property);const value=Reflect.get(native,property,native);return typeof value=="function"?value.bind(native):value},has:(target,property)=>Reflect.has(target,property)||Reflect.has(native,property),getPrototypeOf:()=>Object.getPrototypeOf(native)})}
1
+ import{StatementCache}from"./statement-cache.js";let writes=0;export const writesSoFar=()=>writes;let requestReads=null;export const setRequestReads=reads=>{requestReads=reads},throughRequestReads=store=>requestReads===null?store:requestReads.reader(store),baseStoreOf=store=>requestReads===null?store:requestReads.base(store);let turn=0,turning=!1;export function currentTurn(){return turning||(turning=!0,queueMicrotask(()=>{turning=!1,turn++})),turn}const turnVersions=new WeakMap;export function dataVersionThisTurn(db,exact=!1){const now=currentTurn(),held=turnVersions.get(db);if(!exact&&held!==void 0&&held.turn===now)return held.value;try{const value=String(db.prepare("PRAGMA data_version").get()?.data_version);return turnVersions.set(db,{turn:now,value}),value}catch{return turnVersions.delete(db),null}}export const countsWritesOf=db=>states.has(db);const ownTemp=op=>/^(?:CREATE\s+TEMP\s+TABLE\s+"so_work_ranked_\d+"|(?:DROP\s+TABLE\s+IF\s+EXISTS|DELETE\s+FROM)\s+temp\."so_work_ranked_\d+"$|INSERT\s+INTO\s+temp\."so_work_ranked_\d+"\s)/i.test(op),opening=op=>/^(?:BEGIN(?:\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE))?(?:\s+TRANSACTION)?|SAVEPOINT\s+\w+)\s*;?$/i.test(op),settingOnly=op=>/^PRAGMA\s+busy_timeout\s*=\s*\d+\s*;?$/i.test(op),ending=op=>/^(?:COMMIT|END|ROLLBACK|RELEASE)\b[^;]*;?\s*$/i.test(op),states=new WeakMap;export function measureWriteWait(db,body){const state=states.get(db);if(!state||state.measuringWait)return body();const started=state.telemetry.clock();state.measuringWait=!0;try{return body()}finally{state.measuringWait=!1,state.telemetry.writeWait.observe((state.telemetry.clock()-started)/1e3)}}export function instrumentDatabase(db,telemetry,options={}){const state={telemetry,measuringWait:!1};let heldAt=null;const elapsed=at=>(telemetry.clock()-at)/1e3,operation=sql=>sql.replace(/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)+/,"").trim(),writing=sql=>/^(?:INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER)\b/i.test(sql)||/^WITH\b[\s\S]*\b(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql),standalone=(write,body)=>{if(!write||heldAt!==null)return body();const at=telemetry.clock();try{return body()}finally{telemetry.writeStatement.observe(elapsed(at))}},finish=()=>{heldAt!==null&&(telemetry.writeHold.observe(elapsed(heldAt)),heldAt=null)};let openedAt=null;const native=db,counted=(counts2,body)=>{counts2&&writes++;try{return body()}catch(error){throw writes++,error}},execNow=(sql,op)=>{if(/^BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)\b/i.test(op)){const at=telemetry.clock();try{db.exec(sql),heldAt=telemetry.clock()}finally{state.measuringWait||telemetry.writeWait.observe(elapsed(at))}}else/^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op)?(db.exec(sql),finish()):standalone(writing(op),()=>db.exec(sql))},counts=(op,path,write)=>ownTemp(op)||settingOnly(op)?!1:opening(op)?(openedAt===null&&native.isTransaction!==!0&&(openedAt=writes),!1):ending(op)?openedAt===null||writes!==openedAt:path!=="read"||write,settled=op=>{(native.isTransaction===!1||native.isTransaction===void 0&&/^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op))&&(openedAt=null)},tracked=(op,path,write,body)=>{try{return counted(counts(op,path,write),body)}finally{settled(op)}},methods={exec(sql){const op=operation(sql);try{tracked(op,"exec",!0,()=>execNow(sql,op))}finally{cache?.executed(sql)}},prepare(sql){return cache===null?compile(sql):cache.prepare(sql)},close(){cache?.clear();try{db.close()}finally{finish()}}};function compile(sql){const op=operation(sql),statement=db.prepare(sql),write=writing(op),methods2={run:(...params)=>tracked(op,"run",write,()=>standalone(write,()=>statement.run(...params))),get:(...params)=>tracked(op,"read",write,()=>standalone(write,()=>statement.get(...params))),all:(...params)=>tracked(op,"read",write,()=>standalone(write,()=>statement.all(...params)))},rows=statement;return typeof rows.iterate=="function"&&Object.assign(methods2,{iterate:(...params)=>tracked(op,"read",write,()=>rows.iterate(...params))}),preservingNative(statement,methods2)}const cache=options.cacheStatements===!0?new StatementCache(compile):null;cache!==null&&Object.assign(methods,{prepareUncached:sql=>cache.prepareUncached(sql),statementCacheStats:()=>({...cache.stats})});const wrapped=preservingNative(db,methods);return states.set(wrapped,state),wrapped}function preservingNative(native,methods){return new Proxy(methods,{get(target,property){if(Object.hasOwn(target,property))return Reflect.get(target,property);const value=Reflect.get(native,property,native);return typeof value=="function"?value.bind(native):value},has:(target,property)=>Reflect.has(target,property)||Reflect.has(native,property),getPrototypeOf:()=>Object.getPrototypeOf(native)})}