@remoteshell/device 0.1.0-beta.1 → 0.1.0-beta.11
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/LICENSE +26 -0
- package/NOTICE +20 -0
- package/bin/dev-agent-client.mjs +228 -0
- package/bin/dev-agent-runner.mjs +60 -0
- package/bin/dev-api-client.mjs +31 -0
- package/bin/dev-auto-worker.mjs +25 -0
- package/bin/dev-browser-open.mjs +12 -0
- package/bin/dev-dogfood-read.mjs +3 -0
- package/bin/dev-heartbeat-service.mjs +77 -0
- package/bin/dev-pairing-client.mjs +63 -0
- package/bin/dev-secrets.mjs +33 -0
- package/bin/dev-setup-recovery.mjs +34 -0
- package/bin/dev-signer-pin.mjs +22 -0
- package/bin/device.mjs +254 -9
- package/bin/direct-npx-runtime.mjs +156 -0
- package/bin/install-acquire.mjs +89 -0
- package/bin/install-integrity.mjs +74 -0
- package/bin/install-plan.mjs +43 -0
- package/bin/native-path-contract.mjs +23 -0
- package/bin/remoteshell-device-install.cmd +17 -0
- package/bin/remoteshell-device-install.ps1 +17 -0
- package/bin/remoteshell-device-install.sh +15 -0
- package/bin/remoteshell-device-preflight.cmd +10 -0
- package/bin/remoteshell-device-preflight.ps1 +10 -0
- package/bin/remoteshell-easy-diagnose.ps1 +32 -0
- package/bin/remoteshell-easy-install.ps1 +292 -0
- package/bin/remoteshell-easy-install.sh +71 -0
- package/bin/remoteshell-easy-uninstall.ps1 +128 -0
- package/bin/windows-acl-wmi-client.mjs +50 -0
- package/bin/windows-acl-wmi.js +43 -0
- package/bin/windows-credential-boundary.mjs +113 -0
- package/bin/windows-direct-autostart-runner.mjs +50 -0
- package/bin/windows-direct-autostart.mjs +110 -0
- package/bin/windows-install-layout.mjs +28 -0
- package/bin/windows-native-installer.mjs +91 -0
- package/bin/windows-private-store.mjs +176 -0
- package/bin/windows-user-lifecycle.mjs +34 -0
- package/npm-shrinkwrap.json +8591 -0
- package/package.json +14 -5
- package/shared/lib/bounded-search-contract.mjs +5 -0
- package/shared/lib/dc-generic-policy.mjs +102 -0
- package/shared/lib/dc-relay-contract.mjs +42 -0
- package/shared/lib/dc-tool-catalog.mjs +67 -0
- package/shared/lib/dev-dc-relay-contract.mjs +20 -0
- package/shared/lib/dev-paged-output.mjs +32 -0
- package/shared/lib/dev-root-exclusions.mjs +56 -0
- package/{src/common → shared/lib}/synthetic-write-policy.mjs +0 -1
- package/src/config/l2-dev-oci-credential.mjs +39 -0
- package/src/config/p2-private-credential.mjs +15 -0
- package/src/connection/dev-dogfood-processes.mjs +25 -0
- package/src/connection/dev-dogfood-read.mjs +64 -0
- package/src/connection/dev-dogfood-task.mjs +113 -0
- package/src/connection/dev-dogfood-write.mjs +62 -0
- package/src/connection/dev-file-task.mjs +119 -0
- package/src/connection/dev-r4-file-task.mjs +56 -0
- package/src/connection/dev-read-tools.mjs +134 -0
- package/src/connection/dev-root-scopes.mjs +82 -0
- package/src/{device-agent → core}/c1-supervisor.mjs +9 -7
- package/src/{device-agent → core}/c1-worker.mjs +7 -7
- package/src/dc/dc-access-readiness.mjs +31 -0
- package/src/dc/dev-dc-relay.mjs +47 -0
- package/src/device-agent/main.mjs +1 -230
- package/src/gateway-keepalive.mjs +73 -0
- package/src/main.mjs +436 -0
- package/src/{common → policy}/bounded-search-adapter.mjs +2 -3
- package/src/{common → policy}/isolated-read-adapter.mjs +1 -1
- package/src/{common → policy}/isolated-read-mount.mjs +1 -1
- package/src/{common → policy}/synthetic-auxiliary-adapter.mjs +1 -1
- package/src/{common → policy}/synthetic-file-adapter.mjs +1 -1
- package/src/{common → policy}/synthetic-file-transaction.mjs +1 -1
- package/src/{common → policy}/synthetic-write-adapter.mjs +2 -3
- /package/{src/common → shared/lib}/bounded-search-policy.mjs +0 -0
- /package/{src/common → shared/lib}/config.mjs +0 -0
- /package/{src/common → shared/lib}/contracts.mjs +0 -0
- /package/{src/common → shared/lib}/errors.mjs +0 -0
- /package/{src/common → shared/lib}/events.mjs +0 -0
- /package/{src/common → shared/lib}/execution-policy.mjs +0 -0
- /package/{src/common → shared/lib}/isolated-read-boundary.mjs +0 -0
- /package/{src/common → shared/lib}/isolated-read-policy.mjs +0 -0
- /package/{src/common → shared/lib}/lifecycle-events.mjs +0 -0
- /package/{src/common → shared/lib}/runtime-timing.mjs +0 -0
- /package/{src/common → shared/lib}/synthetic-auxiliary-policy.mjs +0 -0
- /package/{src/common → shared/lib}/tool-registry.mjs +0 -0
- /package/src/{device-agent → core}/c1-dc-transport.mjs +0 -0
- /package/src/{device-agent → core}/c1-startup.mjs +0 -0
- /package/src/{device-agent → core}/fixture.txt +0 -0
- /package/src/{common → policy}/synthetic-write-mount.mjs +0 -0
- /package/src/{common → policy}/verified-bounded-search.mjs +0 -0
- /package/src/{common → policy}/verified-isolated-read.mjs +0 -0
- /package/src/{common → policy}/verified-synthetic-write.mjs +0 -0
|
@@ -1,230 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
3
|
-
import {createRequire} from 'node:module';
|
|
4
|
-
import {lstatSync, readFileSync} from 'node:fs';
|
|
5
|
-
import https from 'node:https';
|
|
6
|
-
import {dirname, resolve} from 'node:path';
|
|
7
|
-
import {fileURLToPath} from 'node:url';
|
|
8
|
-
import {absolutePath, parseDeviceConfig, secret} from '../common/config.mjs';
|
|
9
|
-
import {ERROR_CODES} from '../common/errors.mjs';
|
|
10
|
-
import {resultEnvelope, sessionEnvelope, taskEnvelope} from '../common/contracts.mjs';
|
|
11
|
-
import {validateActiveTool,isIsolatedReadName,isBoundedSearchName} from '../common/tool-registry.mjs';
|
|
12
|
-
import {authorizeIsolatedAgentRead} from '../common/isolated-read-policy.mjs';
|
|
13
|
-
import {makeVerifiedIsolatedReadAdapter} from '../common/verified-isolated-read.mjs';
|
|
14
|
-
import {makeVerifiedBoundedSearchAdapter} from '../common/verified-bounded-search.mjs';
|
|
15
|
-
import {authorizeAgentBoundedSearch} from '../common/bounded-search-policy.mjs';
|
|
16
|
-
import {authorizeAgentExecution} from '../common/execution-policy.mjs';
|
|
17
|
-
import {createLifecycleReporter} from '../common/lifecycle-events.mjs';
|
|
18
|
-
import {isSyntheticWriteName} from '../common/synthetic-write-policy.mjs';
|
|
19
|
-
import {C1Supervisor} from './c1-supervisor.mjs';
|
|
20
|
-
import {createRuntimeTiming} from '../common/runtime-timing.mjs';
|
|
21
|
-
|
|
22
|
-
const require = createRequire(import.meta.url);
|
|
23
|
-
const here = dirname(fileURLToPath(import.meta.url));
|
|
24
|
-
const binPackage = require.resolve('@wonderwhy-er/desktop-commander/package.json');
|
|
25
|
-
const {bin: binaries} = require(binPackage);
|
|
26
|
-
const desktopCommander = resolve(dirname(binPackage), binaries['desktop-commander']);
|
|
27
|
-
const p2Mode = process.env.RS_P2_MODE === 'true';
|
|
28
|
-
const isolatedReadEnabled=p2Mode&&process.env.RS_55A_TEST_MODE==='true'&&Boolean(process.env.RS_55A_ROOT);
|
|
29
|
-
const p3Mode=process.env.RS_P3_MODE==='true';
|
|
30
|
-
const syntheticWriteEnabled=p2Mode&&p3Mode&&process.env.RS_55C1_TEST_MODE==='true';
|
|
31
|
-
if(process.env.RS_55C1_TEST_MODE!==undefined&&!['true','false'].includes(process.env.RS_55C1_TEST_MODE))throw Error('Invalid C1 mode');
|
|
32
|
-
if(process.env.RS_55C1_TEST_MODE==='true'&&!syntheticWriteEnabled)throw Error('C1 requires P2 and P3');
|
|
33
|
-
const boundedSearchEnabled=p2Mode&&p3Mode&&process.env.RS_55A_TEST_MODE==='true'&&process.env.RS_55B_TEST_MODE==='true'&&Boolean(process.env.RS_55A_ROOT)&&typeof process.env.RS_55B_ROOT_SCOPE_ID==='string';
|
|
34
|
-
if(process.env.RS_55B_TEST_MODE!==undefined&&!['true','false'].includes(process.env.RS_55B_TEST_MODE))throw new Error('Invalid configuration: RS_55B_TEST_MODE');
|
|
35
|
-
if(process.env.RS_55B_TEST_MODE==='true'&&(!boundedSearchEnabled||!/^[A-Za-z0-9_-]{16,128}$/.test(process.env.RS_55B_ROOT_SCOPE_ID)))throw new Error('Invalid bounded-search test configuration');
|
|
36
|
-
if (process.env.RS_P2_MODE !== undefined && process.env.RS_P2_MODE !== 'true' && process.env.RS_P2_MODE !== 'false') throw new Error('Invalid configuration: RS_P2_MODE');
|
|
37
|
-
let p2Credential = null;
|
|
38
|
-
if (p2Mode) {
|
|
39
|
-
const credentialFile = absolutePath(process.env.RS_P2_DEVICE_CREDENTIAL_FILE, 'RS_P2_DEVICE_CREDENTIAL_FILE');
|
|
40
|
-
const fileStat = lstatSync(credentialFile);
|
|
41
|
-
if (!fileStat.isFile() || fileStat.isSymbolicLink() || (fileStat.mode & 0o777) !== 0o600) throw new Error('P2 device credential file must be private');
|
|
42
|
-
const parentStat = lstatSync(dirname(credentialFile));
|
|
43
|
-
if (!parentStat.isDirectory() || parentStat.isSymbolicLink() || (parentStat.mode & 0o777) !== 0o700) throw new Error('P2 device credential directory must be private');
|
|
44
|
-
const parsed = JSON.parse(readFileSync(credentialFile, 'utf8'));
|
|
45
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.keys(parsed).some(key => !['device_id', 'credential'].includes(key))) throw new Error('Invalid P2 device provisioning');
|
|
46
|
-
if (typeof parsed.device_id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(parsed.device_id)) throw new Error('Invalid P2 device provisioning');
|
|
47
|
-
p2Credential = {device_id: parsed.device_id, credential: secret(parsed.credential, 'P2 device credential')};
|
|
48
|
-
}
|
|
49
|
-
const gatewayUrl = parseDeviceConfig({
|
|
50
|
-
...process.env,
|
|
51
|
-
RS_DEVICE_TOKEN: p2Mode ? p2Credential.credential : process.env.RS_DEVICE_TOKEN,
|
|
52
|
-
RS_GATEWAY_URL: process.env.RS_GATEWAY_URL || `http://127.0.0.1:${process.env.RS_PORT || 18765}`,
|
|
53
|
-
}).gatewayUrl;
|
|
54
|
-
const endpoint = new URL(gatewayUrl);
|
|
55
|
-
if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.pathname !== '/' || endpoint.search || endpoint.hash) {
|
|
56
|
-
throw new Error('Invalid gateway URL');
|
|
57
|
-
}
|
|
58
|
-
const localHosts = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
59
|
-
const local = localHosts.has(endpoint.hostname);
|
|
60
|
-
if (!local && (endpoint.protocol !== 'https:' || process.env.RS_ENABLE_REMOTE !== 'true' || !process.env.RS_CA_FILE)) {
|
|
61
|
-
throw new Error('Remote gateway requires HTTPS, RS_ENABLE_REMOTE=true and RS_CA_FILE');
|
|
62
|
-
}
|
|
63
|
-
if (endpoint.protocol === 'http:' && !local) throw new Error('Plain HTTP allowed on loopback only');
|
|
64
|
-
const ca = endpoint.protocol === 'https:' && process.env.RS_CA_FILE ? readFileSync(process.env.RS_CA_FILE) : undefined;
|
|
65
|
-
const deviceId = p2Mode ? p2Credential.device_id : 'device-1';
|
|
66
|
-
const deviceToken = p2Mode ? p2Credential.credential : parseDeviceConfig({...process.env, RS_GATEWAY_URL: gatewayUrl}).credentials.device;
|
|
67
|
-
const client = new Client({name: 'remoteshell-device', version: '0.1.0'});
|
|
68
|
-
let isolatedReadRun=null;
|
|
69
|
-
let boundedSearchRun=null;
|
|
70
|
-
let syntheticWriteSupervisor=null;
|
|
71
|
-
const transport = new StdioClientTransport({
|
|
72
|
-
command: process.execPath,
|
|
73
|
-
args: [desktopCommander, '--no-onboarding'],
|
|
74
|
-
stderr: 'pipe',
|
|
75
|
-
cwd: here,
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
let sessionId = null;
|
|
79
|
-
let stopping = false;
|
|
80
|
-
let failures = 0;
|
|
81
|
-
let connected = false;
|
|
82
|
-
const lifecycle = createLifecycleReporter();
|
|
83
|
-
const timing=createRuntimeTiming('agent');
|
|
84
|
-
|
|
85
|
-
async function stop() {
|
|
86
|
-
if (stopping) return;
|
|
87
|
-
stopping = true;
|
|
88
|
-
syntheticWriteSupervisor?.close();
|
|
89
|
-
await boundedSearchRun?.close().catch(()=>{});
|
|
90
|
-
if (p2Mode && sessionId) await post('/device/disconnect', {}).catch(() => {});
|
|
91
|
-
}
|
|
92
|
-
process.once('SIGINT', () => {void stop();});
|
|
93
|
-
process.once('SIGTERM', () => {void stop();});
|
|
94
|
-
|
|
95
|
-
async function post(path, payload, timeout = 6000) {
|
|
96
|
-
const data = JSON.stringify({...payload, ...(sessionId && path !== '/device/register' ? {session_id: sessionId} : {}), device_id: deviceId});
|
|
97
|
-
const headers = {authorization: `Bearer ${deviceToken}`, 'content-type': 'application/json'};
|
|
98
|
-
if (endpoint.protocol === 'https:') {
|
|
99
|
-
return new Promise((resolveResponse, reject) => {
|
|
100
|
-
const request = https.request(new URL(path, endpoint), {
|
|
101
|
-
method: 'POST', ca, headers: {...headers, 'content-length': Buffer.byteLength(data)}, timeout,
|
|
102
|
-
}, response => {
|
|
103
|
-
let text = '';
|
|
104
|
-
response.on('data', chunk => { text += chunk; });
|
|
105
|
-
response.on('end', () => {
|
|
106
|
-
if (response.statusCode < 200 || response.statusCode >= 300) return reject(new Error(`HTTP ${response.statusCode}`));
|
|
107
|
-
try { resolveResponse(JSON.parse(text)); } catch { reject(new Error('INVALID_GATEWAY_RESPONSE')); }
|
|
108
|
-
});
|
|
109
|
-
});
|
|
110
|
-
request.on('timeout', () => request.destroy(new Error('GATEWAY_TIMEOUT')));
|
|
111
|
-
request.on('error', reject);
|
|
112
|
-
request.end(data);
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
const response = await fetch(new URL(path, endpoint), {
|
|
116
|
-
method: 'POST', headers, body: data, signal: AbortSignal.timeout(timeout),
|
|
117
|
-
});
|
|
118
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
119
|
-
return response.json();
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
async function register() {
|
|
123
|
-
const response = sessionEnvelope(await post('/device/register', {}));
|
|
124
|
-
sessionId = response.session_id;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function textOf(result) {
|
|
128
|
-
return (result.content || []).filter(item => item.type === 'text').map(item => item.text).join('\n');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async function execute(taskValue) {
|
|
132
|
-
const task = taskEnvelope(taskValue);
|
|
133
|
-
if (task.state !== 'dispatched' || task.session_id !== sessionId) throw new Error('SESSION_DENIED');
|
|
134
|
-
if(isBoundedSearchName(task.tool.name)){
|
|
135
|
-
const tool=authorizeAgentBoundedSearch({tool:task.tool,enabled:boundedSearchEnabled});
|
|
136
|
-
if(!boundedSearchRun)throw new Error('TOOL_DENIED');
|
|
137
|
-
return boundedSearchRun(tool.name,tool.arguments);
|
|
138
|
-
}
|
|
139
|
-
const tool=isIsolatedReadName(task.tool.name)?authorizeIsolatedAgentRead({tool:task.tool,enabled:isolatedReadEnabled}):p2Mode?authorizeAgentExecution(task.tool):validateActiveTool(task.tool);
|
|
140
|
-
if(isIsolatedReadName(tool.name)){
|
|
141
|
-
if(!isolatedReadRun)throw new Error('TOOL_DENIED');
|
|
142
|
-
return isolatedReadRun(tool.name,tool.arguments);
|
|
143
|
-
}
|
|
144
|
-
if (tool.name === 'pwd') {
|
|
145
|
-
timing({request_id:task.request_id,tool_name:tool.name,phase:'native_begin'});
|
|
146
|
-
const result = await client.callTool({name: 'start_process', arguments: {command: 'pwd', timeout_ms: 4000}}).finally(()=>timing({request_id:task.request_id,tool_name:tool.name,phase:'native_done'}));
|
|
147
|
-
if (result.isError) throw new Error('UPSTREAM_TOOL_ERROR');
|
|
148
|
-
return textOf(result);
|
|
149
|
-
}
|
|
150
|
-
if (tool.name === 'read_fixture') {
|
|
151
|
-
timing({request_id:task.request_id,tool_name:tool.name,phase:'native_begin'});
|
|
152
|
-
const result = await client.callTool({name: 'read_file', arguments: {path: resolve(here, 'fixture.txt')} }).finally(()=>timing({request_id:task.request_id,tool_name:tool.name,phase:'native_done'}));
|
|
153
|
-
if (result.isError) throw new Error('UPSTREAM_TOOL_ERROR');
|
|
154
|
-
return textOf(result);
|
|
155
|
-
}
|
|
156
|
-
throw new Error('TOOL_DENIED');
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
async function reportResult(task, result) {
|
|
160
|
-
timing({request_id:task.request_id,tool_name:task.tool.name,phase:'result_begin'});
|
|
161
|
-
const payload = resultEnvelope({
|
|
162
|
-
request_id: task.request_id,
|
|
163
|
-
ok: result.ok,
|
|
164
|
-
...(result.ok ? {result: result.result} : {error_code: result.error_code || ERROR_CODES.UPSTREAM_TOOL_ERROR}),
|
|
165
|
-
});
|
|
166
|
-
await post('/device/result', payload);
|
|
167
|
-
timing({request_id:task.request_id,tool_name:task.tool.name,phase:'result_done'});
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
async function run() {
|
|
171
|
-
try {
|
|
172
|
-
await client.connect(transport);
|
|
173
|
-
connected = true;
|
|
174
|
-
if(isolatedReadEnabled)isolatedReadRun=makeVerifiedIsolatedReadAdapter({root:process.env.RS_55A_ROOT,client});
|
|
175
|
-
if(boundedSearchEnabled)boundedSearchRun=makeVerifiedBoundedSearchAdapter({root:process.env.RS_55A_ROOT,rootScopeId:process.env.RS_55B_ROOT_SCOPE_ID,client});
|
|
176
|
-
if(syntheticWriteEnabled){
|
|
177
|
-
const runtime=resolve(here,'../..');
|
|
178
|
-
if(resolve(process.env.RS_P2_DEVICE_CREDENTIAL_FILE).startsWith(runtime+'/'))throw Error('C1 credential must be outside runtime');
|
|
179
|
-
syntheticWriteSupervisor=new C1Supervisor({runtime,post});
|
|
180
|
-
await syntheticWriteSupervisor.ready();
|
|
181
|
-
}
|
|
182
|
-
console.log('Device connected to Desktop Commander stdio');
|
|
183
|
-
await register();
|
|
184
|
-
while (!stopping) {
|
|
185
|
-
try {
|
|
186
|
-
const {task: taskValue} = await post('/device/poll', {});
|
|
187
|
-
failures = 0;
|
|
188
|
-
if (taskValue) {
|
|
189
|
-
const task = taskEnvelope(taskValue);
|
|
190
|
-
if (task.session_id !== sessionId || task.state !== 'dispatched') throw new Error('SESSION_DENIED');
|
|
191
|
-
timing({request_id:task.request_id,tool_name:task.tool.name,phase:'poll_received'});
|
|
192
|
-
lifecycle({request_id:task.request_id,session_id:task.session_id,tool_name:task.tool.name,event_type:'dispatched'});
|
|
193
|
-
const startedAt=Date.now();
|
|
194
|
-
try {
|
|
195
|
-
if(isSyntheticWriteName(task.tool.name)){
|
|
196
|
-
if(!syntheticWriteSupervisor||task.context.device_id!==deviceId||task.context.session_id!==sessionId)throw Error('TOOL_DENIED');
|
|
197
|
-
await syntheticWriteSupervisor.execute(task);
|
|
198
|
-
}else await reportResult(task, {ok: true, result: await execute(task)});
|
|
199
|
-
lifecycle({request_id:task.request_id,session_id:task.session_id,tool_name:task.tool.name,event_type:'completed',outcome:'success',duration_ms:Date.now()-startedAt});
|
|
200
|
-
} catch (error) {
|
|
201
|
-
const code = error.code === ERROR_CODES.TOOL_DENIED ? ERROR_CODES.TOOL_DENIED
|
|
202
|
-
: error.code === ERROR_CODES.ARGUMENTS_DENIED ? ERROR_CODES.ARGUMENTS_DENIED
|
|
203
|
-
: ERROR_CODES.UPSTREAM_TOOL_ERROR;
|
|
204
|
-
await reportResult(task, {ok: false, error_code: code});
|
|
205
|
-
lifecycle({request_id:task.request_id,session_id:task.session_id,tool_name:task.tool.name,event_type:'failed',outcome:'failed',error_code:code,duration_ms:Date.now()-startedAt});
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
} catch (error) {
|
|
209
|
-
if (stopping) break;
|
|
210
|
-
console.error('device connection:', /HTTP \d+/.exec(String(error.message))?.[0] || 'NETWORK_ERROR');
|
|
211
|
-
failures = Math.min(failures + 1, 6);
|
|
212
|
-
if (/HTTP (403|503)/.test(error.message)) {
|
|
213
|
-
try { await register(); } catch { console.error('device register: NETWORK_ERROR'); }
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if (!stopping) await new Promise(resolveDelay => setTimeout(resolveDelay, Math.min(5000, 200 * 2 ** failures)));
|
|
217
|
-
}
|
|
218
|
-
} finally {
|
|
219
|
-
syntheticWriteSupervisor?.close();
|
|
220
|
-
await boundedSearchRun?.close().catch(()=>{});
|
|
221
|
-
if (connected) await client.close();
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
run().catch(error => {
|
|
226
|
-
const code=/^C1_[A-Z_]+$/.test(error?.message)?error.message:'INITIALIZATION_FAILED';
|
|
227
|
-
console.error('device startup:',code);
|
|
228
|
-
process.exitCode = 1;
|
|
229
|
-
});
|
|
230
|
-
|
|
1
|
+
import '../main.mjs';
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Gateway session liveness is independent of Desktop Commander discovery and tool calls.
|
|
2
|
+
// One authenticated heartbeat/recovery cycle at a time; never replay a DC tool request.
|
|
3
|
+
export function createGatewayKeepalive({heartbeat,recover,onFailure=()=>{},intervalMs=10000,
|
|
4
|
+
schedule=setInterval,unschedule=clearInterval,now=Date.now,random=Math.random}={}){
|
|
5
|
+
if(typeof heartbeat!=='function'||typeof recover!=='function'||
|
|
6
|
+
!Number.isSafeInteger(intervalMs)||intervalMs<1000)throw Error('INVALID_KEEPALIVE');
|
|
7
|
+
let timer=null,inFlight=false,stopped=false,authorizationRejected=false,failures=0,retryAt=0;
|
|
8
|
+
const notify=error=>{try{onFailure(error)}catch{}};
|
|
9
|
+
async function tick(){
|
|
10
|
+
if(stopped||inFlight||authorizationRejected||now()<retryAt)return;
|
|
11
|
+
inFlight=true;
|
|
12
|
+
try{
|
|
13
|
+
await heartbeat();
|
|
14
|
+
failures=0;
|
|
15
|
+
retryAt=0;
|
|
16
|
+
}catch(error){
|
|
17
|
+
notify(error);
|
|
18
|
+
const code=/HTTP (\d{3})/.exec(String(error?.message||''))?.[1];
|
|
19
|
+
if(code==='401'){authorizationRejected=true;return}
|
|
20
|
+
if(!stopped&&(code==='403'||code==='503')){
|
|
21
|
+
try{
|
|
22
|
+
await recover();
|
|
23
|
+
failures=0;
|
|
24
|
+
retryAt=0;
|
|
25
|
+
return;
|
|
26
|
+
}catch(recoveryError){
|
|
27
|
+
notify(recoveryError);
|
|
28
|
+
// A rejected fresh device registration requires explicit user-side repair.
|
|
29
|
+
if(/HTTP (401|403)/.test(String(recoveryError?.message||''))){
|
|
30
|
+
authorizationRejected=true;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
failures=Math.min(failures+1,6);
|
|
36
|
+
const delay=Math.min(60000,intervalMs*2**failures)+Math.floor(random()*intervalMs);
|
|
37
|
+
retryAt=now()+delay;
|
|
38
|
+
}finally{inFlight=false}
|
|
39
|
+
}
|
|
40
|
+
return Object.freeze({
|
|
41
|
+
start(){
|
|
42
|
+
if(timer!==null||stopped)return;
|
|
43
|
+
timer=schedule(()=>{void tick()},intervalMs);
|
|
44
|
+
},
|
|
45
|
+
stop(){
|
|
46
|
+
stopped=true;
|
|
47
|
+
if(timer!==null){unschedule(timer);timer=null}
|
|
48
|
+
},
|
|
49
|
+
tick,
|
|
50
|
+
get authorizationRejected(){return authorizationRejected}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Control Plane freshness is a separate prerequisite for Gateway credential verification.
|
|
55
|
+
// Keep its heartbeat alive even when the DC request/poll loop is waiting.
|
|
56
|
+
export function createCpHeartbeatLoop({heartbeat,onFailure=()=>{},intervalMs=10000,
|
|
57
|
+
schedule=setInterval,unschedule=clearInterval}={}){
|
|
58
|
+
if(typeof heartbeat!=='function'||!Number.isSafeInteger(intervalMs)||intervalMs<1000)
|
|
59
|
+
throw Error('INVALID_CP_HEARTBEAT');
|
|
60
|
+
let timer=null,stopped=false,inFlight=false;
|
|
61
|
+
async function tick(){
|
|
62
|
+
if(stopped||inFlight)return;
|
|
63
|
+
inFlight=true;
|
|
64
|
+
try{await heartbeat()}
|
|
65
|
+
catch(error){try{onFailure(error)}catch{}}
|
|
66
|
+
finally{inFlight=false}
|
|
67
|
+
}
|
|
68
|
+
return Object.freeze({
|
|
69
|
+
start(){if(timer===null&&!stopped)timer=schedule(()=>{void tick()},intervalMs)},
|
|
70
|
+
stop(){stopped=true;if(timer!==null){unschedule(timer);timer=null}},
|
|
71
|
+
tick
|
|
72
|
+
});
|
|
73
|
+
}
|