@capybara-hq/device 0.1.0-rc.15 → 0.1.0-rc.16
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.
|
@@ -92,8 +92,11 @@ export declare const JAVA_PROXY_AGENT_JAR = "vendor/java-proxy-agent/srt-proxy-a
|
|
|
92
92
|
* kills that tree and the owned groups. Once the launched process has exited and its group is
|
|
93
93
|
* gone, `settle` closes the stdio pipes after a short bounded grace, so a process that escaped
|
|
94
94
|
* (one reparented to launchd before the walk) cannot hold the call or the worker open.
|
|
95
|
+
* Darwin answers a group signal with EPERM (not ESRCH) while the group holds only dead members
|
|
96
|
+
* (zombies not yet reaped, or processes exiting), so `signalGroup` counts EPERM as gone when a
|
|
97
|
+
* process snapshot shows no live member of the group; EPERM with a live member still fails.
|
|
95
98
|
*/
|
|
96
|
-
export declare const WORKER = "import {pathToFileURL} from 'node:url';\nimport {spawn,spawnSync} from 'node:child_process';\nimport {randomUUID} from 'node:crypto';\nlet manager,initialized=false,wrapped=false,closing=false,full=false,child,childClosed,timer,timedOut=false,killed=false,exited=false,forced=false,settling=false,settleTimer;\nconst owned=new Map(),signaled=new Set();\nlet credit,sequence=0,outputFailed=false,outputDone=Promise.resolve();\nasync function collect(stream){\n try{for await(const chunk of stream){\n for(let offset=0;offset<chunk.length;offset+=65536){\n if(outputFailed)continue;\n const data=chunk.subarray(offset,offset+65536);const seq=sequence++;\n const bufferedBytes=chunk.length+stream.readableLength;if(bufferedBytes>262144)throw Error('Managed producer buffer exceeded bound');\n send({event:'output-flow',frameBytes:data.length,bufferedBytes,producerLimit:262144});\n await new Promise((resolve,reject)=>{credit={seq,resolve,reject};send({event:'output',stream:'stdout',seq,data:data.toString('base64')});});\n }\n }}catch(error){if(forced)return;const alreadyFailed=outputFailed;outputFailed=true;stream.resume();if(!alreadyFailed)send({event:'error',message:'Managed producer failed'});}\n}\nconst send=value=>{if(process.connected)process.send(value,()=>{});};\nfunction stopTree(){\n if(!child?.pid||child.exitCode!==null||child.signalCode!==null)return [];\n try{process.kill(child.pid,'SIGSTOP');}catch{return [];}\n const tree=new Set([child.pid]);\n for(let round=0;round<64;round++){\n const ps=spawnSync('/bin/ps',['-axo','pid=,ppid='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0){send({event:'diagnostic',text:'Descendant snapshot failed'});break;}\n const found=[];\n for(const line of ps.stdout.split('\\n')){const [pid,ppid]=line.trim().split(/\\s+/).map(Number);if(pid>1&&tree.has(ppid)&&!tree.has(pid))found.push(pid);}\n if(!found.length)break;\n for(const pid of found)try{process.kill(pid,'SIGSTOP');tree.add(pid);}catch{}\n }\n return [...tree];\n}\nfunction signalOwned(signal='SIGKILL'){if(signal==='SIGKILL')for(const pid of stopTree())try{process.kill(pid,'SIGKILL');}catch{}for(const pid of owned.keys()){if(signaled.has(pid))continue;
|
|
99
|
+
export declare const WORKER = "import {pathToFileURL} from 'node:url';\nimport {spawn,spawnSync} from 'node:child_process';\nimport {randomUUID} from 'node:crypto';\nlet manager,initialized=false,wrapped=false,closing=false,full=false,child,childClosed,timer,timedOut=false,killed=false,exited=false,forced=false,settling=false,settleTimer;\nconst owned=new Map(),signaled=new Set();\nlet credit,sequence=0,outputFailed=false,outputDone=Promise.resolve();\nasync function collect(stream){\n try{for await(const chunk of stream){\n for(let offset=0;offset<chunk.length;offset+=65536){\n if(outputFailed)continue;\n const data=chunk.subarray(offset,offset+65536);const seq=sequence++;\n const bufferedBytes=chunk.length+stream.readableLength;if(bufferedBytes>262144)throw Error('Managed producer buffer exceeded bound');\n send({event:'output-flow',frameBytes:data.length,bufferedBytes,producerLimit:262144});\n await new Promise((resolve,reject)=>{credit={seq,resolve,reject};send({event:'output',stream:'stdout',seq,data:data.toString('base64')});});\n }\n }}catch(error){if(forced)return;const alreadyFailed=outputFailed;outputFailed=true;stream.resume();if(!alreadyFailed)send({event:'error',message:'Managed producer failed'});}\n}\nconst send=value=>{if(process.connected)process.send(value,()=>{});};\nfunction stopTree(){\n if(!child?.pid||child.exitCode!==null||child.signalCode!==null)return [];\n try{process.kill(child.pid,'SIGSTOP');}catch{return [];}\n const tree=new Set([child.pid]);\n for(let round=0;round<64;round++){\n const ps=spawnSync('/bin/ps',['-axo','pid=,ppid='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0){send({event:'diagnostic',text:'Descendant snapshot failed'});break;}\n const found=[];\n for(const line of ps.stdout.split('\\n')){const [pid,ppid]=line.trim().split(/\\s+/).map(Number);if(pid>1&&tree.has(ppid)&&!tree.has(pid))found.push(pid);}\n if(!found.length)break;\n for(const pid of found)try{process.kill(pid,'SIGSTOP');tree.add(pid);}catch{}\n }\n return [...tree];\n}\nfunction deadGroup(pgid){\n const ps=spawnSync('/bin/ps',['-axo','pgid=,stat='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0)return false;\n for(const line of ps.stdout.split('\\n')){const [group,stat='']=line.trim().split(/\\s+/);if(Number(group)===pgid&&!stat.startsWith('Z')&&!stat.includes('E'))return false;}\n return true;\n}\nfunction signalGroup(pgid,signal){try{process.kill(-pgid,signal);return true;}catch(error){if(error.code==='ESRCH'||(error.code==='EPERM'&&deadGroup(pgid)))return false;throw error;}}\nfunction signalOwned(signal='SIGKILL'){if(signal==='SIGKILL')for(const pid of stopTree())try{process.kill(pid,'SIGKILL');}catch{}for(const pid of owned.keys()){if(signaled.has(pid))continue;if(!signalGroup(pid,signal)||signal==='SIGKILL')signaled.add(pid);}}\nfunction settle(){\n if(!child||settling||!exited||!(killed||timedOut||closing))return;settling=true;\n const started=Date.now();let goneAt=0;\n const tick=()=>{\n let gone=false;try{gone=!signalGroup(child.pid,0);}catch{}\n const now=Date.now();if(gone&&!goneAt)goneAt=now;\n if((goneAt&&now-goneAt>=250)||now-started>=5000){\n forced=true;if(credit){const pending=credit;credit=undefined;pending.reject(Error('Owned output closed after cancellation'));}\n child.stdout.destroy();child.stderr.destroy();return;\n }\n settleTimer=setTimeout(tick,50);\n };\n settleTimer=setTimeout(tick,50);\n}\nasync function stop(){\n if(closing)return;closing=true;\n if(credit){outputFailed=true;const pending=credit;credit=undefined;pending.reject(Error('Owned output channel closed'));child?.stdout.resume();}\n try{signalOwned();}catch(error){closing=false;send({event:'error',message:'Owned cancellation remains pending: '+error.code});return;}\n settle();await childClosed;owned.clear();await manager?.reset();process.disconnect?.();\n}\nprocess.on('disconnect',stop);process.on('SIGTERM',stop);\nprocess.on('message',async message=>{try{\n if(message.type==='output-ack'){\n if(credit && credit.seq===message.seq){const pending=credit;credit=undefined;if(message.ok)pending.resolve();else{outputFailed=true;pending.reject(Error('Managed sink failed'));child?.stdout.resume();}}\n }else if(message.type==='init'){\n if(initialized)throw Error('Worker initialization is immutable');initialized=true;full=message.full;\n if(!full){({SandboxManager:manager}=await import(pathToFileURL(message.runtime)));const deps=manager.checkDependencies();if(!manager.isSupportedPlatform()||deps.errors?.length)throw Error('Unsupported macOS sandbox runtime');await manager.initialize(message.config,undefined,false);}\n send({event:'ready',proxyUrl:full?'':'http://srt:'+manager.getProxyAuthToken()+'@127.0.0.1:'+manager.getProxyPort()});\n }else if(message.type==='wrap'){\n if(!initialized||wrapped)throw Error('One command per worker');wrapped=true;\n const script=full?message.script:await manager.wrapWithSandbox(message.script,'/bin/bash');send({event:'wrapped',script});\n }else if(message.type==='execute'){\n if(!wrapped||child||closing)throw Error('Immutable worker already consumed');\n child=spawn('/bin/bash',['-c',message.script],{cwd:message.cwd,env:message.env,detached:true,stdio:['ignore','pipe','pipe']});\n const identity={pid:child.pid,token:randomUUID()};if(!identity.pid)throw Error('Missing trusted launch identity');\n owned.set(identity.pid,identity.token);\n childClosed=new Promise(resolve=>child.once('close',async code=>{clearTimeout(timer);clearTimeout(settleTimer);await outputDone;send({event:'completed',code,timedOut,killed,outputFailed});resolve();}));\n child.once('error',error=>send({event:'error',message:String(error)}));\n child.once('exit',code=>{exited=true;send({event:'process-exit',code,timedOut,killed});try{signalOwned();}catch(error){send({event:'error',message:'Owned group cleanup pending: '+error.code});}settle();});\n if(message.managed){\n if(child.stdout.readableHighWaterMark>65536)throw Error('Unbounded managed producer buffer');\n outputDone=collect(child.stdout);let diagnosticBytes=0;child.stderr.on('data',bytes=>{diagnosticBytes+=bytes.length;if(diagnosticBytes<=65536)send({event:'diagnostic',text:bytes.toString()});});\n }else for(const stream of ['stdout','stderr'])child[stream].on('data',bytes=>{child[stream].pause();if(!process.connected){child[stream].resume();return;}process.send({event:'output',stream,data:bytes.toString('base64')},()=>child[stream].resume());});\n timer=setTimeout(()=>{timedOut=true;try{signalOwned();}catch(error){send({event:'error',message:'Owned timeout cancellation pending: '+error.code});}settle();},message.timeoutMs);\n send({event:'launched',...identity});\n }else if(message.type==='cancel'){\n killed=true;try{if(message.graceMs>0&&child){signalOwned('SIGTERM');const force=setTimeout(()=>{try{signalOwned();}catch(error){send({event:'error',message:'Owned graceful cancellation pending: '+error.code});}},message.graceMs);childClosed.finally(()=>clearTimeout(force));}else signalOwned();send({event:'cancelled',ok:true});}catch(error){send({event:'cancelled',ok:false,message:'Owned cancellation pending: '+error.code});}settle();\n }else if(message.type==='register'){\n if(!Number.isSafeInteger(message.pid)||message.pid<=1||typeof message.token!=='string')throw Error('Invalid trusted launch identity');\n owned.set(message.pid,message.token);send({event:'registered'});\n }else if(message.type==='release'){\n if(owned.get(message.pid)!==message.token)throw Error('Owned launch identity mismatch');owned.delete(message.pid);send({event:'released'});\n }else if(message.type==='stop')await stop();\n}catch(error){send({event:'error',message:String(error)});await stop();}});";
|
|
97
100
|
/** A separate process owns each immutable SRT manager; Full never enters that process. */
|
|
98
101
|
export declare function startMacOperationWorker(request: MacWorkerRequest, signal: AbortSignal): Promise<MacWorkerHandle>;
|
|
99
102
|
export {};
|
|
@@ -123,6 +123,9 @@ export const JAVA_PROXY_AGENT_JAR = "vendor/java-proxy-agent/srt-proxy-agent.jar
|
|
|
123
123
|
* kills that tree and the owned groups. Once the launched process has exited and its group is
|
|
124
124
|
* gone, `settle` closes the stdio pipes after a short bounded grace, so a process that escaped
|
|
125
125
|
* (one reparented to launchd before the walk) cannot hold the call or the worker open.
|
|
126
|
+
* Darwin answers a group signal with EPERM (not ESRCH) while the group holds only dead members
|
|
127
|
+
* (zombies not yet reaped, or processes exiting), so `signalGroup` counts EPERM as gone when a
|
|
128
|
+
* process snapshot shows no live member of the group; EPERM with a live member still fails.
|
|
126
129
|
*/
|
|
127
130
|
export const WORKER = `import {pathToFileURL} from 'node:url';
|
|
128
131
|
import {spawn,spawnSync} from 'node:child_process';
|
|
@@ -156,12 +159,19 @@ function stopTree(){
|
|
|
156
159
|
}
|
|
157
160
|
return [...tree];
|
|
158
161
|
}
|
|
159
|
-
function
|
|
162
|
+
function deadGroup(pgid){
|
|
163
|
+
const ps=spawnSync('/bin/ps',['-axo','pgid=,stat='],{encoding:'utf8',timeout:5000});
|
|
164
|
+
if(ps.status!==0)return false;
|
|
165
|
+
for(const line of ps.stdout.split('\\n')){const [group,stat='']=line.trim().split(/\\s+/);if(Number(group)===pgid&&!stat.startsWith('Z')&&!stat.includes('E'))return false;}
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
function signalGroup(pgid,signal){try{process.kill(-pgid,signal);return true;}catch(error){if(error.code==='ESRCH'||(error.code==='EPERM'&&deadGroup(pgid)))return false;throw error;}}
|
|
169
|
+
function signalOwned(signal='SIGKILL'){if(signal==='SIGKILL')for(const pid of stopTree())try{process.kill(pid,'SIGKILL');}catch{}for(const pid of owned.keys()){if(signaled.has(pid))continue;if(!signalGroup(pid,signal)||signal==='SIGKILL')signaled.add(pid);}}
|
|
160
170
|
function settle(){
|
|
161
171
|
if(!child||settling||!exited||!(killed||timedOut||closing))return;settling=true;
|
|
162
172
|
const started=Date.now();let goneAt=0;
|
|
163
173
|
const tick=()=>{
|
|
164
|
-
let gone=
|
|
174
|
+
let gone=false;try{gone=!signalGroup(child.pid,0);}catch{}
|
|
165
175
|
const now=Date.now();if(gone&&!goneAt)goneAt=now;
|
|
166
176
|
if((goneAt&&now-goneAt>=250)||now-started>=5000){
|
|
167
177
|
forced=true;if(credit){const pending=credit;credit=undefined;pending.reject(Error('Owned output closed after cancellation'));}
|