#!/usr/bin/env node /** * JesusOS ORIGINAL Android Termux → optional v13 recoverable supervisor with adaptive 15-minute ceiling * * --audit: STRICTLY READ ONLY; no downloads, child processes or pool requests. * --selftest: local SHA256 / source-config sanity only. * --run: conscious owner opt-in to the original 2-hour bounded session. * --run-extended: explicit owner opt-in to an 8-hour monitored session. * --run-week: EXPLICIT local opt-in for one 168-hour session; no reboot persistence * or remote wake, and self-throttling can skip or abort work at any time. * LOCAL recovery only: while THIS owner-opted-in parent survives, it may * restart its own unexpectedly exited reporting child at most 3 times, * after source, bearer, battery and idle-relay preflight checks. No second * miner is spawned, no reboot/Termux wake, token persistence or remote shell. * * Keeps original 3340 status reporter, auto-reporter and HeavenCoin UNTOUCHED. * Only opens 127.0.0.1:3334 (pool relay) and 127.0.0.1:3345 (status). * Uses existing exact watch-only first address and existing 0600 pool config. * Uses a SHORT 16-character, owner-issued, single-use pairing code (10 min TTL). * The code is exchanged over JesusOS HTTPS for a private device credential, * held in memory only. No 69-character token copied, no wallet keys, and * original 3340 reporter is never touched. Explicit owner opt-in only. * Without an active dedicated device token, launch FAILS CLOSED: no * repeated local-only CPU mining test. A read-only JesusOS HTTPS pairing * check must succeed BEFORE starting any mining process. * Local port and signed-source preflight finishes BEFORE asking for or * consuming a one-use device code. Failure preserves existing pairing. * With EXPLICIT original 15-minute device authorization, opted-in agent polls MAIN, receives at * most one bounded 90s 5000 H/s command per UTC quarter-hour, with >=15min * spacing between claimed missions. Requires a verified Termux:API battery * reading before and DURING local mining; local governor SKIPS work as the * battery warms, reduces to 30-minute spacing when warm, and applies * a cooldown after heat / low battery / sensor failures. No battery charging * control, no CPU thermal identity guarantee, and no Android auto-restart. * ORIGINAL v9 remains installed and works unchanged with one per UTC hour. * Mining stops on Ctrl+C, process failure or at 2h (default) / 8h * (explicit extended session) / 168h (separate explicit week choice). Each CPU work order stays capped at * 90 seconds, 5,000 H/s and at most one work order per UTC quarter-hour. * No persistent token, automatic Android boot, shell execution or payout promise. */ import fs from 'node:fs'; import fsp from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import crypto from 'node:crypto'; import {spawn,execFile} from 'node:child_process'; import net from 'node:net'; const home=process.env.HOME||os.homedir(); const original=path.join(home,'jesusos-bitcoin-mining'); const watchDir=path.join(home,'jesusos-sovereign-wallet'); const cache=path.join(original,'.jesusos-live-pinned-v1'); const PINS={ proxy:{name:'jesusos-stratum-proxy-v1.txt',sha:'5fa74b2366c8ef8d4c7885c9885237fe0ea2d9db36821ce42a72edb9223c45a3'}, miner:{name:'jesusos-owner-cpu-miner-v1.txt',sha:'2cdc072de0f8915250651bca8aae2853136e244fe4373e4926455b2f16f554c4'}, agent:{name:'jesusos-mining-device-agent-v8.txt',sha:'3a45562234dffece88c9e5bf13a116988196415cc3c5cc966aa3013517b64782'} }; const sha=b=>crypto.createHash('sha256').update(b).digest('hex'); const timestamp=()=>new Date().toISOString(); const log=(event,more={})=>console.log(JSON.stringify({at:timestamp(),event,...more})); const tokenPattern=/^jmr1_[0-9a-f]{64}$/; const mainFile=path.join(original,'jesusos-pool-settings.env'); const watchFile=path.join(watchDir,'watch.json'); const safeDirectory=(d,onlyOwner=false)=>{ const s=fs.lstatSync(d); if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&(onlyOwner?0o077:0o022))!==0) throw Error('Unsafe or non-directory original workspace: '+path.basename(d)); }; function privateFile(filename,max=8192){ const s=fs.lstatSync(filename); if(!s.isFile()||s.isSymbolicLink()||(s.mode&0o077)!==0||s.size>max) throw Error('Original public-config file missing safe 0600 permissions or valid type: '+path.basename(filename)); return fs.readFileSync(filename,'utf8'); } function parsePool(text){ const fields=new Map(); for(const line of text.split(/\r?\n/)){ if(!line.trim()||line.startsWith('#'))continue; const m=line.match(/^([A-Z][A-Z0-9_]*)=([^\r\n]*)$/); if(!m||fields.has(m[1]))throw Error('Pool settings malformed or duplicated; no mining started.'); fields.set(m[1],m[2]); } const pool={ host:fields.get('STRATUM_HOST'),port:fields.get('STRATUM_PORT'), tls:fields.get('STRATUM_TLS'),worker:fields.get('STRATUM_WORKER') }; if(pool.host!=='stratum.ckpool.org'||pool.port!=='3333'||pool.tls!=='false'|| typeof pool.worker!=='string'||!/^bc1q[a-z0-9]{38,85}$/.test(pool.worker)) throw Error('Original public CKPool configuration does not meet pinned solo-mainnet requirements.'); return pool; } function validatePayout(){ safeDirectory(original); safeDirectory(watchDir,true); const settings=parsePool(privateFile(mainFile)); const data=JSON.parse(privateFile(watchFile,16384)); if(!data||data.schema!=='jesusos.btc.watchonly.bip84.v1'|| data.network!=='mainnet'||typeof data.firstAddress!=='string'|| typeof data.accountXpub!=='string'||!data.accountXpub.startsWith('xpub')) throw Error('Original watch-only manifest invalid. Original wallet never modified.'); if(settings.worker!==data.firstAddress) throw Error('Pool payout worker does NOT match original watch-only receive address. Refusing to mine.'); return settings; } async function canListen(port){ return new Promise(resolve=>{ const s=net.createServer(); s.on('error',()=>resolve(false)); s.listen(port,'127.0.0.1',()=>s.close(()=>resolve(true))); }); } function secretCheck(){ const direct=process.env.JESUSOS_MINING_DEVICE_TOKEN||''; if(direct&&!tokenPattern.test(direct))throw Error('Dedicated device token has invalid format; no mining started.'); return direct||null; } /** Private original Termux short-code prompt. Accept ONLY 16 owner-issued * uppercase base32 characters. No terminal echo. No shell command can be * interpreted as a pairing code. Ctrl+C cancels all operations. */ const pairCodePattern=/^[A-HJ-NP-Z2-9]{16}$/; async function readShortDevicePairCode(){ const input=process.stdin; if(!input.isTTY||!process.stdout.isTTY||typeof input.setRawMode!=='function') return null; process.stdout.write('PASTE 16-character JesusOS pairing CODE ONLY (not command, Enter=submit, Ctrl+C=cancel): '); const previousRaw=Boolean(input.isRaw); return new Promise((resolve,reject)=>{ let code='',finished=false; function cleanup(){ if(finished)return; finished=true; input.off('data',onData); try{input.setRawMode(previousRaw)}catch{} if(!previousRaw)input.pause(); process.stdout.write('\n'); } function onData(chunk){ for(const ch of String(chunk)){ if(ch==='\r'||ch==='\n'){ cleanup(); if(!pairCodePattern.test(code))reject(Error('Expected exactly 16 pairing-code letters/digits FROM JesusOS. Do NOT paste a shell command or the 69-character token here.')); else resolve(code); return; } if(ch==='\u0003'){cleanup();reject(Error('Operator cancelled pairing; no mining started.'));return} if(ch==='\u007f'||ch==='\b'){code=code.slice(0,-1);continue} if(ch==='\u001b'){cleanup();reject(Error('Unexpected terminal escape; pairing cancelled.'));return} if(ch===' '||ch==='-')continue; if(ch>='!'&&ch<='~'){ if(code.length>=24){ cleanup();reject(Error('This prompt takes ONLY the 16-character pairing code shown in JesusOS—not a shell command. Nothing started.'));return; } code+=ch.toUpperCase(); } } } try{input.setRawMode(true);input.setEncoding('utf8');input.on('data',onData);input.resume()} catch{cleanup();reject(Error('Private terminal input unavailable. No miner started.'))} }); } /** Claim a one-use high-entropy short code; only server returns device * credential over HTTPS, in memory. Old 3340 reporter remains valid. */ async function claimShortCode(code){ const body=JSON.stringify({schema:'jesusos.bitcoin.device-short-claim.v1',code, mode:'opt-in-15m-v1'}); let response; try{ response=await fetch('https://jesusos.online/_api/bitcoin-mining-device-short-claim',{ method:'POST',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(12000), headers:{'Content-Type':'application/json'},body }); }catch{throw Error('JesusOS pairing network unavailable. Nothing started. Generate a new short code and retry.')} if(!response.ok){ throw Error('Short pairing code was invalid, expired or already used (HTTP '+response.status+'). No mining started. Generate a new code in JesusOS.'); } let data; try{data=await response.json()}catch{throw Error('Unexpected pairing response; no mining started')} if(!data||data.schema!=='jesusos.bitcoin.device-short-claim.v1'|| data.authorized!==true||!tokenPattern.test(data.token)|| data.originalLegacyReporterUnchanged!==true||data.noWalletKeysUsed!==true|| data.bitcoinPayoutVerified!==false||data.scope!=='bounded-cpu-stratum'|| data.selectedDeviceCadence!=='15m') throw Error('Unexpected device authorization; no mining started'); log('owner_short_code_pairing_success',{legacyReporterPreserved:true,privateCredentialNotPrinted:true}); return data.token; } const mode=process.argv[2]||'--audit'; const activeMode=mode==='--run'||mode==='--run-extended'||mode==='--run-week'; const maxSessionHours=mode==='--run-week'?168:mode==='--run-extended'?8:2; if(mode==='--selftest'){ if(sha('abc')!=='ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') throw Error('SHA256 selftest failed.'); if(Object.values(PINS).length!==3||new Set(Object.values(PINS).map(x=>x.sha)).size!==3) throw Error('Pinned sources invalid.'); log('selftest_ok',{mode:'local-only',networkRequests:0,spawnedProcesses:0}); process.exit(0); } if(mode!=='--audit'&&!activeMode){ console.error('Use --audit, --selftest, --run (2h), --run-extended (8h), or --run-week (168h). Only explicit run modes can mine.'); process.exit(2); } let settings,token; try{ settings=validatePayout(); token=secretCheck(); // Prevent the device token from leaking into other spawned processes. delete process.env.JESUSOS_MINING_DEVICE_TOKEN; }catch(e){console.error('LIVE MINING REFUSED:',e instanceof Error?e.message:'Configuration invalid');process.exit(2)} const relayFree=await canListen(3334),statusFree=await canListen(3345); const report={ schema:'jesusos.bitcoin.termux-live-agent-readiness.v1', mode:mode==='--audit'?'READ_ONLY_AUDIT':'OPERATOR_OPT_IN', payoutMatchesOriginalWatchOnly:true, soloPool:'stratum.ckpool.org:3333', originalStatus3340:'UNTOUCHED', safeRelay3334Free:relayFree, safeStatus3345Free:statusFree, dedicatedDeviceCredentialProvided:!!token, sessionMaxHours:maxSessionHours, deviceCadence:'explicit-v11-opt-in-15m-v1', localBatterySafety:'Termux:API adaptive local governor, pause if warm/low or unavailable', actualReporterCredentialValueNeverPrinted:true, agentMode:token?'existing-device-credential-present': activeMode?'pairing-after-local-and-source-preflight':'not-authorized-no-mining', actualMinerRunning:false, bitcoinPayoutVerified:false, heavenCoinTouched:false }; console.log('=== JesusOS ORIGINAL Bitcoin LIVE miner activation ==='); console.log(JSON.stringify(report,null,2)); if(mode==='--audit'){ console.log('READ ONLY audit completed. No mining, source downloads, process signals or wallet changes.'); process.exit(0); } async function verifyDedicatedDevicePairing(credential){ const body=JSON.stringify({schema:'jesusos.bitcoin.device-pair-check.v1',action:'verify'}); let response; try{ response=await fetch('https://jesusos.online/_api/bitcoin-mining-device-pair',{ method:'POST',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(9000), headers:{'Content-Type':'application/json','Authorization':'Bearer '+credential}, body }); }catch{throw Error('Original device pairing service unavailable; no mining started')} if(!response.ok)throw Error('Dedicated device not authorized by JesusOS (HTTP '+response.status+'); no mining started'); let v; try{v=await response.json()}catch{throw Error('Pairing response invalid; no mining started')} if(!v||v.schema!=='jesusos.bitcoin.device-pair-check.v1'||v.authorized!==true|| v.scope!=='bounded-cpu-stratum'||v.originalLegacyReporterUnchanged!==true|| v.physicalDeviceAttested!==false||v.actualHashesVerified!==false|| v.bitcoinPayoutVerified!==false||v.heavenCoinMinted!==false|| v.selectedDeviceCadence!=='15m') throw Error('Unexpected pairing response; no mining started'); log('dedicated_device_pair_authorized',{oldReporterUnchanged:true,hardwareNotAttested:true,noPayoutInferred:true}); } if(!relayFree||!statusFree){ console.error('LIVE MINING REFUSED: reserved ports 3334 or 3345 occupied. Existing processes and unclaimed pairing code preserved. Inspect a prior V6 session before restarting.'); process.exit(3); } async function pinnedFile(entry){ await fsp.mkdir(cache,{recursive:true,mode:0o700}); safeDirectory(cache,true); const dest=path.join(cache,entry.name+'.mjs'); try{ const prior=await fsp.readFile(dest); const st=fs.lstatSync(dest); if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o077)!==0||sha(prior)!==entry.sha) throw Error('Pinned local cache file mismatch; original file preserved.'); return dest; }catch(e){if(e?.code!=='ENOENT')throw e} const response=await fetch('https://jesusos.online/'+entry.name,{ redirect:'error',signal:AbortSignal.timeout(12500),cache:'no-store' }); if(!response.ok)throw Error('Pinned original worker source unavailable: '+entry.name); const bytes=Buffer.from(await response.arrayBuffer()); if(bytes.length<1000||bytes.length>25000||sha(bytes)!==entry.sha) throw Error('Pinned source SHA-256 mismatch: '+entry.name+'; refusing execution.'); const tmp=dest+'.tmp.'+process.pid; await fsp.writeFile(tmp,bytes,{flag:'wx',mode:0o600}); if(sha(await fsp.readFile(tmp))!==entry.sha)throw Error('Temporary pinned source readback mismatch.'); await fsp.rename(tmp,dest); return dest; } let paths; try{ paths={ proxy:await pinnedFile(PINS.proxy), miner:await pinnedFile(PINS.miner), agent:await pinnedFile(PINS.agent) }; }catch(e){console.error('LIVE MINING REFUSED:',e instanceof Error?e.message:'source validation');process.exit(4)} /** No private pairing code is consumed unless the local battery sensor is * actually available and reports plausible safe values. This is an explicit * run-mode preflight only; --audit remains fully child-process free. */ async function requireLocalBatterySensor(){ return new Promise((resolve,reject)=>{ execFile('termux-battery-status',[],{timeout:5000,maxBuffer:4096}, (err,stdout)=>{ if(err){reject(Error('Termux:API battery sensor unavailable; install Termux:API and allow permissions BEFORE pairing.'));return;} try{ const b=JSON.parse(stdout); if(typeof b.temperature!=='number'||!Number.isFinite(b.temperature)|| !Number.isInteger(b.percentage)||b.temperature<10||b.temperature>60|| b.percentage<0||b.percentage>100||b.temperature>=38||b.percentage<30){ reject(Error('Battery temperature/charge unsafe or invalid; private pairing code not consumed.'));return; } resolve(true); }catch(e){reject(Error('Invalid battery sensor JSON; pairing code not consumed.'))} }); }); } // Local-only ports AND exact SHA-256 sources have been verified before // consuming the short code. Failed preflight must never revoke an earlier // device key or waste a one-use, ten-minute owner-issued pairing code. if(activeMode){ try{ await requireLocalBatterySensor(); log('local_battery_sensor_preflight_passed',{thermalAndChargeGuard:'eligible-to-supervise',chargingControl:false}); if(!token){ const code=await readShortDevicePairCode(); if(!code)throw Error('No short pairing code entered. No mining started.'); token=await claimShortCode(code); } await verifyDedicatedDevicePairing(token); }catch(e){console.error('LIVE MINING REFUSED:',e instanceof Error?e.message:'Device pairing failed');process.exit(5)} } let stopping=false; const children=new Set(); let agentProcess=null,recoveryTimer=null,recoveryAttempts=0; const MAX_AGENT_RECOVERIES=3; const AGENT_BACKOFF_MS=[120000,300000,600000]; const supervisorDeadline=Date.now()+maxSessionHours*60*60*1000; const spawnChild=(name,filename,env)=>{ const proc=spawn(process.execPath,[filename,name==='agent'?'--run':'--mine'],{ env,stdio:['ignore','inherit','inherit'] }); children.add(proc); proc.on('error',e=>{log('child_error',{name,code:e.code||'unknown'});stop('child-error')}); proc.on('exit',(code,signal)=>{children.delete(proc); log('child_exited',{name,code,signal:signal||null}); if(!stopping&&name!=='miner')stop('child-exited'); }); return proc; }; function stop(reason){ if(stopping)return; stopping=true; if(recoveryTimer!==null){clearTimeout(recoveryTimer);recoveryTimer=null;} log('live_agent_stopping',{reason,childProcesses:children.size, originalStatus3340:'preserved',heavenCoin:'preserved'}); for(const p of children){try{p.kill('SIGTERM')}catch{}} setTimeout(()=>{for(const p of children){try{p.kill('SIGKILL')}catch{}} process.exit(reason==='operator-signal'||reason==='planned-cap'?0:1) },4500).unref(); if(children.size===0)process.exit(reason==='operator-signal'||reason==='planned-cap'?0:1); } for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>stop('operator-signal')); const withoutToken={...process.env, STRATUM_HOST:settings.host,STRATUM_PORT:settings.port, STRATUM_TLS:settings.tls,STRATUM_WORKER:settings.worker, STRATUM_PASSWORD:'x', LOCAL_STRATUM_PORT:'3334',LOCAL_STRATUM_HOST:'127.0.0.1', STATUS_PORT:'3345',MAX_MINERS:'1'}; delete withoutToken.JESUSOS_MINING_REPORTER_TOKEN; delete withoutToken.JESUSOS_MINING_DEVICE_TOKEN; delete withoutToken.JESUSOS_DEVICE_ALLOW_MINING; delete withoutToken.JESUSOS_DEVICE_WORK_CADENCE; const proxy=spawn(process.execPath,[paths.proxy],{env:withoutToken, stdio:['ignore','inherit','inherit']}); children.add(proxy); proxy.on('error',e=>{log('proxy_failed',{code:e.code||'unknown'});stop('proxy-error')}); proxy.on('exit',(code,signal)=>{children.delete(proxy); if(!stopping){log('proxy_exited',{code,signal:signal||null});stop('proxy-exited')} }); const localStatus='http://127.0.0.1:3345/status'; async function getStatus(){ const r=await fetch(localStatus,{headers:{Host:'127.0.0.1:3345'}, cache:'no-store',signal:AbortSignal.timeout(1500)}); if(!r.ok)throw Error('Original live relay status unavailable.'); const j=await r.json(); if(j.schema!=='jesusos.stratum.telemetry.v1')throw Error('Unexpected original status schema.'); return j; } let ready=false; for(let i=0;i<45&&!stopping;i++){ try{await getStatus();ready=true;break}catch{await new Promise(r=>setTimeout(r,250))} } if(!ready){ console.error('LIVE MINING REFUSED: verified relay not available; 3340 and HeavenCoin preserved.'); stop('relay-unavailable'); }else if(!stopping){ log('real_pool_relay_ready',{host:'127.0.0.1',port:3334, statusPort:3345,officialPool:'stratum.ckpool.org:3333', agentMode:'authenticated'}); const monitor=setInterval(async()=>{ if(stopping){clearInterval(monitor);return} try{ const s=await getStatus(); log('live_status',{connected:s.minersConnected,authorized:s.authorized, poolJobs:s.jobs,sharesSubmitted:s.sharesSubmitted, sharesAccepted:s.sharesAccepted,sharesRejected:s.sharesRejected, verifiedBitcoinPayout:false}); }catch{log('live_status_unavailable')} },10000); monitor.unref(); const agentEnvironment={...withoutToken, JESUSOS_VERIFIED_MINER_PATH:paths.miner, JESUSOS_MINING_REPORTER_TOKEN:token, JESUSOS_DEVICE_ALLOW_MINING:'1', JESUSOS_DEVICE_WORK_CADENCE:'opt-in-15m-v1', JESUSOS_LOCAL_RECOVERY:'bounded-local-recovery-v13', JESUSOS_LOCAL_STATUS_URL:localStatus }; // Only the child sees the device reporter credential. The parent keeps // it in memory solely for THIS explicitly authorized local session. // A lost Android app / dead parent has no privileged remote restart path. function startDeviceAgent(trigger){ if(stopping||agentProcess)return; if(Date.now()>=supervisorDeadline){stop('planned-cap');return} const agent=spawn(process.execPath,[paths.agent,'--run'],{ env:agentEnvironment,stdio:['ignore','inherit','inherit'] }); agentProcess=agent;children.add(agent); log('device_agent_spawned',{trigger,sessionMaxHours:maxSessionHours, recoveryAttempts,credentialsPersisted:false}); let handled=false; const departed=(reason,code=null,signal=null)=>{ if(handled)return;handled=true; children.delete(agent); if(agentProcess===agent)agentProcess=null; log('device_agent_departed',{reason,code,signal,recoveryAttempts, originalPortsUntouched:true,operatorStopped:stopping}); if(!stopping)scheduleAgentRecovery(reason); }; agent.on('error',e=>departed('spawn-error',String(e?.code||'unknown'))); agent.on('exit',(code,signal)=>departed('unexpected-exit',code,signal||null)); } function scheduleAgentRecovery(reason){ if(stopping)return; if(agentProcess||recoveryTimer!==null)return; if(Date.now()>=supervisorDeadline){stop('planned-cap');return} if(recoveryAttempts>=MAX_AGENT_RECOVERIES){ log('device_recovery_exhausted',{reason,attempts:recoveryAttempts, nextAction:'owner-check-Termux; never remote-start'}); stop('agent-recovery-exhausted');return; } const delayMs=AGENT_BACKOFF_MS[recoveryAttempts++]; log('device_recovery_scheduled',{reason,attempt:recoveryAttempts, delaySeconds:delayMs/1000,backoffBounded:true}); recoveryTimer=setTimeout(async()=>{ recoveryTimer=null; if(stopping||agentProcess)return; if(Date.now()>=supervisorDeadline){stop('planned-cap');return} try{ if(!children.has(proxy))throw Error('original-relay-not-running'); const status=await getStatus(); if(!Number.isSafeInteger(status.minersConnected)||status.minersConnected!==0) throw Error('local-miner-not-idle; refusing-duplicate'); await requireLocalBatterySensor(); const st=fs.lstatSync(paths.agent); if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o077)!==0|| sha(await fsp.readFile(paths.agent))!==PINS.agent.sha) throw Error('pinned-device-agent-file-changed'); await verifyDedicatedDevicePairing(token); log('device_recovery_preflight_passed',{attempt:recoveryAttempts, noDuplicateMiner:true,pinnedSource:true,localBatteryCheck:true, ownerAuthorizationReusedInMemory:true}); startDeviceAgent('bounded-local-recovery'); }catch(e){ log('device_recovery_preflight_failed',{attempt:recoveryAttempts, reason:String(e instanceof Error?e.message:e).slice(0,110)}); scheduleAgentRecovery('local-preflight-refused'); } },delayMs); } startDeviceAgent('initial-owner-opt-in'); log('device_agent_enabled',{heartbeatSeconds:60,commandDurationCapSeconds:90, hashRateCap:5000,workOrdersPerUTCExpectedHour:4, requiredLocalSafety:'termux-battery-status; adaptive 15m cool, 30m warm, pause hot/low; abort at warming threshold', reporterCredential:'dedicated-device-token-never-displayed', sessionMaxHours:maxSessionHours}); const capMs=Math.max(0,supervisorDeadline-Date.now()); setTimeout(()=>stop('planned-cap'),capMs).unref(); }