@remoteshell/device 0.1.0-beta.11 → 0.1.0-beta.17
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/NOTICE +17 -1
- package/bin/ci-backed-update-approval.mjs +58 -0
- package/bin/dev-agent-client.mjs +1 -1
- package/bin/dev-agent-runner.mjs +28 -4
- package/bin/dev-api-client.mjs +0 -0
- package/bin/dev-auto-worker.mjs +2 -2
- package/bin/dev-browser-open.mjs +0 -0
- package/bin/dev-dogfood-read.mjs +0 -0
- package/bin/dev-heartbeat-service.mjs +0 -0
- package/bin/dev-pairing-client.mjs +0 -0
- package/bin/dev-secrets.mjs +0 -0
- package/bin/dev-setup-recovery.mjs +0 -0
- package/bin/dev-signer-pin.mjs +0 -0
- package/bin/device.mjs +2 -2
- package/bin/direct-npx-runtime.mjs +61 -10
- package/bin/enrollment-client.mjs +0 -0
- package/bin/install-acquire.mjs +0 -0
- package/bin/install-integrity.mjs +0 -0
- package/bin/install-plan.mjs +0 -0
- package/bin/lifecycle.mjs +0 -0
- package/bin/native-path-contract.mjs +0 -0
- package/bin/remoteshell-device-install.sh +0 -0
- package/bin/remoteshell-easy-install.sh +0 -0
- package/bin/remoteshell-npx-entry.ps1 +54 -0
- package/bin/remoteshell-npx-entry.sh +34 -0
- package/bin/safe-update-artifact.mjs +61 -0
- package/bin/safe-update-contract.mjs +78 -0
- package/bin/safe-update-stage.mjs +62 -0
- package/bin/safe-update-transition.mjs +50 -0
- package/bin/windows-acl-wmi-client.mjs +35 -9
- package/bin/windows-credential-boundary.mjs +6 -5
- package/bin/windows-direct-autostart-runner.mjs +57 -9
- package/bin/windows-direct-autostart.mjs +0 -0
- package/bin/windows-install-layout.mjs +0 -0
- package/bin/windows-native-installer.mjs +1 -1
- package/bin/windows-private-store.mjs +10 -10
- package/bin/windows-safe-update-coordinator.mjs +67 -0
- package/bin/windows-safe-update-journal.mjs +69 -0
- package/bin/windows-safe-update-pin.mjs +68 -0
- package/bin/windows-safe-update-stage.mjs +59 -0
- package/bin/windows-user-lifecycle.mjs +0 -0
- package/npm-shrinkwrap.json +407 -27
- package/package.json +5 -2
- package/shared/lib/contracts.mjs +24 -1
- package/shared/lib/dc-tool-catalog.mjs +7 -0
- package/src/config/l2-dev-oci-credential.mjs +1 -1
- package/src/connection/cp-heartbeat-bootstrap.mjs +24 -0
- package/src/connection/dev-cp-heartbeat-worker.mjs +39 -0
- package/src/connection/startup-native-proof.mjs +18 -0
- package/src/core/c1-worker.mjs +3 -3
- package/src/gateway-keepalive.mjs +6 -3
- package/src/main.mjs +60 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@remoteshell/device",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.17",
|
|
4
4
|
"description": "RemoteShell public beta device agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -19,7 +19,10 @@
|
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"@modelcontextprotocol/sdk": "1.32.1",
|
|
22
|
-
"@wonderwhy-er/desktop-commander": "0.3.
|
|
22
|
+
"@wonderwhy-er/desktop-commander": "0.3.4"
|
|
23
|
+
},
|
|
24
|
+
"overrides": {
|
|
25
|
+
"node-forge": "1.4.4"
|
|
23
26
|
},
|
|
24
27
|
"repository": {
|
|
25
28
|
"type": "git",
|
package/shared/lib/contracts.mjs
CHANGED
|
@@ -4,7 +4,30 @@ import {isSyntheticWriteName,validateSyntheticWriteTool} from './synthetic-write
|
|
|
4
4
|
const plain=x=>x!==null&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
|
|
5
5
|
function check(value,label){if(!plain(value))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid '+label);return value;}
|
|
6
6
|
const ident=(x,label)=>{if(typeof x!=='string'||!x||x.length>128)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid '+label);return x;};
|
|
7
|
-
|
|
7
|
+
// GHSA-mrhx-c7xc-m3w5: reject oversized nested arrays before untrusted tool
|
|
8
|
+
// arguments reach DC's Zod-3 MCP validators. This is a bounded defense-in-depth
|
|
9
|
+
// control, not a claim that the underlying vulnerable library was patched.
|
|
10
|
+
const MAX_TOOL_ARRAY_ELEMENTS=1024,MAX_TOOL_TOTAL_NODES=8192,MAX_TOOL_DEPTH=24;
|
|
11
|
+
export function assertBoundedToolArguments(args){
|
|
12
|
+
const pending=[[args,0]],visited=new Set();let nodes=0;
|
|
13
|
+
while(pending.length){
|
|
14
|
+
const [value,depth]=pending.pop();
|
|
15
|
+
if(++nodes>MAX_TOOL_TOTAL_NODES||depth>MAX_TOOL_DEPTH)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Tool arguments exceed structural limits');
|
|
16
|
+
if(value===null||typeof value!=='object')continue;
|
|
17
|
+
if(visited.has(value))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Circular tool arguments denied');
|
|
18
|
+
visited.add(value);
|
|
19
|
+
if(Array.isArray(value)){
|
|
20
|
+
if(value.length>MAX_TOOL_ARRAY_ELEMENTS)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Tool array exceeds limit');
|
|
21
|
+
for(const element of value)pending.push([element,depth+1]);
|
|
22
|
+
}else{
|
|
23
|
+
const keys=Object.keys(value);
|
|
24
|
+
if(keys.length>MAX_TOOL_ARRAY_ELEMENTS)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Tool object exceeds limit');
|
|
25
|
+
for(const key of keys)pending.push([value[key],depth+1]);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return args;
|
|
29
|
+
}
|
|
30
|
+
export function toolCall(value){check(value,'tool');const keys=Object.keys(value);if(keys.some(k=>!['name','arguments'].includes(k)))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid tool fields');ident(value.name,'tool name');check(value.arguments,'arguments');assertBoundedToolArguments(value.arguments);return {name:value.name,arguments:value.arguments};}
|
|
8
31
|
export function requestEnvelope(value){check(value,'request');return Object.freeze({request_id:ident(value.request_id,'request_id'),session_id:ident(value.session_id,'session_id'),tool:toolCall(value.tool),...(value.context===undefined?{}:{context:check(value.context,'context')})});}
|
|
9
32
|
export function resultEnvelope(value){check(value,'result');if(typeof value.ok!=='boolean')throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid result');return Object.freeze({request_id:ident(value.request_id,'request_id'),ok:value.ok,...(value.result===undefined?{}:{result:value.result}),...(value.error_code===undefined?{}:{error_code:ident(value.error_code,'error_code')})});}
|
|
10
33
|
export function sessionEnvelope(value){check(value,'session');return Object.freeze({session_id:ident(value.session_id,'session_id'),...(value.context===undefined?{}:{context:check(value.context,'context')})});}
|
|
@@ -42,6 +42,13 @@ export async function discoverDcCatalog(client,{requestTimeoutMs=12000}={}){
|
|
|
42
42
|
}while(cursor);
|
|
43
43
|
return normalizeDcCatalog(tools);
|
|
44
44
|
}
|
|
45
|
+
// A failed discovery is not an authorization decision. Retry temporary DC
|
|
46
|
+
// delays sooner, without spinning or ever publishing an unverified catalog.
|
|
47
|
+
export function dcCatalogRetryDelay(failures,{invalid=false}={}){
|
|
48
|
+
if(!Number.isSafeInteger(failures)||failures<0)throw Error('DC_CATALOG_RETRY_INVALID');
|
|
49
|
+
if(failures===0||invalid)return 60000;
|
|
50
|
+
return Math.min(60000,10000*2**Math.min(failures-1,3));
|
|
51
|
+
}
|
|
45
52
|
export function dcCatalogFingerprint(catalog){
|
|
46
53
|
return createHash('sha256').update(stable(catalog)).digest('hex');
|
|
47
54
|
}
|
|
@@ -27,7 +27,7 @@ export function readL2DevOciCredential(file,{lstat=lstatSync,readFile=readFileSy
|
|
|
27
27
|
stat.uid!==uid||(stat.mode&0o777)!==0o600||stat.size>8192)deny();
|
|
28
28
|
}
|
|
29
29
|
raw=readFile(file,'utf8');
|
|
30
|
-
}catch{deny();}
|
|
30
|
+
}catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
|
|
31
31
|
let data;
|
|
32
32
|
try{data=JSON.parse(raw);}catch{deny();}
|
|
33
33
|
const keys=Object.keys(data||{}).sort();
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Bounded startup recovery for an overloaded Windows CP heartbeat Worker.
|
|
2
|
+
// A timeout is not an ACL or credential denial. Every retry starts an
|
|
3
|
+
// independent Worker and repeats all native checks; never replay a tool call.
|
|
4
|
+
export async function initialCpHeartbeat(heartbeat,{
|
|
5
|
+
delay=ms=>new Promise(resolve=>setTimeout(resolve,ms)),
|
|
6
|
+
retryDelayMs=1500,maxAttempts=3,onRetry=()=>{}
|
|
7
|
+
}={}){
|
|
8
|
+
if(typeof heartbeat!=='function'||typeof delay!=='function'||typeof onRetry!=='function'||
|
|
9
|
+
!Number.isSafeInteger(retryDelayMs)||retryDelayMs<0||retryDelayMs>5000||
|
|
10
|
+
!Number.isSafeInteger(maxAttempts)||maxAttempts<1||maxAttempts>3)
|
|
11
|
+
throw Error('DEVICE_CP_BOOTSTRAP_INVALID');
|
|
12
|
+
for(let attempt=1;attempt<=maxAttempts;attempt++){
|
|
13
|
+
try{return await heartbeat()}
|
|
14
|
+
catch(error){
|
|
15
|
+
// Explicit Worker deadline is the ONLY transient class.
|
|
16
|
+
// ACL rejection, HTTP 401/403, bad signature, missing proof, and any
|
|
17
|
+
// unclassified exception stop immediately without another attempt.
|
|
18
|
+
if(error?.message!=='DEVICE_CP_HEARTBEAT_WORKER_TIMEOUT'||attempt===maxAttempts)throw error;
|
|
19
|
+
const waitMs=Math.min(10000,retryDelayMs*2**(attempt-1));
|
|
20
|
+
try{onRetry(Object.freeze({attempt,delay_ms:waitMs,reason:'worker_timeout'}))}catch{}
|
|
21
|
+
await delay(waitMs);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// #327 Windows CP heartbeat off-thread: retain native owner/DACL checks and
|
|
2
|
+
// atomic monotonic sequence reservation without blocking the DC event loop.
|
|
3
|
+
import {Worker,isMainThread,parentPort,workerData} from 'node:worker_threads';
|
|
4
|
+
import {devHeartbeatOnce} from '../../bin/dev-agent-client.mjs';
|
|
5
|
+
|
|
6
|
+
const FAILED=()=>Error('DEVICE_CP_HEARTBEAT_WORKER_FAILED');
|
|
7
|
+
const TIMEOUT=()=>Error('DEVICE_CP_HEARTBEAT_WORKER_TIMEOUT');
|
|
8
|
+
// A verified security rejection is never a reason to retry a credential proof.
|
|
9
|
+
// Only an elapsed worker deadline is classified as a transient availability issue.
|
|
10
|
+
export function cpHeartbeatInWorker(storageDir,{WorkerClass=Worker,timeoutMs=120000,
|
|
11
|
+
schedule=setTimeout,unschedule=clearTimeout}={}){
|
|
12
|
+
if(!isMainThread||typeof storageDir!=='string'||!storageDir||
|
|
13
|
+
!Number.isSafeInteger(timeoutMs)||timeoutMs<1000||timeoutMs>300000)throw FAILED();
|
|
14
|
+
return new Promise((resolve,reject)=>{
|
|
15
|
+
let worker,timer=null,finished=false;
|
|
16
|
+
const done=(kind)=>{
|
|
17
|
+
if(finished)return;
|
|
18
|
+
finished=true;
|
|
19
|
+
if(timer!==null)unschedule(timer);
|
|
20
|
+
try{void worker?.terminate?.()}catch{}
|
|
21
|
+
if(kind==='success')resolve();
|
|
22
|
+
else reject(kind==='timeout'?TIMEOUT():FAILED());
|
|
23
|
+
};
|
|
24
|
+
try{
|
|
25
|
+
worker=new WorkerClass(new URL(import.meta.url),{workerData:{storageDir}});
|
|
26
|
+
worker.once('message',message=>done(message?.ok===true?'success':message?.reason==='timeout'?'timeout':'failed'));
|
|
27
|
+
worker.once('error',()=>done('failed'));
|
|
28
|
+
worker.once('exit',()=>done('failed'));
|
|
29
|
+
timer=schedule(()=>done('timeout'),timeoutMs);
|
|
30
|
+
}catch{done('failed')}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if(!isMainThread&&parentPort){
|
|
35
|
+
void devHeartbeatOnce({storageDir:workerData.storageDir}).then(
|
|
36
|
+
()=>parentPort.postMessage({ok:true}),
|
|
37
|
+
error=>parentPort.postMessage(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT'?{ok:false,reason:'timeout'}:{ok:false})
|
|
38
|
+
);
|
|
39
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// #327: native Windows ACL checks may time out under high CPU contention.
|
|
2
|
+
// Retry only an explicit native timeout with a fresh independent proof.
|
|
3
|
+
export async function retryStartupNativeProof(proof,{os=process.platform,
|
|
4
|
+
wait=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onRetry=()=>{},
|
|
5
|
+
maxAttempts=6}={}){
|
|
6
|
+
if(typeof proof!=='function'||typeof wait!=='function'||typeof onRetry!=='function'||
|
|
7
|
+
!Number.isInteger(maxAttempts)||maxAttempts<1||maxAttempts>6)
|
|
8
|
+
throw Error('DEVICE_STARTUP_PROOF_INVALID');
|
|
9
|
+
for(let attempt=1;attempt<=maxAttempts;attempt++){
|
|
10
|
+
try{return await proof();}
|
|
11
|
+
catch(error){
|
|
12
|
+
if(os!=='win32'||error?.message!=='DEVICE_WINDOWS_ACL_TIMEOUT'||attempt===maxAttempts)
|
|
13
|
+
throw error;
|
|
14
|
+
try{onRetry(Object.freeze({attempt,reason:'native_acl_timeout'}))}catch{}
|
|
15
|
+
await wait(Math.min(12000,1500*2**(attempt-1)));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
package/src/core/c1-worker.mjs
CHANGED
|
@@ -39,8 +39,8 @@ stage='NOEXEC';
|
|
|
39
39
|
writeFileSync('/scratch/probe.txt','#!/bin/sh\nexit 0\n',{mode:0o700});
|
|
40
40
|
try{execFileSync('/scratch/probe.txt');fail();}catch(error){if(error.code!=='EACCES')throw error;}finally{unlinkSync('/scratch/probe.txt');}
|
|
41
41
|
stage='DC_PACKAGE';
|
|
42
|
-
const pkg=require.resolve('@wonderwhy-er/desktop-commander/package.json');if(require(pkg).version!=='0.3.
|
|
43
|
-
const client=new Client({name:'rs-c1-worker',version:'1.0.0'}),transport=new C1DcTransport({command:process.execPath,args:[join(dirname(pkg),'dist/index.js'),'--no-onboarding'],cwd:root,env:{PATH:'/usr/bin',HOME:home,TMPDIR:home+'/tmp',DO_NOT_TRACK:'1',CI:'1'},stderr:'pipe'});
|
|
42
|
+
const pkg=require.resolve('@wonderwhy-er/desktop-commander/package.json');if(require(pkg).version!=='0.3.4')fail();
|
|
43
|
+
const client=new Client({name:'rs-c1-worker',version:'1.0.0'}),transport=new C1DcTransport({command:process.execPath,args:['--max-old-space-size=512',join(dirname(pkg),'dist/index.js'),'--no-onboarding'],cwd:root,env:{PATH:'/usr/bin',HOME:home,TMPDIR:home+'/tmp',DO_NOT_TRACK:'1',CI:'1'},stderr:'pipe'});
|
|
44
44
|
stage='DC_CONNECT';startupStage('DC_CONNECT_BEGIN');
|
|
45
45
|
await client.connect(transport);
|
|
46
46
|
startupStage('DC_CONNECT_DONE');stage='MOUNT';
|
|
@@ -55,7 +55,7 @@ async function rollback(){
|
|
|
55
55
|
else{const temp=join(root,'.c1-rollback');writeFileSync(temp,before,{flag:'wx',mode:0o600});renameSync(temp,path);if(sha(readFileSync(path))!==sha(before))fail();}
|
|
56
56
|
pending=null;
|
|
57
57
|
}
|
|
58
|
-
stage='REQUEST';startupStage('READY_SEND');send({type:'ready',version:'0.3.
|
|
58
|
+
stage='REQUEST';startupStage('READY_SEND');send({type:'ready',version:'0.3.4'});
|
|
59
59
|
const lines=createInterface({input:process.stdin,crlfDelay:Infinity});
|
|
60
60
|
try{
|
|
61
61
|
for await(const line of lines){
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Gateway session liveness is independent of Desktop Commander discovery and tool calls.
|
|
2
2
|
// One authenticated heartbeat/recovery cycle at a time; never replay a DC tool request.
|
|
3
|
-
export function createGatewayKeepalive({heartbeat,recover,onFailure=()=>{},intervalMs=10000,
|
|
3
|
+
export function createGatewayKeepalive({heartbeat,recover,onFailure=()=>{},canRecover=()=>true,intervalMs=10000,
|
|
4
4
|
schedule=setInterval,unschedule=clearInterval,now=Date.now,random=Math.random}={}){
|
|
5
|
-
if(typeof heartbeat!=='function'||typeof recover!=='function'||
|
|
5
|
+
if(typeof heartbeat!=='function'||typeof recover!=='function'||typeof canRecover!=='function'||
|
|
6
6
|
!Number.isSafeInteger(intervalMs)||intervalMs<1000)throw Error('INVALID_KEEPALIVE');
|
|
7
7
|
let timer=null,inFlight=false,stopped=false,authorizationRejected=false,failures=0,retryAt=0;
|
|
8
8
|
const notify=error=>{try{onFailure(error)}catch{}};
|
|
@@ -17,7 +17,10 @@ export function createGatewayKeepalive({heartbeat,recover,onFailure=()=>{},inter
|
|
|
17
17
|
notify(error);
|
|
18
18
|
const code=/HTTP (\d{3})/.exec(String(error?.message||''))?.[1];
|
|
19
19
|
if(code==='401'){authorizationRejected=true;return}
|
|
20
|
-
|
|
20
|
+
// A stale CP proof can produce a temporary Gateway 403. Do not make
|
|
21
|
+
// that a permanent rejection or try to register before CP is fresh.
|
|
22
|
+
// The Gateway still validates every fresh recovery; no auth bypass.
|
|
23
|
+
if(!stopped&&(code==='403'||code==='503')&&canRecover()){
|
|
21
24
|
try{
|
|
22
25
|
await recover();
|
|
23
26
|
failures=0;
|
package/src/main.mjs
CHANGED
|
@@ -22,20 +22,31 @@ import {C1Supervisor} from './core/c1-supervisor.mjs';
|
|
|
22
22
|
import {createRuntimeTiming} from '../shared/lib/runtime-timing.mjs';
|
|
23
23
|
import {readL2DevOciCredential} from './config/l2-dev-oci-credential.mjs';
|
|
24
24
|
import {devHeartbeatOnce} from '../bin/dev-agent-client.mjs';
|
|
25
|
+
import {cpHeartbeatInWorker} from './connection/dev-cp-heartbeat-worker.mjs';
|
|
26
|
+
import {initialCpHeartbeat} from './connection/cp-heartbeat-bootstrap.mjs';
|
|
27
|
+
import {retryStartupNativeProof} from './connection/startup-native-proof.mjs';
|
|
25
28
|
import {devDogfoodTaskEnvelope,executeDevDogfoodTask} from './connection/dev-dogfood-task.mjs';
|
|
26
29
|
import {callOriginalDc,callOriginalDcGeneric} from './dc/dev-dc-relay.mjs';
|
|
27
30
|
import {isDcPublic} from '../shared/lib/dc-generic-policy.mjs';
|
|
28
|
-
import {discoverDcCatalog,dcCatalogFingerprint,diffDcCatalog} from '../shared/lib/dc-tool-catalog.mjs';
|
|
31
|
+
import {discoverDcCatalog,dcCatalogRetryDelay,dcCatalogFingerprint,diffDcCatalog} from '../shared/lib/dc-tool-catalog.mjs';
|
|
29
32
|
import {inspectDcAccessBoundary} from './dc/dc-access-readiness.mjs';
|
|
30
33
|
import {createDevDogfoodProcesses} from './connection/dev-dogfood-processes.mjs';
|
|
31
34
|
import {createRootScopeDiscovery,routeDiscoveredRootTask} from './connection/dev-root-scopes.mjs';
|
|
32
35
|
import {validateExclusionPolicy} from '../shared/lib/dev-root-exclusions.mjs';
|
|
33
36
|
|
|
37
|
+
// Fixed, non-sensitive stages: no user paths, commands, credentials, or tokens.
|
|
38
|
+
const startupTraceAt=Date.now();
|
|
39
|
+
function startupStage(stage){
|
|
40
|
+
if(process.env.RS_L2_DEV_AGENT==='true')
|
|
41
|
+
console.info('RS_S3_BOOT_STAGE',JSON.stringify({stage,elapsed_ms:Date.now()-startupTraceAt}));
|
|
42
|
+
}
|
|
43
|
+
startupStage('module_imports_done');
|
|
34
44
|
const require = createRequire(import.meta.url);
|
|
35
45
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
36
46
|
const binPackage = require.resolve('@wonderwhy-er/desktop-commander/package.json');
|
|
37
47
|
const {bin: binaries} = require(binPackage);
|
|
38
48
|
const desktopCommander = resolve(dirname(binPackage), binaries['desktop-commander']);
|
|
49
|
+
startupStage('dc_package_resolved');
|
|
39
50
|
const p2Mode = process.env.RS_P2_MODE === 'true';
|
|
40
51
|
const isolatedReadEnabled=p2Mode&&process.env.RS_55A_TEST_MODE==='true'&&Boolean(process.env.RS_55A_ROOT);
|
|
41
52
|
if(process.env.RS_L2_DEV_AGENT!==undefined&&!['true','false'].includes(process.env.RS_L2_DEV_AGENT))throw Error('Invalid RS_L2_DEV_AGENT');
|
|
@@ -64,7 +75,11 @@ if (process.env.RS_P2_MODE !== undefined && process.env.RS_P2_MODE !== 'true' &&
|
|
|
64
75
|
let p2Credential = null;
|
|
65
76
|
if (p2Mode) {
|
|
66
77
|
if(l2DevAgent&&l2DevCredentialFile){
|
|
67
|
-
|
|
78
|
+
startupStage('credential_acl_begin');
|
|
79
|
+
p2Credential=await retryStartupNativeProof(
|
|
80
|
+
()=>readL2DevOciCredential(absolutePath(l2DevCredentialFile,'RS_L2_DEV_CREDENTIAL_FILE')),
|
|
81
|
+
{onRetry:()=>startupStage('credential_acl_timeout_retry')});
|
|
82
|
+
startupStage('credential_acl_done');
|
|
68
83
|
}else{
|
|
69
84
|
p2Credential = readPrivateP2Credential(
|
|
70
85
|
absolutePath(process.env.RS_P2_DEVICE_CREDENTIAL_FILE, 'RS_P2_DEVICE_CREDENTIAL_FILE'));
|
|
@@ -76,11 +91,13 @@ const gatewayUrl = parseDeviceConfig({
|
|
|
76
91
|
RS_GATEWAY_URL: process.env.RS_GATEWAY_URL || `http://127.0.0.1:${process.env.RS_PORT || 18765}`,
|
|
77
92
|
}).gatewayUrl;
|
|
78
93
|
const endpoint = new URL(gatewayUrl);
|
|
94
|
+
startupStage('gateway_config_parsed');
|
|
79
95
|
// Public DEV Agent Gateway API is versioned independently of the internal transport.
|
|
80
96
|
const publicDevGateway = l2DevAgent && endpoint.protocol === 'https:' &&
|
|
81
97
|
endpoint.hostname === 'ailab-remoteshell.duckdns.org' && endpoint.pathname === '/gateway/v1/';
|
|
82
98
|
if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.username || endpoint.password ||
|
|
83
|
-
(endpoint.pathname !== '/' && !publicDevGateway
|
|
99
|
+
(endpoint.pathname !== '/' && !publicDevGateway &&
|
|
100
|
+
!(l2DevAgent && endpoint.protocol==='https:' && process.env.RS_CA_FILE && endpoint.pathname==='/gateway/v1/')) || endpoint.search || endpoint.hash) {
|
|
84
101
|
throw new Error('Invalid gateway URL');
|
|
85
102
|
}
|
|
86
103
|
const localHosts = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
@@ -99,13 +116,16 @@ let boundedSearchRun=null;
|
|
|
99
116
|
let syntheticWriteSupervisor=null;
|
|
100
117
|
let devDogfoodProcesses=null;
|
|
101
118
|
let rootScopes=null;
|
|
119
|
+
startupStage('dc_transport_construct_begin');
|
|
102
120
|
const transport = new StdioClientTransport({
|
|
103
121
|
command: process.execPath,
|
|
104
|
-
|
|
122
|
+
// Bound a compromised Zod-3/DC parser's JS heap without mutating the DC package.
|
|
123
|
+
args: ['--max-old-space-size=512',desktopCommander, '--no-onboarding'],
|
|
105
124
|
stderr: 'pipe',
|
|
106
125
|
// Match RDC's original DC working-directory semantics (the DC binary folder).
|
|
107
126
|
cwd: dirname(desktopCommander),
|
|
108
127
|
});
|
|
128
|
+
startupStage('dc_transport_construct_done');
|
|
109
129
|
|
|
110
130
|
let sessionId = null;
|
|
111
131
|
let sessionRegisteredAt = 0;
|
|
@@ -177,7 +197,13 @@ async function post(path, payload, timeout = 6000) {
|
|
|
177
197
|
return response.json();
|
|
178
198
|
}
|
|
179
199
|
|
|
180
|
-
let dcCatalog=null,dcCatalogCheckedAt=0,dcCatalogPublishedHash=null;
|
|
200
|
+
let dcCatalog=null,dcCatalogCheckedAt=0,dcCatalogPublishedHash=null,dcCatalogFailures=0,dcCatalogInvalid=false;
|
|
201
|
+
const startupAt=Date.now();
|
|
202
|
+
function diagnostic(stage,detail={}){
|
|
203
|
+
console.info('RS_S3_STARTUP_DIAGNOSTIC',JSON.stringify({stage,pid:process.pid,ppid:process.ppid,
|
|
204
|
+
device_ref:deviceId.slice(0,8),elapsed_ms:Date.now()-startupAt,
|
|
205
|
+
catalog_ready:Array.isArray(dcCatalog),catalog_published:dcCatalogPublishedHash!==null,...detail}));
|
|
206
|
+
}
|
|
181
207
|
async function publishDcCatalog(){
|
|
182
208
|
if(!sessionId||!dcCatalog)return;
|
|
183
209
|
const fingerprint=dcCatalogFingerprint(dcCatalog);
|
|
@@ -186,17 +212,20 @@ async function publishDcCatalog(){
|
|
|
186
212
|
const reply=await post('/device/catalog',{fingerprint,tools:dcCatalog},10000);
|
|
187
213
|
if(reply?.accepted!==true||reply.fingerprint!==fingerprint)throw Error('DC_CATALOG_NOT_ACKNOWLEDGED');
|
|
188
214
|
dcCatalogPublishedHash=fingerprint;
|
|
215
|
+
diagnostic('catalog_accepted',{count:dcCatalog.length});
|
|
189
216
|
console.info('RS_DC_CATALOG_ACCEPTED',JSON.stringify({count:dcCatalog.length,fingerprint}));
|
|
190
217
|
}catch{console.warn('RS_DC_CATALOG_DELIVERY_FAILED');}
|
|
191
218
|
}
|
|
192
219
|
async function refreshDcCatalog({force=false}={}){
|
|
193
|
-
if(!force&&Date.now()-dcCatalogCheckedAt<
|
|
220
|
+
if(!force&&Date.now()-dcCatalogCheckedAt<
|
|
221
|
+
dcCatalogRetryDelay(dcCatalogFailures,{invalid:dcCatalogInvalid}))return;
|
|
194
222
|
dcCatalogCheckedAt=Date.now();
|
|
195
223
|
const checkedAt=Date.now();
|
|
224
|
+
diagnostic('catalog_discovery_begin');
|
|
196
225
|
try{
|
|
197
226
|
// Windows DC startup and concurrent access inspection can delay first tools/list.
|
|
198
227
|
// Bound the wait without replacing or modifying original DC behavior.
|
|
199
|
-
const next=await discoverDcCatalog(client,{requestTimeoutMs:process.platform==='win32'?
|
|
228
|
+
const next=await discoverDcCatalog(client,{requestTimeoutMs:process.platform==='win32'?60000:12000});
|
|
200
229
|
console.info('RS_DC_DISCOVERY_TIMING',JSON.stringify({result:'ok',duration_ms:Date.now()-checkedAt,device_ref:deviceId.slice(0,8)}));
|
|
201
230
|
const diff=diffDcCatalog(dcCatalog||[],next);
|
|
202
231
|
const fingerprint=dcCatalogFingerprint(next);
|
|
@@ -208,9 +237,18 @@ async function refreshDcCatalog({force=false}={}){
|
|
|
208
237
|
published:false
|
|
209
238
|
}));
|
|
210
239
|
dcCatalog=next;
|
|
240
|
+
dcCatalogFailures=0;
|
|
241
|
+
dcCatalogInvalid=false;
|
|
242
|
+
dcCatalogCheckedAt=Date.now();
|
|
243
|
+
diagnostic('catalog_discovered',{count:next.length,discovery_ms:Date.now()-checkedAt});
|
|
211
244
|
if(sessionId)await publishDcCatalog();
|
|
212
245
|
}catch(error){
|
|
246
|
+
dcCatalogFailures=Math.min(dcCatalogFailures+1,4);
|
|
247
|
+
dcCatalogInvalid=error?.message==='DC_CATALOG_INVALID';
|
|
248
|
+
dcCatalogCheckedAt=Date.now();
|
|
249
|
+
diagnostic('catalog_retry_scheduled',{retry_ms:dcCatalogRetryDelay(dcCatalogFailures,{invalid:dcCatalogInvalid})});
|
|
213
250
|
console.warn('RS_DC_DISCOVERY_TIMING',JSON.stringify({result:'failed',duration_ms:Date.now()-checkedAt,device_ref:deviceId.slice(0,8)}));
|
|
251
|
+
diagnostic('catalog_discovery_failed',{discovery_ms:Date.now()-checkedAt,error_type:error?.message==='DC_CATALOG_INVALID'?'invalid':'unavailable'});
|
|
214
252
|
console.warn('RS_DC_CATALOG_UNAVAILABLE',error?.message==='DC_CATALOG_INVALID'?
|
|
215
253
|
'INVALID':'DISCOVERY_FAILED');
|
|
216
254
|
}
|
|
@@ -223,7 +261,8 @@ async function refreshCpHeartbeat(){
|
|
|
223
261
|
if(Date.now()-lastCpHeartbeat<(process.platform==='win32'?1000:15000))return;
|
|
224
262
|
cpHeartbeatInFlight=(async()=>{
|
|
225
263
|
try{
|
|
226
|
-
await
|
|
264
|
+
if(process.platform==='win32')await cpHeartbeatInWorker(dirname(l2DevCredentialFile));
|
|
265
|
+
else await devHeartbeatOnce({storageDir:dirname(l2DevCredentialFile)});
|
|
227
266
|
lastCpHeartbeat=Date.now();
|
|
228
267
|
console.log('L2_CP_HEARTBEAT_OK');
|
|
229
268
|
}catch(error){
|
|
@@ -241,6 +280,7 @@ async function register(){
|
|
|
241
280
|
if(stopping)return;
|
|
242
281
|
sessionId=response.session_id;
|
|
243
282
|
sessionRegisteredAt=Date.now();
|
|
283
|
+
diagnostic('gateway_registered',{session_ref:sessionId.slice(0,8)});
|
|
244
284
|
console.info('RS_GATEWAY_SESSION_REGISTERED',JSON.stringify({device_ref:deviceId.slice(0,8),session_ref:sessionId.slice(0,8)}));
|
|
245
285
|
dcCatalogPublishedHash=null;
|
|
246
286
|
await publishDcCatalog();
|
|
@@ -278,9 +318,11 @@ async function execute(taskValue,exclusion_policy) {
|
|
|
278
318
|
const a=task.tool.arguments;
|
|
279
319
|
if(!isDcPublic(task.tool.name))throw Error('DC_RELAY_DENIED');
|
|
280
320
|
// Original Desktop Commander alone handles file/command permissions.
|
|
321
|
+
diagnostic('dc_relay_begin',{request_ref:task.request_id.slice(0,8),tool:task.tool.name});
|
|
281
322
|
const output=await callOriginalDcGeneric({client,name:task.tool.name,args:a.dc_args,
|
|
282
323
|
catalog:dcCatalog,onTrace:e=>console.log('RS_DC_RELAY',
|
|
283
324
|
JSON.stringify({request_id:task.request_id,...e}))});
|
|
325
|
+
diagnostic('dc_relay_result',{request_ref:task.request_id.slice(0,8),tool:task.tool.name,is_error:output.isError===true});
|
|
284
326
|
return JSON.stringify(output);
|
|
285
327
|
}
|
|
286
328
|
const result=await executeDevDogfoodTask({tool:task.tool,rootId:selectedRootId,root:selectedRoot,
|
|
@@ -325,8 +367,10 @@ async function reportResult(task, result) {
|
|
|
325
367
|
|
|
326
368
|
async function run() {
|
|
327
369
|
try {
|
|
370
|
+
diagnostic('dc_connect_begin');
|
|
328
371
|
await client.connect(transport);
|
|
329
372
|
connected = true;
|
|
373
|
+
diagnostic('dc_transport_connected');
|
|
330
374
|
if(isolatedReadEnabled&&!l2DevAgent)isolatedReadRun=makeVerifiedIsolatedReadAdapter({root:process.env.RS_55A_ROOT,client});
|
|
331
375
|
if(l2DevAgent&&d1RootId){
|
|
332
376
|
rootScopes=createRootScopeDiscovery({deviceId,legacyRootId:d1RootId,legacyRoot:d1Root});
|
|
@@ -342,11 +386,14 @@ async function run() {
|
|
|
342
386
|
await syntheticWriteSupervisor.ready();
|
|
343
387
|
}
|
|
344
388
|
console.log('Device connected to Desktop Commander stdio');
|
|
345
|
-
await refreshCpHeartbeat
|
|
389
|
+
if(process.platform==='win32')await initialCpHeartbeat(refreshCpHeartbeat,{
|
|
390
|
+
onRetry:({attempt,delay_ms,reason})=>diagnostic('cp_heartbeat_retry',{attempt,delay_ms,reason})});
|
|
391
|
+
else await refreshCpHeartbeat();
|
|
346
392
|
await register();
|
|
347
393
|
gatewayKeepalive=createGatewayKeepalive({
|
|
348
394
|
heartbeat:()=>post('/device/heartbeat',{}),
|
|
349
395
|
recover:()=>register(),
|
|
396
|
+
canRecover:()=>lastCpHeartbeat>0&&Date.now()-lastCpHeartbeat<15000,
|
|
350
397
|
onFailure:error=>console.warn('RS_GATEWAY_KEEPALIVE',/HTTP \d+/.exec(String(error?.message))?.[0]||'NETWORK_ERROR')
|
|
351
398
|
});
|
|
352
399
|
gatewayKeepalive.start();
|
|
@@ -413,9 +460,10 @@ async function run() {
|
|
|
413
460
|
if (stopping) break;
|
|
414
461
|
console.error('device connection:', /HTTP \d+/.exec(String(error.message))?.[0] || 'NETWORK_ERROR');
|
|
415
462
|
failures = Math.min(failures + 1, 6);
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
463
|
+
// Gateway session recovery has one owner: gatewayKeepalive. The poll
|
|
464
|
+
// loop must not independently re-register on 403/503, as it can replace
|
|
465
|
+
// the newly recovered session while a previous poll is still in flight.
|
|
466
|
+
// Keep the normal bounded poll retry, but never replay a DC request.
|
|
419
467
|
}
|
|
420
468
|
if (!stopping) await new Promise(resolveDelay => setTimeout(resolveDelay, Math.min(5000, 200 * 2 ** failures)));
|
|
421
469
|
}
|