@remoteshell/device 0.0.0-stage → 0.1.0-beta.2
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 +363 -0
- package/bin/enrollment-client.mjs +105 -0
- package/bin/install-acquire.mjs +89 -0
- package/bin/install-integrity.mjs +74 -0
- package/bin/install-plan.mjs +43 -0
- package/bin/lifecycle.mjs +172 -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 +289 -0
- package/bin/remoteshell-easy-install.sh +71 -0
- package/bin/remoteshell-easy-uninstall.ps1 +124 -0
- package/bin/windows-credential-boundary.mjs +106 -0
- package/bin/windows-install-layout.mjs +28 -0
- package/bin/windows-native-installer.mjs +88 -0
- package/bin/windows-private-store.mjs +163 -0
- package/bin/windows-user-lifecycle.mjs +34 -0
- package/npm-shrinkwrap.json +8591 -0
- package/package.json +27 -4
- package/shared/lib/bounded-search-contract.mjs +5 -0
- package/shared/lib/bounded-search-policy.mjs +24 -0
- package/shared/lib/config.mjs +14 -0
- package/shared/lib/contracts.mjs +26 -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/shared/lib/errors.mjs +9 -0
- package/shared/lib/events.mjs +5 -0
- package/shared/lib/execution-policy.mjs +41 -0
- package/shared/lib/isolated-read-boundary.mjs +50 -0
- package/shared/lib/isolated-read-policy.mjs +29 -0
- package/shared/lib/lifecycle-events.mjs +13 -0
- package/shared/lib/runtime-timing.mjs +9 -0
- package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
- package/shared/lib/synthetic-write-policy.mjs +52 -0
- package/shared/lib/tool-registry.mjs +58 -0
- 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/core/c1-dc-transport.mjs +26 -0
- package/src/core/c1-startup.mjs +22 -0
- package/src/core/c1-supervisor.mjs +111 -0
- package/src/core/c1-worker.mjs +88 -0
- package/src/core/fixture.txt +2 -0
- 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 -0
- package/src/gateway-keepalive.mjs +73 -0
- package/src/main.mjs +434 -0
- package/src/policy/bounded-search-adapter.mjs +115 -0
- package/src/policy/isolated-read-adapter.mjs +50 -0
- package/src/policy/isolated-read-mount.mjs +27 -0
- package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
- package/src/policy/synthetic-file-adapter.mjs +26 -0
- package/src/policy/synthetic-file-transaction.mjs +87 -0
- package/src/policy/synthetic-write-adapter.mjs +151 -0
- package/src/policy/synthetic-write-mount.mjs +23 -0
- package/src/policy/verified-bounded-search.mjs +12 -0
- package/src/policy/verified-isolated-read.mjs +15 -0
- package/src/policy/verified-synthetic-write.mjs +14 -0
- package/README.md +0 -3
|
@@ -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
|
+
}
|
package/src/main.mjs
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
|
+
import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
3
|
+
import {createRequire} from 'node:module';
|
|
4
|
+
import {readFileSync} from 'node:fs';
|
|
5
|
+
import https from 'node:https';
|
|
6
|
+
import {createGatewayKeepalive,createCpHeartbeatLoop} from './gateway-keepalive.mjs';
|
|
7
|
+
import {dirname, resolve, isAbsolute} from 'node:path';
|
|
8
|
+
import {fileURLToPath} from 'node:url';
|
|
9
|
+
import {absolutePath, parseDeviceConfig} from '../shared/lib/config.mjs';
|
|
10
|
+
import {readPrivateP2Credential} from './config/p2-private-credential.mjs';
|
|
11
|
+
import {ERROR_CODES} from '../shared/lib/errors.mjs';
|
|
12
|
+
import {resultEnvelope, sessionEnvelope, taskEnvelope} from '../shared/lib/contracts.mjs';
|
|
13
|
+
import {validateActiveTool,isIsolatedReadName,isBoundedSearchName} from '../shared/lib/tool-registry.mjs';
|
|
14
|
+
import {authorizeIsolatedAgentRead} from '../shared/lib/isolated-read-policy.mjs';
|
|
15
|
+
import {makeVerifiedIsolatedReadAdapter} from './policy/verified-isolated-read.mjs';
|
|
16
|
+
import {makeVerifiedBoundedSearchAdapter} from './policy/verified-bounded-search.mjs';
|
|
17
|
+
import {authorizeAgentBoundedSearch} from '../shared/lib/bounded-search-policy.mjs';
|
|
18
|
+
import {authorizeAgentExecution} from '../shared/lib/execution-policy.mjs';
|
|
19
|
+
import {createLifecycleReporter} from '../shared/lib/lifecycle-events.mjs';
|
|
20
|
+
import {isSyntheticWriteName} from '../shared/lib/synthetic-write-policy.mjs';
|
|
21
|
+
import {C1Supervisor} from './core/c1-supervisor.mjs';
|
|
22
|
+
import {createRuntimeTiming} from '../shared/lib/runtime-timing.mjs';
|
|
23
|
+
import {readL2DevOciCredential} from './config/l2-dev-oci-credential.mjs';
|
|
24
|
+
import {devHeartbeatOnce} from '../bin/dev-agent-client.mjs';
|
|
25
|
+
import {devDogfoodTaskEnvelope,executeDevDogfoodTask} from './connection/dev-dogfood-task.mjs';
|
|
26
|
+
import {callOriginalDc,callOriginalDcGeneric} from './dc/dev-dc-relay.mjs';
|
|
27
|
+
import {isDcPublic} from '../shared/lib/dc-generic-policy.mjs';
|
|
28
|
+
import {discoverDcCatalog,dcCatalogFingerprint,diffDcCatalog} from '../shared/lib/dc-tool-catalog.mjs';
|
|
29
|
+
import {inspectDcAccessBoundary} from './dc/dc-access-readiness.mjs';
|
|
30
|
+
import {createDevDogfoodProcesses} from './connection/dev-dogfood-processes.mjs';
|
|
31
|
+
import {createRootScopeDiscovery,routeDiscoveredRootTask} from './connection/dev-root-scopes.mjs';
|
|
32
|
+
import {validateExclusionPolicy} from '../shared/lib/dev-root-exclusions.mjs';
|
|
33
|
+
|
|
34
|
+
const require = createRequire(import.meta.url);
|
|
35
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
36
|
+
const binPackage = require.resolve('@wonderwhy-er/desktop-commander/package.json');
|
|
37
|
+
const {bin: binaries} = require(binPackage);
|
|
38
|
+
const desktopCommander = resolve(dirname(binPackage), binaries['desktop-commander']);
|
|
39
|
+
const p2Mode = process.env.RS_P2_MODE === 'true';
|
|
40
|
+
const isolatedReadEnabled=p2Mode&&process.env.RS_55A_TEST_MODE==='true'&&Boolean(process.env.RS_55A_ROOT);
|
|
41
|
+
if(process.env.RS_L2_DEV_AGENT!==undefined&&!['true','false'].includes(process.env.RS_L2_DEV_AGENT))throw Error('Invalid RS_L2_DEV_AGENT');
|
|
42
|
+
const l2DevAgent=process.env.RS_L2_DEV_AGENT==='true';
|
|
43
|
+
if(l2DevAgent&&(!p2Mode||!isolatedReadEnabled||process.env.RS_55B_TEST_MODE==='true'||process.env.RS_55C1_TEST_MODE==='true'))throw Error('L2 DEV Agent requires isolated read-only P2 mode');
|
|
44
|
+
// These values map the CP-approved root_id to a local folder. They are not an
|
|
45
|
+
// authorization grant: the Gateway must only dispatch a task after a fresh CP
|
|
46
|
+
// owner/device/connection/root/tool decision.
|
|
47
|
+
const d1RootId=process.env.RS_L2_D1_ROOT_ID;
|
|
48
|
+
const d1Root=process.env.RS_L2_D1_ROOT;
|
|
49
|
+
if((d1RootId!==undefined||d1Root!==undefined)&&(!l2DevAgent||
|
|
50
|
+
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(d1RootId||'')||
|
|
51
|
+
typeof d1Root!=='string'||!isAbsolute(d1Root)))throw Error('Invalid L2 D1 local root mapping');
|
|
52
|
+
const l2DevCredentialFile=process.env.RS_L2_DEV_CREDENTIAL_FILE;
|
|
53
|
+
if(l2DevCredentialFile!==undefined&&(!l2DevAgent||!p2Mode||process.env.RS_P2_DEVICE_CREDENTIAL_FILE))
|
|
54
|
+
throw Error('L2 DEV OCI credential requires the explicit L2 DEV agent mode');
|
|
55
|
+
if(l2DevAgent&&!l2DevCredentialFile)throw Error('L2 DEV OCI credential file is required');
|
|
56
|
+
const p3Mode=process.env.RS_P3_MODE==='true';
|
|
57
|
+
const syntheticWriteEnabled=p2Mode&&p3Mode&&process.env.RS_55C1_TEST_MODE==='true';
|
|
58
|
+
if(process.env.RS_55C1_TEST_MODE!==undefined&&!['true','false'].includes(process.env.RS_55C1_TEST_MODE))throw Error('Invalid C1 mode');
|
|
59
|
+
if(process.env.RS_55C1_TEST_MODE==='true'&&!syntheticWriteEnabled)throw Error('C1 requires P2 and P3');
|
|
60
|
+
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';
|
|
61
|
+
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');
|
|
62
|
+
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');
|
|
63
|
+
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');
|
|
64
|
+
let p2Credential = null;
|
|
65
|
+
if (p2Mode) {
|
|
66
|
+
if(l2DevAgent&&l2DevCredentialFile){
|
|
67
|
+
p2Credential=readL2DevOciCredential(absolutePath(l2DevCredentialFile,'RS_L2_DEV_CREDENTIAL_FILE'));
|
|
68
|
+
}else{
|
|
69
|
+
p2Credential = readPrivateP2Credential(
|
|
70
|
+
absolutePath(process.env.RS_P2_DEVICE_CREDENTIAL_FILE, 'RS_P2_DEVICE_CREDENTIAL_FILE'));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const gatewayUrl = parseDeviceConfig({
|
|
74
|
+
...process.env,
|
|
75
|
+
RS_DEVICE_TOKEN: p2Mode ? p2Credential.credential : process.env.RS_DEVICE_TOKEN,
|
|
76
|
+
RS_GATEWAY_URL: process.env.RS_GATEWAY_URL || `http://127.0.0.1:${process.env.RS_PORT || 18765}`,
|
|
77
|
+
}).gatewayUrl;
|
|
78
|
+
const endpoint = new URL(gatewayUrl);
|
|
79
|
+
// Public DEV Agent Gateway API is versioned independently of the internal transport.
|
|
80
|
+
const publicDevGateway = l2DevAgent && endpoint.protocol === 'https:' &&
|
|
81
|
+
endpoint.hostname === 'ailab-remoteshell.duckdns.org' && endpoint.pathname === '/gateway/v1/';
|
|
82
|
+
if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.username || endpoint.password ||
|
|
83
|
+
(endpoint.pathname !== '/' && !publicDevGateway) || endpoint.search || endpoint.hash) {
|
|
84
|
+
throw new Error('Invalid gateway URL');
|
|
85
|
+
}
|
|
86
|
+
const localHosts = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
87
|
+
const local = localHosts.has(endpoint.hostname);
|
|
88
|
+
if (!local && (endpoint.protocol !== 'https:' || process.env.RS_ENABLE_REMOTE !== 'true' ||
|
|
89
|
+
(!publicDevGateway && !process.env.RS_CA_FILE))) {
|
|
90
|
+
throw new Error('Remote gateway requires HTTPS, RS_ENABLE_REMOTE=true and RS_CA_FILE');
|
|
91
|
+
}
|
|
92
|
+
if (endpoint.protocol === 'http:' && !local) throw new Error('Plain HTTP allowed on loopback only');
|
|
93
|
+
const ca = endpoint.protocol === 'https:' && process.env.RS_CA_FILE ? readFileSync(process.env.RS_CA_FILE) : undefined;
|
|
94
|
+
const deviceId = p2Mode ? p2Credential.device_id : 'device-1';
|
|
95
|
+
const deviceToken = p2Mode ? p2Credential.credential : parseDeviceConfig({...process.env, RS_GATEWAY_URL: gatewayUrl}).credentials.device;
|
|
96
|
+
const client = new Client({name: 'remoteshell-device', version: '0.1.0'});
|
|
97
|
+
let isolatedReadRun=null;
|
|
98
|
+
let boundedSearchRun=null;
|
|
99
|
+
let syntheticWriteSupervisor=null;
|
|
100
|
+
let devDogfoodProcesses=null;
|
|
101
|
+
let rootScopes=null;
|
|
102
|
+
const transport = new StdioClientTransport({
|
|
103
|
+
command: process.execPath,
|
|
104
|
+
args: [desktopCommander, '--no-onboarding'],
|
|
105
|
+
stderr: 'pipe',
|
|
106
|
+
// Match RDC's original DC working-directory semantics (the DC binary folder).
|
|
107
|
+
cwd: dirname(desktopCommander),
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
let sessionId = null;
|
|
111
|
+
let sessionRegisteredAt = 0;
|
|
112
|
+
let registrationInFlight=null;
|
|
113
|
+
let catalogInFlight=null;
|
|
114
|
+
let gatewayKeepalive=null;
|
|
115
|
+
let cpHeartbeatLoop=null;
|
|
116
|
+
let stopping = false;
|
|
117
|
+
let failures = 0;
|
|
118
|
+
let connected = false;
|
|
119
|
+
const lifecycle = createLifecycleReporter();
|
|
120
|
+
const timing=createRuntimeTiming('agent');
|
|
121
|
+
|
|
122
|
+
async function stop() {
|
|
123
|
+
if (stopping) return;
|
|
124
|
+
stopping = true;
|
|
125
|
+
gatewayKeepalive?.stop();
|
|
126
|
+
cpHeartbeatLoop?.stop();
|
|
127
|
+
syntheticWriteSupervisor?.close();
|
|
128
|
+
devDogfoodProcesses?.close({deviceId,sessionId});
|
|
129
|
+
await boundedSearchRun?.close().catch(()=>{});
|
|
130
|
+
if (p2Mode && sessionId) await post('/device/disconnect', {}).catch(() => {});
|
|
131
|
+
}
|
|
132
|
+
process.once('SIGINT', () => {void stop();});
|
|
133
|
+
process.once('SIGTERM', () => {void stop();});
|
|
134
|
+
|
|
135
|
+
async function post(path, payload, timeout = 6000) {
|
|
136
|
+
const startedAt=Date.now();
|
|
137
|
+
const requestedSessionId=sessionId;
|
|
138
|
+
const registeredAt=sessionRegisteredAt;
|
|
139
|
+
const recordDenied=(status)=>console.warn('RS_GATEWAY_REQUEST_DENIED',JSON.stringify({
|
|
140
|
+
route:path,status,device_ref:deviceId.slice(0,8),
|
|
141
|
+
session_ref:requestedSessionId?.slice(0,8)||null,
|
|
142
|
+
session_age_ms:registeredAt?Date.now()-registeredAt:null,
|
|
143
|
+
duration_ms:Date.now()-startedAt
|
|
144
|
+
}));
|
|
145
|
+
const wirePath=l2DevAgent?path.replace(/^\/device\//,'/l2/dev/device/'):path;
|
|
146
|
+
const publicPath=publicDevGateway?wirePath.replace(/^\/l2\/dev\//,''):wirePath;
|
|
147
|
+
const wireUrl=new URL(publicDevGateway?publicPath:wirePath,endpoint);
|
|
148
|
+
const data = JSON.stringify({...payload, ...(requestedSessionId && path !== '/device/register' ? {session_id: requestedSessionId} : {}), device_id: deviceId});
|
|
149
|
+
const headers = {authorization: `Bearer ${deviceToken}`, 'content-type': 'application/json'};
|
|
150
|
+
if (endpoint.protocol === 'https:') {
|
|
151
|
+
return new Promise((resolveResponse, reject) => {
|
|
152
|
+
const request = https.request(wireUrl, {
|
|
153
|
+
method: 'POST', ca, headers: {...headers, 'content-length': Buffer.byteLength(data)}, timeout,
|
|
154
|
+
}, response => {
|
|
155
|
+
let text = '';
|
|
156
|
+
response.on('data', chunk => { text += chunk; });
|
|
157
|
+
response.on('end', () => {
|
|
158
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
159
|
+
recordDenied(response.statusCode);
|
|
160
|
+
return reject(new Error(`HTTP ${response.statusCode}`));
|
|
161
|
+
}
|
|
162
|
+
try { resolveResponse(JSON.parse(text)); } catch { reject(new Error('INVALID_GATEWAY_RESPONSE')); }
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
request.on('timeout', () => request.destroy(new Error('GATEWAY_TIMEOUT')));
|
|
166
|
+
request.on('error', reject);
|
|
167
|
+
request.end(data);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
const response = await fetch(wireUrl, {
|
|
171
|
+
method: 'POST', headers, body: data, signal: AbortSignal.timeout(timeout),
|
|
172
|
+
});
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
recordDenied(response.status);
|
|
175
|
+
throw new Error(`HTTP ${response.status}`);
|
|
176
|
+
}
|
|
177
|
+
return response.json();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
let dcCatalog=null,dcCatalogCheckedAt=0,dcCatalogPublishedHash=null;
|
|
181
|
+
async function publishDcCatalog(){
|
|
182
|
+
if(!sessionId||!dcCatalog)return;
|
|
183
|
+
const fingerprint=dcCatalogFingerprint(dcCatalog);
|
|
184
|
+
if(fingerprint===dcCatalogPublishedHash)return;
|
|
185
|
+
try{
|
|
186
|
+
const reply=await post('/device/catalog',{fingerprint,tools:dcCatalog},10000);
|
|
187
|
+
if(reply?.accepted!==true||reply.fingerprint!==fingerprint)throw Error('DC_CATALOG_NOT_ACKNOWLEDGED');
|
|
188
|
+
dcCatalogPublishedHash=fingerprint;
|
|
189
|
+
console.info('RS_DC_CATALOG_ACCEPTED',JSON.stringify({count:dcCatalog.length,fingerprint}));
|
|
190
|
+
}catch{console.warn('RS_DC_CATALOG_DELIVERY_FAILED');}
|
|
191
|
+
}
|
|
192
|
+
async function refreshDcCatalog({force=false}={}){
|
|
193
|
+
if(!force&&Date.now()-dcCatalogCheckedAt<60_000)return;
|
|
194
|
+
dcCatalogCheckedAt=Date.now();
|
|
195
|
+
const checkedAt=Date.now();
|
|
196
|
+
try{
|
|
197
|
+
const next=await discoverDcCatalog(client);
|
|
198
|
+
console.info('RS_DC_DISCOVERY_TIMING',JSON.stringify({result:'ok',duration_ms:Date.now()-checkedAt,device_ref:deviceId.slice(0,8)}));
|
|
199
|
+
const diff=diffDcCatalog(dcCatalog||[],next);
|
|
200
|
+
const fingerprint=dcCatalogFingerprint(next);
|
|
201
|
+
if(dcCatalog===null||diff.hasChanges)
|
|
202
|
+
console.info('RS_DC_CATALOG_DISCOVERED',JSON.stringify({
|
|
203
|
+
count:next.length,fingerprint,
|
|
204
|
+
added:diff.added,removed:diff.removed,changed:diff.changed,
|
|
205
|
+
// A tool discovered upstream is NOT automatically executable or advertised.
|
|
206
|
+
published:false
|
|
207
|
+
}));
|
|
208
|
+
dcCatalog=next;
|
|
209
|
+
if(sessionId)await publishDcCatalog();
|
|
210
|
+
}catch(error){
|
|
211
|
+
console.warn('RS_DC_DISCOVERY_TIMING',JSON.stringify({result:'failed',duration_ms:Date.now()-checkedAt,device_ref:deviceId.slice(0,8)}));
|
|
212
|
+
console.warn('RS_DC_CATALOG_UNAVAILABLE',error?.message==='DC_CATALOG_INVALID'?
|
|
213
|
+
'INVALID':'DISCOVERY_FAILED');
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
let lastCpHeartbeat=0;
|
|
217
|
+
let cpHeartbeatInFlight=null;
|
|
218
|
+
async function refreshCpHeartbeat(){
|
|
219
|
+
if(!l2DevAgent)return;
|
|
220
|
+
if(cpHeartbeatInFlight)return cpHeartbeatInFlight;
|
|
221
|
+
if(Date.now()-lastCpHeartbeat<(process.platform==='win32'?1000:15000))return;
|
|
222
|
+
cpHeartbeatInFlight=(async()=>{
|
|
223
|
+
try{
|
|
224
|
+
await devHeartbeatOnce({storageDir:dirname(l2DevCredentialFile)});
|
|
225
|
+
lastCpHeartbeat=Date.now();
|
|
226
|
+
console.log('L2_CP_HEARTBEAT_OK');
|
|
227
|
+
}catch(error){
|
|
228
|
+
const status=/HTTP (\d{3})/.exec(String(error?.message||''));
|
|
229
|
+
console.error('L2_CP_HEARTBEAT_FAIL',status?.[1]||'PROVIDER_DENIED');
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
})();
|
|
233
|
+
try{return await cpHeartbeatInFlight}finally{cpHeartbeatInFlight=null}
|
|
234
|
+
}
|
|
235
|
+
async function register(){
|
|
236
|
+
if(registrationInFlight)return registrationInFlight;
|
|
237
|
+
registrationInFlight=(async()=>{
|
|
238
|
+
const response=sessionEnvelope(await post('/device/register',rootScopes?{root_scopes:rootScopes.root_scopes}:{}));
|
|
239
|
+
if(stopping)return;
|
|
240
|
+
sessionId=response.session_id;
|
|
241
|
+
sessionRegisteredAt=Date.now();
|
|
242
|
+
console.info('RS_GATEWAY_SESSION_REGISTERED',JSON.stringify({device_ref:deviceId.slice(0,8),session_ref:sessionId.slice(0,8)}));
|
|
243
|
+
dcCatalogPublishedHash=null;
|
|
244
|
+
await publishDcCatalog();
|
|
245
|
+
})();
|
|
246
|
+
try{return await registrationInFlight}finally{registrationInFlight=null}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function scheduleCatalogRefresh({force=false}={}){
|
|
250
|
+
if(catalogInFlight)return;
|
|
251
|
+
catalogInFlight=refreshDcCatalog({force}).catch(()=>{}).finally(()=>{catalogInFlight=null});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function textOf(result) {
|
|
255
|
+
return (result.content || []).filter(item => item.type === 'text').map(item => item.text).join('\n');
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function execute(taskValue,exclusion_policy) {
|
|
259
|
+
const selectedRoot=l2DevAgent&&rootScopes&&taskValue?.tool?.arguments?.root_id?
|
|
260
|
+
rootScopes.resolve(taskValue.tool.arguments.root_id):null;
|
|
261
|
+
const dcRelayTask=taskValue?.tool?.arguments?.dc_relay===true;
|
|
262
|
+
const selectedRootId=dcRelayTask?taskValue.tool.arguments.root_id:
|
|
263
|
+
selectedRoot?taskValue.tool.arguments.root_id:d1RootId;
|
|
264
|
+
const task = l2DevAgent&&d1RootId?devDogfoodTaskEnvelope(taskValue,{sessionId,rootId:selectedRootId,deviceId}):taskEnvelope(taskValue);
|
|
265
|
+
if (task.state !== 'dispatched' || task.session_id !== sessionId) throw new Error('SESSION_DENIED');
|
|
266
|
+
if(l2DevAgent&&d1RootId){
|
|
267
|
+
if(!selectedRoot&&!dcRelayTask)throw Error('DEV_ROOT_SCOPE_DENIED');
|
|
268
|
+
// A non-legacy scope may edit/test only with its exact, live CP file grant.
|
|
269
|
+
if(selectedRootId!==d1RootId&&!dcRelayTask&&
|
|
270
|
+
(task.tool.arguments.r4_authorization||
|
|
271
|
+
(!task.tool.arguments.file_authorization&&task.tool.arguments.dc_relay!==true&&
|
|
272
|
+
!['list_directory','read_file','start_search','search_content',
|
|
273
|
+
'git_status','git_diff'].includes(task.tool.name))))
|
|
274
|
+
throw Error('DEV_ROOT_SCOPE_DENIED');
|
|
275
|
+
if(task.tool.arguments.dc_relay===true){
|
|
276
|
+
const a=task.tool.arguments;
|
|
277
|
+
if(!isDcPublic(task.tool.name))throw Error('DC_RELAY_DENIED');
|
|
278
|
+
// Original Desktop Commander alone handles file/command permissions.
|
|
279
|
+
const output=await callOriginalDcGeneric({client,name:task.tool.name,args:a.dc_args,
|
|
280
|
+
catalog:dcCatalog,onTrace:e=>console.log('RS_DC_RELAY',
|
|
281
|
+
JSON.stringify({request_id:task.request_id,...e}))});
|
|
282
|
+
return JSON.stringify(output);
|
|
283
|
+
}
|
|
284
|
+
const result=await executeDevDogfoodTask({tool:task.tool,rootId:selectedRootId,root:selectedRoot,
|
|
285
|
+
client,deviceId,sessionId,processes:devDogfoodProcesses,exclusion_policy,requirePolicy:true});
|
|
286
|
+
if(result!==null)return result;
|
|
287
|
+
}
|
|
288
|
+
if(isBoundedSearchName(task.tool.name)){
|
|
289
|
+
const tool=authorizeAgentBoundedSearch({tool:task.tool,enabled:boundedSearchEnabled});
|
|
290
|
+
if(!boundedSearchRun)throw new Error('TOOL_DENIED');
|
|
291
|
+
return boundedSearchRun(tool.name,tool.arguments);
|
|
292
|
+
}
|
|
293
|
+
const tool=isIsolatedReadName(task.tool.name)?authorizeIsolatedAgentRead({tool:task.tool,enabled:isolatedReadEnabled}):p2Mode?authorizeAgentExecution(task.tool):validateActiveTool(task.tool);
|
|
294
|
+
if(isIsolatedReadName(tool.name)){
|
|
295
|
+
if(!isolatedReadRun)throw new Error('TOOL_DENIED');
|
|
296
|
+
return isolatedReadRun(tool.name,tool.arguments);
|
|
297
|
+
}
|
|
298
|
+
if (tool.name === 'pwd') {
|
|
299
|
+
timing({request_id:task.request_id,tool_name:tool.name,phase:'native_begin'});
|
|
300
|
+
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'}));
|
|
301
|
+
if (result.isError) throw new Error('UPSTREAM_TOOL_ERROR');
|
|
302
|
+
return textOf(result);
|
|
303
|
+
}
|
|
304
|
+
if (tool.name === 'read_fixture') {
|
|
305
|
+
timing({request_id:task.request_id,tool_name:tool.name,phase:'native_begin'});
|
|
306
|
+
const result = await client.callTool({name: 'read_file', arguments: {path: resolve(here, 'core/fixture.txt')} }).finally(()=>timing({request_id:task.request_id,tool_name:tool.name,phase:'native_done'}));
|
|
307
|
+
if (result.isError) throw new Error('UPSTREAM_TOOL_ERROR');
|
|
308
|
+
return textOf(result);
|
|
309
|
+
}
|
|
310
|
+
throw new Error('TOOL_DENIED');
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function reportResult(task, result) {
|
|
314
|
+
timing({request_id:task.request_id,tool_name:task.tool.name,phase:'result_begin'});
|
|
315
|
+
const payload = resultEnvelope({
|
|
316
|
+
request_id: task.request_id,
|
|
317
|
+
ok: result.ok,
|
|
318
|
+
...(result.ok ? {result: result.result} : {error_code: result.error_code || ERROR_CODES.UPSTREAM_TOOL_ERROR}),
|
|
319
|
+
});
|
|
320
|
+
await post('/device/result', payload);
|
|
321
|
+
timing({request_id:task.request_id,tool_name:task.tool.name,phase:'result_done'});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function run() {
|
|
325
|
+
try {
|
|
326
|
+
await client.connect(transport);
|
|
327
|
+
connected = true;
|
|
328
|
+
if(isolatedReadEnabled&&!l2DevAgent)isolatedReadRun=makeVerifiedIsolatedReadAdapter({root:process.env.RS_55A_ROOT,client});
|
|
329
|
+
if(l2DevAgent&&d1RootId){
|
|
330
|
+
rootScopes=createRootScopeDiscovery({deviceId,legacyRootId:d1RootId,legacyRoot:d1Root});
|
|
331
|
+
devDogfoodProcesses=createDevDogfoodProcesses({rootId:d1RootId});
|
|
332
|
+
console.log('L2_ROOT_SCOPES_DISCOVERED',rootScopes.root_scopes.length);
|
|
333
|
+
// DC inspection is best-effort. It must not delay authenticated Gateway registration.
|
|
334
|
+
}
|
|
335
|
+
if(boundedSearchEnabled)boundedSearchRun=makeVerifiedBoundedSearchAdapter({root:process.env.RS_55A_ROOT,rootScopeId:process.env.RS_55B_ROOT_SCOPE_ID,client});
|
|
336
|
+
if(syntheticWriteEnabled){
|
|
337
|
+
const runtime=resolve(here,'..');
|
|
338
|
+
if(resolve(process.env.RS_P2_DEVICE_CREDENTIAL_FILE).startsWith(runtime+'/'))throw Error('C1 credential must be outside runtime');
|
|
339
|
+
syntheticWriteSupervisor=new C1Supervisor({runtime,post});
|
|
340
|
+
await syntheticWriteSupervisor.ready();
|
|
341
|
+
}
|
|
342
|
+
console.log('Device connected to Desktop Commander stdio');
|
|
343
|
+
await refreshCpHeartbeat();
|
|
344
|
+
await register();
|
|
345
|
+
gatewayKeepalive=createGatewayKeepalive({
|
|
346
|
+
heartbeat:()=>post('/device/heartbeat',{}),
|
|
347
|
+
recover:()=>register(),
|
|
348
|
+
onFailure:error=>console.warn('RS_GATEWAY_KEEPALIVE',/HTTP \d+/.exec(String(error?.message))?.[0]||'NETWORK_ERROR')
|
|
349
|
+
});
|
|
350
|
+
gatewayKeepalive.start();
|
|
351
|
+
cpHeartbeatLoop=createCpHeartbeatLoop({heartbeat:refreshCpHeartbeat,
|
|
352
|
+
onFailure:error=>console.warn('RS_CP_KEEPALIVE',/HTTP \d+/.exec(String(error?.message))?.[0]||'NETWORK_ERROR')});
|
|
353
|
+
cpHeartbeatLoop.start();
|
|
354
|
+
if(l2DevAgent&&d1RootId){
|
|
355
|
+
void inspectDcAccessBoundary(client,d1Root).then(access=>{
|
|
356
|
+
console.info('RS_DC_ACCESS_BOUNDARY',JSON.stringify(access));
|
|
357
|
+
}).catch(()=>console.warn('RS_DC_ACCESS_BOUNDARY_UNAVAILABLE'));
|
|
358
|
+
}
|
|
359
|
+
scheduleCatalogRefresh({force:true});
|
|
360
|
+
while (!stopping) {
|
|
361
|
+
try {
|
|
362
|
+
await refreshCpHeartbeat();
|
|
363
|
+
scheduleCatalogRefresh();
|
|
364
|
+
const {task: taskValue} = await post('/device/poll', {});
|
|
365
|
+
failures = 0;
|
|
366
|
+
if (taskValue) {
|
|
367
|
+
// CP policy is transferred only inside the authenticated Agent task.
|
|
368
|
+
// Remove it before the legacy per-tool exact-argument validators.
|
|
369
|
+
const policy=taskValue?.arguments?.exclusion_policy;
|
|
370
|
+
const args=taskValue?.arguments?{...taskValue.arguments}:null;
|
|
371
|
+
if(args)delete args.exclusion_policy;
|
|
372
|
+
const wireTask=l2DevAgent?{
|
|
373
|
+
request_id:taskValue.request_id,session_id:sessionId,state:'dispatched',
|
|
374
|
+
tool:{name:taskValue.name,arguments:args}
|
|
375
|
+
}:taskValue;
|
|
376
|
+
const directDc=l2DevAgent&&wireTask?.tool?.arguments?.dc_relay===true;
|
|
377
|
+
const routed=directDc?{task:wireTask,dcRelay:true}:
|
|
378
|
+
l2DevAgent&&d1RootId&&wireTask?.tool?.arguments?.root_id?
|
|
379
|
+
routeDiscoveredRootTask({wireTask,sessionId,rootScopes,legacyRootId:d1RootId,deviceId}):null;
|
|
380
|
+
const task=routed?routed.task:taskEnvelope(wireTask);
|
|
381
|
+
if(l2DevAgent){
|
|
382
|
+
const a=task.tool.arguments;
|
|
383
|
+
const legacy=task.tool.name==='list_directory'&&['.','fixtures'].includes(a.path)||
|
|
384
|
+
task.tool.name==='read_file'&&a.path==='fixtures/l2-read.txt';
|
|
385
|
+
if(!legacy&&!routed)throw Error('TOOL_DENIED');
|
|
386
|
+
}
|
|
387
|
+
if (task.session_id !== sessionId || task.state !== 'dispatched') throw new Error('SESSION_DENIED');
|
|
388
|
+
timing({request_id:task.request_id,tool_name:task.tool.name,phase:'poll_received'});
|
|
389
|
+
lifecycle({request_id:task.request_id,session_id:task.session_id,tool_name:task.tool.name,event_type:'dispatched'});
|
|
390
|
+
const startedAt=Date.now();
|
|
391
|
+
try {
|
|
392
|
+
if(routed){
|
|
393
|
+
if(!routed.dcRelay)validateExclusionPolicy(policy,{device_id:deviceId,root_id:task.tool.arguments.root_id});
|
|
394
|
+
await reportResult(task,{ok:true,result:await execute(task,policy)});
|
|
395
|
+
}else if(isSyntheticWriteName(task.tool.name)){
|
|
396
|
+
if(!syntheticWriteSupervisor||task.context.device_id!==deviceId||task.context.session_id!==sessionId)throw Error('TOOL_DENIED');
|
|
397
|
+
await syntheticWriteSupervisor.execute(task);
|
|
398
|
+
}else await reportResult(task, {ok: true, result: await execute(task)});
|
|
399
|
+
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});
|
|
400
|
+
} catch (error) {
|
|
401
|
+
const code = error?.message==='DEV_PAGE_STALE'?'DEV_PAGE_STALE':
|
|
402
|
+
error?.message==='DEV_PAGE_DENIED'?'DEV_PAGE_DENIED':
|
|
403
|
+
error.code === ERROR_CODES.TOOL_DENIED ? ERROR_CODES.TOOL_DENIED
|
|
404
|
+
: error.code === ERROR_CODES.ARGUMENTS_DENIED ? ERROR_CODES.ARGUMENTS_DENIED
|
|
405
|
+
: ERROR_CODES.UPSTREAM_TOOL_ERROR;
|
|
406
|
+
await reportResult(task, {ok: false, error_code: code});
|
|
407
|
+
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});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
} catch (error) {
|
|
411
|
+
if (stopping) break;
|
|
412
|
+
console.error('device connection:', /HTTP \d+/.exec(String(error.message))?.[0] || 'NETWORK_ERROR');
|
|
413
|
+
failures = Math.min(failures + 1, 6);
|
|
414
|
+
if (/HTTP (403|503)/.test(error.message)) {
|
|
415
|
+
try { await refreshCpHeartbeat(); await register(); } catch(error) { console.error('device register:',/HTTP \d{3}/.exec(String(error.message))?.[0]||'PROVIDER_DENIED'); }
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
if (!stopping) await new Promise(resolveDelay => setTimeout(resolveDelay, Math.min(5000, 200 * 2 ** failures)));
|
|
419
|
+
}
|
|
420
|
+
} finally {
|
|
421
|
+
gatewayKeepalive?.stop();
|
|
422
|
+
cpHeartbeatLoop?.stop();
|
|
423
|
+
syntheticWriteSupervisor?.close();
|
|
424
|
+
devDogfoodProcesses?.close({deviceId,sessionId});
|
|
425
|
+
await boundedSearchRun?.close().catch(()=>{});
|
|
426
|
+
if (connected) await client.close();
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
run().catch(error => {
|
|
431
|
+
const code=/^C1_[A-Z_]+$/.test(error?.message)?error.message:'INITIALIZATION_FAILED';
|
|
432
|
+
console.error('device startup:',code);
|
|
433
|
+
process.exitCode = 1;
|
|
434
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import {lstatSync,readdirSync,realpathSync} from 'node:fs';
|
|
2
|
+
import {isAbsolute,relative,resolve,sep} from 'node:path';
|
|
3
|
+
import {validateReadPath,resolveReadTarget} from '../../shared/lib/isolated-read-boundary.mjs';
|
|
4
|
+
import {BOUNDED_SEARCH_LIMITS} from '../../shared/lib/bounded-search-contract.mjs';
|
|
5
|
+
|
|
6
|
+
const deny=()=>{throw new Error('SEARCH_SCOPE_DENIED');};
|
|
7
|
+
const utf8Prefix=(value,max)=>{let out='';for(const cp of value){if(Buffer.byteLength(out+cp)>max)break;out+=cp;}return out;};
|
|
8
|
+
const textOf=result=>{if(result?.isError||!Array.isArray(result.content)||result.content.some(x=>x.type!=='text'||typeof x.text!=='string'))deny();const text=result.content.map(x=>x.text).join('\n');if(Buffer.byteLength(text)>BOUNDED_SEARCH_LIMITS.maxSessionBytes)deny();return text;};
|
|
9
|
+
function scanTree(root){
|
|
10
|
+
let entries=0,totalBytes=0;
|
|
11
|
+
const visit=(dir,depth)=>{
|
|
12
|
+
if(depth>BOUNDED_SEARCH_LIMITS.maxDepth)deny();
|
|
13
|
+
for(const name of readdirSync(dir)){
|
|
14
|
+
entries++;if(entries>BOUNDED_SEARCH_LIMITS.maxEntries)deny();
|
|
15
|
+
const abs=resolve(dir,name),rel=relative(root,abs).split(sep).join('/');
|
|
16
|
+
validateReadPath(rel);
|
|
17
|
+
const stat=lstatSync(abs);if(stat.isSymbolicLink()||!stat.isFile()&&!stat.isDirectory())deny();
|
|
18
|
+
if(stat.isDirectory())visit(abs,depth+1);
|
|
19
|
+
else {if(stat.size>BOUNDED_SEARCH_LIMITS.maxFileBytes)deny();totalBytes+=stat.size;if(totalBytes>BOUNDED_SEARCH_LIMITS.maxTreeBytes)deny();}
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
visit(root,0);
|
|
23
|
+
}
|
|
24
|
+
function relativeResultPath(root,value){
|
|
25
|
+
if(typeof value!=='string'||!isAbsolute(value))deny();
|
|
26
|
+
const resolved=resolve(value),rel=relative(root,resolved);
|
|
27
|
+
if(!rel||rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))deny();
|
|
28
|
+
const safe=rel.split(sep).join('/');validateReadPath(safe);
|
|
29
|
+
const stat=lstatSync(resolved);if(stat.isSymbolicLink()||!stat.isFile())deny();
|
|
30
|
+
const real=realpathSync(resolved);if(real!==resolved)deny();
|
|
31
|
+
return safe;
|
|
32
|
+
}
|
|
33
|
+
function parseSearchText(text,root){
|
|
34
|
+
const sid=/(?:Started (?:file|content) search session:|Search session:)\s*(search_[A-Za-z0-9_-]+)/.exec(text)?.[1];
|
|
35
|
+
const status=/^Status:\s*(RUNNING|COMPLETED|STOPPED|FAILED)\s*$/m.exec(text)?.[1]??(/terminated successfully/i.test(text)?'STOPPED':undefined);
|
|
36
|
+
const totalMatch=/^Total results:\s*(\d+)\s+match(?:es)?\s*$/im.exec(text);
|
|
37
|
+
const pageMatch=/^Showing results\s+(\d+)-(\d+)(?:\s+of\s+\d+)?\s*$/im.exec(text);
|
|
38
|
+
const emptyOffset=/^No results at offset\s+(\d+)\b/im.exec(text);
|
|
39
|
+
const emptyTotal=/^No results at offset\s+\d+\s+\((\d+)\s+in total\)/im.exec(text);
|
|
40
|
+
const bodyStart=Math.max(text.lastIndexOf('\nResults:'),text.lastIndexOf('\nInitial results:'));
|
|
41
|
+
const body=bodyStart<0?'':text.slice(bodyStart).split('\n').slice(1);
|
|
42
|
+
const results=[];
|
|
43
|
+
for(const line of body){
|
|
44
|
+
let m=/^📁\s+(.+)$/.exec(line);
|
|
45
|
+
if(m){const path=relativeResultPath(root,m[1]);results.push({path,type:'file'});continue;}
|
|
46
|
+
m=/^📄\s+(.+?):(\d+)\s+-\s?(.*)$/.exec(line);
|
|
47
|
+
if(m){const path=relativeResultPath(root,m[1]),lineNumber=Number(m[2]);if(!Number.isSafeInteger(lineNumber)||lineNumber<1)deny();results.push({path,type:'content',line:lineNumber,snippet:utf8Prefix(m[3],BOUNDED_SEARCH_LIMITS.maxSnippetBytes)});continue;}
|
|
48
|
+
}
|
|
49
|
+
return {sessionId:sid,status:status??(emptyOffset?'COMPLETED':undefined),totalResults:totalMatch?Number(totalMatch[1]):emptyTotal?Number(emptyTotal[1]):undefined,offset:pageMatch?Number(pageMatch[1]):emptyOffset?Number(emptyOffset[1]):0,results};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function makeBoundedSearchAdapter({root,rootScopeId,client,verifyRoot=()=>{}}={}){
|
|
53
|
+
if(typeof root!=='string'||typeof rootScopeId!=='string'||!/^[A-Za-z0-9_-]{16,128}$/.test(rootScopeId)||!client||typeof client.callTool!=='function')throw new Error('BOUNDED_SEARCH_DISABLED');
|
|
54
|
+
const canonicalRoot=realpathSync(root),active=new Map();
|
|
55
|
+
const verified=()=>{verifyRoot(canonicalRoot);const target=resolveReadTarget(canonicalRoot,'.',{type:'directory',maxEntries:BOUNDED_SEARCH_LIMITS.maxEntries});scanTree(canonicalRoot);return target.root;};
|
|
56
|
+
const call=async(name,args)=>textOf(await client.callTool({name,arguments:args}));
|
|
57
|
+
const resultEnvelope=value=>{const text=JSON.stringify(value);if(Buffer.byteLength(text)>BOUNDED_SEARCH_LIMITS.maxPageBytes)deny();return text;};
|
|
58
|
+
async function execute(name,args){
|
|
59
|
+
for(const [id,session] of active){if(Date.now()>=session.expiresAt){clearTimeout(session.timer);active.delete(id);await client.callTool({name:'stop_search',arguments:{sessionId:id}}).catch(()=>{});}}
|
|
60
|
+
const rootNow=verified();if(rootNow!==canonicalRoot)deny();
|
|
61
|
+
if(name==='list_searches'){
|
|
62
|
+
if(Object.keys(args).length)deny();
|
|
63
|
+
const raw=await call(name,{}),sessions=[];
|
|
64
|
+
if(raw!=='No active searches.'&&!raw.startsWith('Active Searches ('))deny();
|
|
65
|
+
for(const block of raw.split(/^Session: /m).slice(1)){
|
|
66
|
+
const id=block.split('\n')[0].trim(),status=/^ Status: (?:🔄 |✅ |❌ )?(RUNNING|COMPLETED|ERROR)\s*$/m.exec(block)?.[1];
|
|
67
|
+
if(!/^search_[A-Za-z0-9_-]{1,120}$/.test(id)||!status)deny();
|
|
68
|
+
if(active.has(id)){if(sessions.some(x=>x.sessionId===id))deny();sessions.push({sessionId:id,status});}
|
|
69
|
+
}
|
|
70
|
+
if(sessions.length>BOUNDED_SEARCH_LIMITS.maxSessions)deny();
|
|
71
|
+
return resultEnvelope({kind:'list',rootScopeId,sessions});
|
|
72
|
+
}
|
|
73
|
+
if(name==='start_search'){
|
|
74
|
+
if(active.size>=BOUNDED_SEARCH_LIMITS.maxSessions)deny();
|
|
75
|
+
const safe=validateReadPath(args.path,{allowRoot:true});
|
|
76
|
+
const target=resolveReadTarget(canonicalRoot,safe,{type:'directory',maxEntries:BOUNDED_SEARCH_LIMITS.maxEntries});
|
|
77
|
+
if(Buffer.byteLength(args.pattern,'utf8')>BOUNDED_SEARCH_LIMITS.maxPatternBytes)deny();
|
|
78
|
+
const filePattern=args.filePattern;
|
|
79
|
+
const nativeArgs={path:target.path,pattern:args.pattern,searchType:args.searchType,filePattern,ignoreCase:args.ignoreCase,maxResults:args.maxResults,includeHidden:false,contextLines:2,timeout_ms:BOUNDED_SEARCH_LIMITS.searchTimeoutMs,earlyTermination:false,literalSearch:args.literalSearch};
|
|
80
|
+
for(const key of Object.keys(nativeArgs))if(nativeArgs[key]===undefined)delete nativeArgs[key];
|
|
81
|
+
const started=parseSearchText(await call('start_search',nativeArgs),canonicalRoot);
|
|
82
|
+
if(!started.sessionId||!/^search_[A-Za-z0-9_-]+$/.test(started.sessionId)){deny();}
|
|
83
|
+
const session={expiresAt:Date.now()+120000,timer:null,totalResults:started.totalResults};
|
|
84
|
+
session.timer=setTimeout(()=>{if(active.get(started.sessionId)===session){active.delete(started.sessionId);void client.callTool({name:'stop_search',arguments:{sessionId:started.sessionId}}).catch(()=>{});}},120000);
|
|
85
|
+
session.timer.unref?.();active.set(started.sessionId,session);
|
|
86
|
+
try{
|
|
87
|
+
if(!['RUNNING','COMPLETED'].includes(started.status)||!Number.isSafeInteger(started.totalResults)||started.totalResults>(args.maxResults??BOUNDED_SEARCH_LIMITS.maxResults)||started.results.length>started.totalResults)deny();
|
|
88
|
+
const results=started.results.slice(0,BOUNDED_SEARCH_LIMITS.maxPage);
|
|
89
|
+
const value={kind:'start',sessionId:started.sessionId,rootScopeId,searchType:args.searchType,status:started.status,totalResults:started.totalResults,offset:0,results};
|
|
90
|
+
return resultEnvelope(value);
|
|
91
|
+
}catch(error){clearTimeout(session.timer);active.delete(started.sessionId);await client.callTool({name:'stop_search',arguments:{sessionId:started.sessionId}}).catch(()=>{});throw error;}
|
|
92
|
+
}
|
|
93
|
+
if(name==='get_more_search_results'){
|
|
94
|
+
const sid=args.sessionId;if(!active.has(sid))deny();
|
|
95
|
+
const page=parseSearchText(await call(name,{sessionId:sid,offset:args.offset,length:args.length}),canonicalRoot);
|
|
96
|
+
const totalResults=page.totalResults??active.get(sid).totalResults;
|
|
97
|
+
// Reject malformed or cross-session pages without exposing native search handles.
|
|
98
|
+
// Distinct fixed codes identify the *first* failing invariant in native E2E.
|
|
99
|
+
if(page.sessionId!==sid)throw Error('SEARCH_PAGE_SESSION_DENIED');
|
|
100
|
+
if(!['RUNNING','COMPLETED'].includes(page.status))throw Error('SEARCH_PAGE_STATUS_DENIED');
|
|
101
|
+
if(!Number.isSafeInteger(totalResults)||totalResults<0||totalResults>BOUNDED_SEARCH_LIMITS.maxResults)throw Error('SEARCH_PAGE_TOTAL_INVALID');
|
|
102
|
+
if(totalResults!==active.get(sid).totalResults)throw Error('SEARCH_PAGE_TOTAL_CHANGED');
|
|
103
|
+
if(page.results.length>args.length)throw Error('SEARCH_PAGE_LENGTH_DENIED');
|
|
104
|
+
return resultEnvelope({kind:'page',sessionId:sid,rootScopeId,status:page.status,totalResults,offset:args.offset,results:page.results});
|
|
105
|
+
}
|
|
106
|
+
if(name==='stop_search'){
|
|
107
|
+
const sid=args.sessionId;if(!active.has(sid))deny();
|
|
108
|
+
const response=await call(name,{sessionId:sid});if(!/terminated successfully/i.test(response))deny();
|
|
109
|
+
clearTimeout(active.get(sid).timer);active.delete(sid);return resultEnvelope({kind:'stop',sessionId:sid,rootScopeId,stopped:true});
|
|
110
|
+
}
|
|
111
|
+
deny();
|
|
112
|
+
}
|
|
113
|
+
execute.close=async()=>{for(const [sessionId,session] of active){clearTimeout(session.timer);await client.callTool({name:'stop_search',arguments:{sessionId}}).catch(()=>{});}active.clear();};
|
|
114
|
+
return execute;
|
|
115
|
+
}
|