remotelink 0.3.9 → 0.3.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/README.md +10 -3
- package/dist/index.js +249 -22
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -90,9 +90,11 @@ request to another service, or mutating a remote database.
|
|
|
90
90
|
|
|
91
91
|
## Workspace and sensitive-path policy
|
|
92
92
|
|
|
93
|
-
The dashboard can configure allowed workspace roots
|
|
94
|
-
paths per device. Sensitive-path
|
|
95
|
-
credential locations and `.env`
|
|
93
|
+
The dashboard can configure allowed workspace roots, additional protected
|
|
94
|
+
paths, and narrow sensitive-path exceptions per device. Sensitive-path
|
|
95
|
+
protection stays on by default for common credential locations and `.env`
|
|
96
|
+
files; an exception bypasses only sensitive-path protection, not Workspace
|
|
97
|
+
Scope.
|
|
96
98
|
|
|
97
99
|
Filesystem paths are canonicalized and checked locally immediately before
|
|
98
100
|
execution. If workspace roots are configured, file operations must stay under
|
|
@@ -107,6 +109,11 @@ deletion, disk formatting or raw-disk overwrite, fork bombs, and machine
|
|
|
107
109
|
shutdown/reboot. These checks happen on the device before the command reaches
|
|
108
110
|
the local execution core.
|
|
109
111
|
|
|
112
|
+
Full mode also supports managed background processes. `start_process` can
|
|
113
|
+
return a local process id, and `process_status`, `process_output`, and
|
|
114
|
+
`stop_process` manage that process without introducing another execution
|
|
115
|
+
backend.
|
|
116
|
+
|
|
110
117
|
## Security
|
|
111
118
|
|
|
112
119
|
- Each computer receives its own revocable credential.
|
package/dist/index.js
CHANGED
|
@@ -20,10 +20,11 @@ var printableSize = (bytes) => {
|
|
|
20
20
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
21
21
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
22
22
|
};
|
|
23
|
-
async function listDirectory(targetPath, depth = 2) {
|
|
23
|
+
async function listDirectory(targetPath, depth = 2, canReveal) {
|
|
24
24
|
const maxDepth = Math.max(1, Math.min(10, Math.trunc(depth || 2)));
|
|
25
25
|
const lines = [];
|
|
26
26
|
let entriesSeen = 0;
|
|
27
|
+
let protectedEntries = 0;
|
|
27
28
|
async function walk(directory, level, prefix) {
|
|
28
29
|
if (entriesSeen >= MAX_DIRECTORY_ENTRIES) return;
|
|
29
30
|
const entries = await fs.readdir(directory, { withFileTypes: true });
|
|
@@ -33,8 +34,12 @@ async function listDirectory(targetPath, depth = 2) {
|
|
|
33
34
|
});
|
|
34
35
|
for (const entry of entries) {
|
|
35
36
|
if (entriesSeen >= MAX_DIRECTORY_ENTRIES) break;
|
|
36
|
-
entriesSeen += 1;
|
|
37
37
|
const absolute = path.join(directory, entry.name);
|
|
38
|
+
if (canReveal && !await canReveal(absolute)) {
|
|
39
|
+
protectedEntries += 1;
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
entriesSeen += 1;
|
|
38
43
|
const label = entry.isDirectory() ? "[DIR]" : entry.isSymbolicLink() ? "[LINK]" : "[FILE]";
|
|
39
44
|
lines.push(`${prefix}${label} ${entry.name}`);
|
|
40
45
|
if (entry.isDirectory() && level < maxDepth) {
|
|
@@ -48,10 +53,13 @@ async function listDirectory(targetPath, depth = 2) {
|
|
|
48
53
|
if (entriesSeen >= MAX_DIRECTORY_ENTRIES) {
|
|
49
54
|
lines.push(`\u2026 truncated after ${MAX_DIRECTORY_ENTRIES} entries`);
|
|
50
55
|
}
|
|
56
|
+
const protectionNote = protectedEntries ? `
|
|
57
|
+
|
|
58
|
+
[Remote Arc omitted ${protectedEntries} protected or out-of-scope entr${protectedEntries === 1 ? "y" : "ies"}.]` : "";
|
|
51
59
|
return `Directory: ${targetPath}
|
|
52
60
|
Depth: ${maxDepth}
|
|
53
61
|
|
|
54
|
-
${lines.join("\n") || "(empty)"}`;
|
|
62
|
+
${lines.join("\n") || "(empty)"}${protectionNote}`;
|
|
55
63
|
}
|
|
56
64
|
async function readTextFile(targetPath, offset, length) {
|
|
57
65
|
const stat = await fs.stat(targetPath);
|
|
@@ -144,6 +152,7 @@ async function editTextBlock(filePath, oldString, newString, expectedReplacement
|
|
|
144
152
|
|
|
145
153
|
// ../execution-core/src/process.ts
|
|
146
154
|
import { execFile, spawn } from "child_process";
|
|
155
|
+
import crypto2 from "crypto";
|
|
147
156
|
import process2 from "process";
|
|
148
157
|
var MAX_CAPTURE_BYTES = 2 * 1024 * 1024;
|
|
149
158
|
function appendCapped(current, chunk) {
|
|
@@ -242,9 +251,139 @@ async function runShellCommand(command, timeoutMs = 5e3, cwd) {
|
|
|
242
251
|
});
|
|
243
252
|
});
|
|
244
253
|
}
|
|
254
|
+
var managedProcesses = /* @__PURE__ */ new Map();
|
|
255
|
+
var MAX_MANAGED_PROCESSES = 32;
|
|
256
|
+
var FINISHED_PROCESS_RETENTION_MS = 30 * 60 * 1e3;
|
|
257
|
+
function cleanupManagedProcesses() {
|
|
258
|
+
const now = Date.now();
|
|
259
|
+
for (const [id, item] of managedProcesses) {
|
|
260
|
+
if (item.endedAt !== null && now - item.endedAt > FINISHED_PROCESS_RETENTION_MS) {
|
|
261
|
+
managedProcesses.delete(id);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (managedProcesses.size <= MAX_MANAGED_PROCESSES) return;
|
|
265
|
+
const finished = [...managedProcesses.values()].filter((item) => item.endedAt !== null).sort((a, b) => (a.endedAt || 0) - (b.endedAt || 0));
|
|
266
|
+
for (const item of finished) {
|
|
267
|
+
if (managedProcesses.size <= MAX_MANAGED_PROCESSES) break;
|
|
268
|
+
managedProcesses.delete(item.id);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
async function startBackgroundProcess(command, cwd) {
|
|
272
|
+
cleanupManagedProcesses();
|
|
273
|
+
if (managedProcesses.size >= MAX_MANAGED_PROCESSES) {
|
|
274
|
+
throw new Error(
|
|
275
|
+
"Remote Arc already has the maximum number of managed background processes on this device."
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
const child = spawn(command, {
|
|
279
|
+
shell: true,
|
|
280
|
+
cwd,
|
|
281
|
+
windowsHide: true,
|
|
282
|
+
detached: process2.platform !== "win32",
|
|
283
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
284
|
+
});
|
|
285
|
+
const id = crypto2.randomUUID();
|
|
286
|
+
const item = {
|
|
287
|
+
id,
|
|
288
|
+
child,
|
|
289
|
+
command,
|
|
290
|
+
cwd: cwd || null,
|
|
291
|
+
startedAt: Date.now(),
|
|
292
|
+
endedAt: null,
|
|
293
|
+
exitCode: null,
|
|
294
|
+
signal: null,
|
|
295
|
+
stdout: "",
|
|
296
|
+
stderr: ""
|
|
297
|
+
};
|
|
298
|
+
managedProcesses.set(id, item);
|
|
299
|
+
child.stdout?.on("data", (chunk) => {
|
|
300
|
+
item.stdout = appendCapped(item.stdout, chunk);
|
|
301
|
+
});
|
|
302
|
+
child.stderr?.on("data", (chunk) => {
|
|
303
|
+
item.stderr = appendCapped(item.stderr, chunk);
|
|
304
|
+
});
|
|
305
|
+
child.once("error", (error) => {
|
|
306
|
+
item.stderr = appendCapped(item.stderr, "\n" + error.message);
|
|
307
|
+
item.endedAt = Date.now();
|
|
308
|
+
});
|
|
309
|
+
child.once("close", (code, signal) => {
|
|
310
|
+
item.exitCode = code;
|
|
311
|
+
item.signal = signal;
|
|
312
|
+
item.endedAt = Date.now();
|
|
313
|
+
});
|
|
314
|
+
return {
|
|
315
|
+
process_id: id,
|
|
316
|
+
pid: child.pid || null,
|
|
317
|
+
command,
|
|
318
|
+
cwd: cwd || null,
|
|
319
|
+
status: "running",
|
|
320
|
+
started_at: new Date(item.startedAt).toISOString()
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function managedProcessOrThrow(processId) {
|
|
324
|
+
cleanupManagedProcesses();
|
|
325
|
+
const item = managedProcesses.get(processId);
|
|
326
|
+
if (!item) {
|
|
327
|
+
throw new Error(
|
|
328
|
+
"Managed process not found or its local retention window has expired."
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
return item;
|
|
332
|
+
}
|
|
333
|
+
function getManagedProcessStatus(processId) {
|
|
334
|
+
const item = managedProcessOrThrow(processId);
|
|
335
|
+
return {
|
|
336
|
+
process_id: item.id,
|
|
337
|
+
pid: item.child.pid || null,
|
|
338
|
+
command: item.command,
|
|
339
|
+
cwd: item.cwd,
|
|
340
|
+
status: item.endedAt === null ? "running" : "exited",
|
|
341
|
+
exit_code: item.exitCode,
|
|
342
|
+
signal: item.signal,
|
|
343
|
+
started_at: new Date(item.startedAt).toISOString(),
|
|
344
|
+
ended_at: item.endedAt === null ? null : new Date(item.endedAt).toISOString(),
|
|
345
|
+
duration_ms: (item.endedAt || Date.now()) - item.startedAt
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function readManagedProcessOutput(processId) {
|
|
349
|
+
const item = managedProcessOrThrow(processId);
|
|
350
|
+
return {
|
|
351
|
+
...getManagedProcessStatus(processId),
|
|
352
|
+
stdout: item.stdout,
|
|
353
|
+
stderr: item.stderr,
|
|
354
|
+
truncated: Buffer.byteLength(item.stdout) >= MAX_CAPTURE_BYTES || Buffer.byteLength(item.stderr) >= MAX_CAPTURE_BYTES
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
async function stopManagedProcess(processId) {
|
|
358
|
+
const item = managedProcessOrThrow(processId);
|
|
359
|
+
if (item.endedAt !== null) {
|
|
360
|
+
return {
|
|
361
|
+
...getManagedProcessStatus(processId),
|
|
362
|
+
stopped: false,
|
|
363
|
+
already_exited: true
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
await terminateTree(item.child);
|
|
367
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
368
|
+
return {
|
|
369
|
+
...getManagedProcessStatus(processId),
|
|
370
|
+
stopped: true,
|
|
371
|
+
already_exited: false
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
async function stopAllManagedProcesses() {
|
|
375
|
+
const running = [...managedProcesses.values()].filter(
|
|
376
|
+
(item) => item.endedAt === null
|
|
377
|
+
);
|
|
378
|
+
await Promise.all(
|
|
379
|
+
running.map(async (item) => {
|
|
380
|
+
await terminateTree(item.child).catch(() => void 0);
|
|
381
|
+
})
|
|
382
|
+
);
|
|
383
|
+
}
|
|
245
384
|
|
|
246
385
|
// ../execution-core/src/safety.ts
|
|
247
|
-
import
|
|
386
|
+
import crypto3 from "crypto";
|
|
248
387
|
import { createReadStream } from "fs";
|
|
249
388
|
import fs2 from "fs/promises";
|
|
250
389
|
import os from "os";
|
|
@@ -320,7 +459,7 @@ async function createUndoSnapshot(tool, args) {
|
|
|
320
459
|
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
321
460
|
if (code !== "ENOENT") throw error;
|
|
322
461
|
}
|
|
323
|
-
const id = `${Date.now()}-${
|
|
462
|
+
const id = `${Date.now()}-${crypto3.randomUUID().slice(0, 8)}`;
|
|
324
463
|
const directory = path2.join(undoRoot(), id);
|
|
325
464
|
await fs2.mkdir(directory, { recursive: true, mode: 448 });
|
|
326
465
|
if (original) {
|
|
@@ -344,7 +483,7 @@ async function createUndoSnapshot(tool, args) {
|
|
|
344
483
|
return { id, directory, manifest };
|
|
345
484
|
}
|
|
346
485
|
async function hashFile(filePath) {
|
|
347
|
-
const hash =
|
|
486
|
+
const hash = crypto3.createHash("sha256");
|
|
348
487
|
for await (const chunk of createReadStream(filePath)) hash.update(chunk);
|
|
349
488
|
return hash.digest("hex");
|
|
350
489
|
}
|
|
@@ -380,16 +519,34 @@ async function undoCandidates() {
|
|
|
380
519
|
return candidates;
|
|
381
520
|
}
|
|
382
521
|
async function listUndoActions(limit = 20) {
|
|
383
|
-
const candidates = await undoCandidates()
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
522
|
+
const candidates = (await undoCandidates()).slice(
|
|
523
|
+
0,
|
|
524
|
+
Math.max(1, Math.min(100, Math.trunc(limit)))
|
|
525
|
+
);
|
|
526
|
+
return Promise.all(
|
|
527
|
+
candidates.map(async ({ manifest }) => {
|
|
528
|
+
let status = "legacy";
|
|
529
|
+
if (manifest.postChangeHash) {
|
|
530
|
+
try {
|
|
531
|
+
const currentHash = await hashFile(manifest.targetPath);
|
|
532
|
+
status = currentHash === manifest.postChangeHash ? "ready" : "conflict";
|
|
533
|
+
} catch {
|
|
534
|
+
status = "missing";
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return {
|
|
538
|
+
id: manifest.id,
|
|
539
|
+
created_at: manifest.createdAt,
|
|
540
|
+
tool: manifest.tool,
|
|
541
|
+
path: manifest.targetPath,
|
|
542
|
+
bytes: manifest.bytes,
|
|
543
|
+
existed_before: manifest.existed,
|
|
544
|
+
conflict_safe: Boolean(manifest.postChangeHash),
|
|
545
|
+
can_undo: status === "ready",
|
|
546
|
+
status
|
|
547
|
+
};
|
|
548
|
+
})
|
|
549
|
+
);
|
|
393
550
|
}
|
|
394
551
|
async function restoreUndoCandidate(candidate) {
|
|
395
552
|
const { directory, manifest } = candidate;
|
|
@@ -596,9 +753,15 @@ async function enforcePathPolicy(targetPath, policy = {}) {
|
|
|
596
753
|
const sensitiveRoots = await Promise.all(
|
|
597
754
|
sensitiveInputs.map(canonicalTarget)
|
|
598
755
|
);
|
|
599
|
-
|
|
756
|
+
const allowedSensitiveRoots = await Promise.all(
|
|
757
|
+
(policy.sensitiveAllowPaths || []).filter((item) => typeof item === "string" && item.trim()).map(canonicalTarget)
|
|
758
|
+
);
|
|
759
|
+
const explicitlyAllowed = allowedSensitiveRoots.some(
|
|
760
|
+
(root) => isInside(target, root)
|
|
761
|
+
);
|
|
762
|
+
if (!explicitlyAllowed && (looksLikeSensitiveFile(target) || sensitiveRoots.some((root) => isInside(target, root)))) {
|
|
600
763
|
throw new Error(
|
|
601
|
-
"Blocked by Remote Arc Sensitive Path Policy.
|
|
764
|
+
"Blocked by Remote Arc Sensitive Path Policy. Add a narrow sensitive-path exception for this device if you intentionally need access."
|
|
602
765
|
);
|
|
603
766
|
}
|
|
604
767
|
}
|
|
@@ -613,6 +776,9 @@ function normalizePolicy(policy) {
|
|
|
613
776
|
sensitivePaths: Array.from(
|
|
614
777
|
new Set((policy?.sensitivePaths || []).filter((item) => typeof item === "string" && item.trim()))
|
|
615
778
|
).slice(0, 32),
|
|
779
|
+
sensitiveAllowPaths: Array.from(
|
|
780
|
+
new Set((policy?.sensitiveAllowPaths || []).filter((item) => typeof item === "string" && item.trim()))
|
|
781
|
+
).slice(0, 32),
|
|
616
782
|
undoEnabled: policy?.undoEnabled !== false
|
|
617
783
|
};
|
|
618
784
|
}
|
|
@@ -634,7 +800,10 @@ var DEVELOPER_TOOLS = /* @__PURE__ */ new Set([
|
|
|
634
800
|
]);
|
|
635
801
|
var FULL_TOOLS = /* @__PURE__ */ new Set([
|
|
636
802
|
...DEVELOPER_TOOLS,
|
|
637
|
-
"start_process"
|
|
803
|
+
"start_process",
|
|
804
|
+
"process_status",
|
|
805
|
+
"process_output",
|
|
806
|
+
"stop_process"
|
|
638
807
|
]);
|
|
639
808
|
var DEFINITIONS = [
|
|
640
809
|
{
|
|
@@ -744,11 +913,42 @@ var DEFINITIONS = [
|
|
|
744
913
|
properties: {
|
|
745
914
|
command: { type: "string" },
|
|
746
915
|
timeout_ms: { type: "integer", minimum: 100, maximum: 12e4, default: 5e3 },
|
|
747
|
-
cwd: { type: "string" }
|
|
916
|
+
cwd: { type: "string" },
|
|
917
|
+
background: { type: "boolean", default: false }
|
|
748
918
|
},
|
|
749
919
|
required: ["command"],
|
|
750
920
|
additionalProperties: false
|
|
751
921
|
}
|
|
922
|
+
},
|
|
923
|
+
{
|
|
924
|
+
name: "process_status",
|
|
925
|
+
description: "Get status for a Remote Arc managed background process.",
|
|
926
|
+
inputSchema: {
|
|
927
|
+
type: "object",
|
|
928
|
+
properties: { process_id: { type: "string" } },
|
|
929
|
+
required: ["process_id"],
|
|
930
|
+
additionalProperties: false
|
|
931
|
+
}
|
|
932
|
+
},
|
|
933
|
+
{
|
|
934
|
+
name: "process_output",
|
|
935
|
+
description: "Read captured stdout and stderr from a Remote Arc managed background process.",
|
|
936
|
+
inputSchema: {
|
|
937
|
+
type: "object",
|
|
938
|
+
properties: { process_id: { type: "string" } },
|
|
939
|
+
required: ["process_id"],
|
|
940
|
+
additionalProperties: false
|
|
941
|
+
}
|
|
942
|
+
},
|
|
943
|
+
{
|
|
944
|
+
name: "stop_process",
|
|
945
|
+
description: "Stop a Remote Arc managed background process and its child process tree.",
|
|
946
|
+
inputSchema: {
|
|
947
|
+
type: "object",
|
|
948
|
+
properties: { process_id: { type: "string" } },
|
|
949
|
+
required: ["process_id"],
|
|
950
|
+
additionalProperties: false
|
|
951
|
+
}
|
|
752
952
|
}
|
|
753
953
|
];
|
|
754
954
|
var textResult = (value) => ({
|
|
@@ -796,7 +996,18 @@ var RemoteArcExecutionCore = class {
|
|
|
796
996
|
case "list_directory": {
|
|
797
997
|
const target = await enforcePathPolicy(requiredString(args, "path"), policy);
|
|
798
998
|
return textResult(
|
|
799
|
-
await listDirectory(
|
|
999
|
+
await listDirectory(
|
|
1000
|
+
target,
|
|
1001
|
+
optionalNumber(args, "depth") ?? 2,
|
|
1002
|
+
async (candidate) => {
|
|
1003
|
+
try {
|
|
1004
|
+
await enforcePathPolicy(candidate, policy);
|
|
1005
|
+
return true;
|
|
1006
|
+
} catch {
|
|
1007
|
+
return false;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
)
|
|
800
1011
|
);
|
|
801
1012
|
}
|
|
802
1013
|
case "read_file": {
|
|
@@ -863,6 +1074,9 @@ var RemoteArcExecutionCore = class {
|
|
|
863
1074
|
);
|
|
864
1075
|
}
|
|
865
1076
|
const cwd = cwdInput ? await enforcePathPolicy(cwdInput, policy) : void 0;
|
|
1077
|
+
if (args.background === true) {
|
|
1078
|
+
return textResult(await startBackgroundProcess(command, cwd));
|
|
1079
|
+
}
|
|
866
1080
|
return textResult(
|
|
867
1081
|
await runShellCommand(
|
|
868
1082
|
command,
|
|
@@ -871,6 +1085,18 @@ var RemoteArcExecutionCore = class {
|
|
|
871
1085
|
)
|
|
872
1086
|
);
|
|
873
1087
|
}
|
|
1088
|
+
case "process_status":
|
|
1089
|
+
return textResult(
|
|
1090
|
+
getManagedProcessStatus(requiredString(args, "process_id"))
|
|
1091
|
+
);
|
|
1092
|
+
case "process_output":
|
|
1093
|
+
return textResult(
|
|
1094
|
+
readManagedProcessOutput(requiredString(args, "process_id"))
|
|
1095
|
+
);
|
|
1096
|
+
case "stop_process":
|
|
1097
|
+
return textResult(
|
|
1098
|
+
await stopManagedProcess(requiredString(args, "process_id"))
|
|
1099
|
+
);
|
|
874
1100
|
case "write_file":
|
|
875
1101
|
case "edit_block": {
|
|
876
1102
|
const pathKey = toolName === "write_file" ? "path" : "file_path";
|
|
@@ -904,11 +1130,12 @@ var RemoteArcExecutionCore = class {
|
|
|
904
1130
|
}
|
|
905
1131
|
}
|
|
906
1132
|
async close() {
|
|
1133
|
+
await stopAllManagedProcesses();
|
|
907
1134
|
}
|
|
908
1135
|
};
|
|
909
1136
|
|
|
910
1137
|
// src/index.ts
|
|
911
|
-
var VERSION = "0.3.
|
|
1138
|
+
var VERSION = "0.3.11";
|
|
912
1139
|
var DEFAULT_ORIGIN = "https://mcp.remotearc.app";
|
|
913
1140
|
var CONFIG_DIR = path4.join(os3.homedir(), ".remotearc");
|
|
914
1141
|
var CONFIG_PATH = path4.join(CONFIG_DIR, "config.json");
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../execution-core/src/filesystem.ts","../../execution-core/src/process.ts","../../execution-core/src/safety.ts","../../execution-core/src/policy.ts","../../execution-core/src/core.ts"],"sourcesContent":["#!/usr/bin/env node\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { spawn } from \"node:child_process\";\nimport process from \"node:process\";\nimport WebSocket from \"ws\";\nimport {\n RemoteArcExecutionCore,\n type ExecutionPolicy,\n} from \"@remotearc/execution-core\";\n\nconst VERSION = \"0.3.9\";\nconst DEFAULT_ORIGIN = \"https://mcp.remotearc.app\";\nconst CONFIG_DIR = path.join(os.homedir(), \".remotearc\");\nconst CONFIG_PATH = path.join(CONFIG_DIR, \"config.json\");\nconst LEGACY_CONFIG_PATH = path.join(os.homedir(), \".remote-link\", \"config.json\");\n\ntype Mode = \"managed\" | \"safe\" | \"developer\";\n\ntype SavedConfig = {\n deviceId: string;\n deviceToken: string;\n deviceName: string;\n origin: string;\n mode: Mode;\n};\n\ntype PairingStart = {\n device_code: string;\n device_secret: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete: string;\n expires_in: number;\n interval: number;\n};\n\ntype PairingToken = {\n device_id: string;\n device_token: string;\n relay_url: string;\n};\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst supportsColor = process.stdout.isTTY && !process.env.NO_COLOR;\nconst paint = (code: string, value: string) =>\n supportsColor ? `\\x1b[${code}m${value}\\x1b[0m` : value;\nconst dim = (value: string) => paint(\"2\", value);\nconst cyan = (value: string) => paint(\"36\", value);\nconst green = (value: string) => paint(\"32\", value);\nconst yellow = (value: string) => paint(\"33\", value);\nconst red = (value: string) => paint(\"31\", value);\nconst bold = (value: string) => paint(\"1\", value);\n\nfunction nowTime() {\n return new Date().toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n}\n\nfunction logLine(\n level: \"info\" | \"success\" | \"warn\" | \"error\" | \"event\",\n message: string,\n) {\n const icon =\n level === \"success\" ? green(\"✓\") :\n level === \"warn\" ? yellow(\"!\") :\n level === \"error\" ? red(\"×\") :\n level === \"event\" ? cyan(\"→\") :\n cyan(\"•\");\n process.stdout.write(`${dim(nowTime())} ${icon} ${message}\\n`);\n}\n\nfunction banner() {\n process.stdout.write(\"\\n\");\n process.stdout.write(bold(\"Remote Arc\") + \" \" + dim(`v${VERSION}`) + \"\\n\");\n process.stdout.write(dim(\"Secure remote MCP bridge\") + \"\\n\\n\");\n}\n\nfunction argFlag(name: string) {\n return process.argv.includes(name);\n}\n\nfunction selectedMode(): Mode {\n if (argFlag(\"--safe\")) return \"safe\";\n return \"managed\";\n}\n\nfunction isLocalSafeMode(mode: Mode) {\n return mode === \"safe\";\n}\n\nfunction modeLabel(mode: Mode) {\n return isLocalSafeMode(mode) ? \"safe local cap\" : \"dashboard-managed\";\n}\n\nasync function readConfig(): Promise<SavedConfig | null> {\n try {\n return JSON.parse(await fs.readFile(CONFIG_PATH, \"utf8\")) as SavedConfig;\n } catch {\n try {\n const legacy = JSON.parse(\n await fs.readFile(LEGACY_CONFIG_PATH, \"utf8\"),\n ) as SavedConfig;\n await writeConfig(legacy);\n logLine(\"success\", \"Migrated existing Remote Link pairing to Remote Arc.\");\n return legacy;\n } catch {\n return null;\n }\n }\n}\n\nasync function writeConfig(config: SavedConfig) {\n await fs.mkdir(CONFIG_DIR, { recursive: true });\n await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n mode: 0o600,\n });\n}\n\nasync function resetConfig() {\n await Promise.all([\n fs.rm(CONFIG_PATH, { force: true }),\n fs.rm(LEGACY_CONFIG_PATH, { force: true }),\n ]);\n logLine(\"success\", \"Removed saved device credentials.\");\n}\n\nfunction openBrowser(url: string) {\n const command =\n process.platform === \"win32\"\n ? \"cmd\"\n : process.platform === \"darwin\"\n ? \"open\"\n : \"xdg-open\";\n const args =\n process.platform === \"win32\"\n ? [\"/c\", \"start\", \"\", url]\n : [url];\n\n const child = spawn(command, args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n}\n\nasync function pair(origin: string, mode: Mode): Promise<SavedConfig> {\n const deviceName = os.hostname();\n const response = await fetch(origin + \"/api/device/start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n device_name: deviceName,\n platform: process.platform,\n arch: process.arch,\n hostname: os.hostname(),\n }),\n });\n\n if (!response.ok) {\n throw new Error(\"Could not start device pairing: \" + response.status);\n }\n\n const pairing = (await response.json()) as PairingStart;\n\n banner();\n logLine(\"info\", `Device: ${bold(deviceName)} · ${process.platform}/${process.arch} · ${modeLabel(mode)}`);\n logLine(\"event\", \"Pairing required — opening secure browser approval.\");\n process.stdout.write(\"\\n Pairing code \" + bold(cyan(pairing.user_code)) + \"\\n\");\n process.stdout.write(\" \" + dim(pairing.verification_uri_complete) + \"\\n\\n\");\n openBrowser(pairing.verification_uri_complete);\n logLine(\"info\", \"Waiting for authorization…\");\n\n const startedAt = Date.now();\n while (Date.now() - startedAt < pairing.expires_in * 1000) {\n await sleep(Math.max(pairing.interval, 2) * 1000);\n\n const tokenResponse = await fetch(origin + \"/api/device/token\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n device_code: pairing.device_code,\n device_secret: pairing.device_secret,\n }),\n });\n\n if (tokenResponse.status === 428) {\n if (process.stdout.isTTY) process.stdout.write(dim(\"·\"));\n continue;\n }\n\n if (!tokenResponse.ok) {\n const body = await tokenResponse.text();\n throw new Error(\"Pairing failed: \" + body);\n }\n\n const result = (await tokenResponse.json()) as PairingToken;\n process.stdout.write(\"\\n\");\n logLine(\"success\", \"Device authorized.\");\n\n const config: SavedConfig = {\n deviceId: result.device_id,\n deviceToken: result.device_token,\n deviceName,\n origin,\n mode,\n };\n await writeConfig(config);\n return config;\n }\n\n throw new Error(\"Pairing expired. Run Remote Arc again to retry.\");\n}\n\nclass ExecutionCore {\n private readonly core: RemoteArcExecutionCore;\n\n constructor(mode: Mode) {\n this.core = new RemoteArcExecutionCore(\n isLocalSafeMode(mode) ? \"safe\" : \"managed\",\n );\n }\n\n async tools() {\n return this.core.listTools();\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n policy?: ExecutionPolicy,\n ) {\n return this.core.callTool(name, args, policy);\n }\n\n async close() {\n await this.core.close();\n }\n}\n\nasync function connectAgent(config: SavedConfig) {\n const core = new ExecutionCore(config.mode);\n banner();\n logLine(\"info\", `Device: ${bold(config.deviceName)} · ${process.platform}/${process.arch}`);\n logLine(\n \"info\",\n `Permission profile: ${isLocalSafeMode(config.mode) ? green(\"safe local cap\") : cyan(\"dashboard-managed\")}`,\n );\n\n const tools = await core.tools();\n logLine(\"success\", `Local tools ready: ${tools.length} exposed`);\n process.stdout.write(\" \" + dim(tools.map((tool) => tool.name).join(\" · \")) + \"\\n\");\n const wsUrl = new URL(\"/agent\", config.origin.replace(/^http/, \"ws\"));\n\n let stopped = false;\n let backoff = 1000;\n\n const shutdown = async () => {\n stopped = true;\n await core.close().catch(() => undefined);\n process.exit(0);\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n while (!stopped) {\n logLine(\"event\", `Connecting relay ${dim(wsUrl.host)}…`);\n const ws = new WebSocket(wsUrl, {\n headers: {\n Authorization: \"Bearer \" + config.deviceToken,\n },\n });\n\n try {\n await new Promise<void>((resolve, reject) => {\n ws.once(\"open\", resolve);\n ws.once(\"error\", reject);\n });\n\n backoff = 1000;\n ws.send(\n JSON.stringify({\n type: \"hello\",\n device: {\n id: config.deviceId,\n name: config.deviceName,\n platform: process.platform,\n arch: process.arch,\n hostname: os.hostname(),\n agentVersion: VERSION,\n },\n tools: tools.map((tool) => tool.name),\n capabilities: [\"native_core_v1\", \"device_policy_v1\", \"undo_history_v1\"],\n }),\n );\n\n logLine(\"success\", `Relay connected · ${bold(config.deviceName)} · ${config.mode} mode`);\n logLine(\"success\", \"Device presence published.\");\n process.stdout.write(\" \" + dim(config.origin) + \"\\n\");\n process.stdout.write(\" \" + dim(\"Ctrl+C to disconnect\") + \"\\n\\n\");\n\n const sendHeartbeat = async () => {\n try {\n await fetch(new URL(\"/api/device/heartbeat\", config.origin), {\n method: \"POST\",\n headers: { Authorization: \"Bearer \" + config.deviceToken },\n });\n } catch {\n // WebSocket reconnect logic remains the source of truth for connectivity.\n }\n };\n void sendHeartbeat();\n const heartbeatTimer = setInterval(\n () => void sendHeartbeat(),\n 15 * 60_000,\n );\n\n await new Promise<void>((resolve) => {\n ws.on(\"message\", async (raw) => {\n let message: {\n type?: string;\n id?: string;\n tool?: string;\n arguments?: Record<string, unknown>;\n policy?: ExecutionPolicy;\n };\n\n try {\n message = JSON.parse(raw.toString());\n } catch {\n return;\n }\n\n if (\n message.type !== \"call\" ||\n !message.id ||\n !message.tool\n ) {\n return;\n }\n\n const callStarted = Date.now();\n logLine(\"event\", `tool.call ${bold(message.tool)} · ${dim(message.id.slice(0, 8))}`);\n try {\n const result = await core.call(\n message.tool,\n message.arguments || {},\n message.policy,\n );\n logLine(\"success\", `tool.done ${message.tool} · ${Date.now() - callStarted}ms`);\n ws.send(\n JSON.stringify({\n type: \"result\",\n id: message.id,\n result,\n }),\n );\n } catch (error) {\n logLine(\"error\", `tool.fail ${message.tool} · ${error instanceof Error ? error.message : String(error)}`);\n ws.send(\n JSON.stringify({\n type: \"result\",\n id: message.id,\n error: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n });\n\n ws.once(\"close\", resolve);\n ws.once(\"error\", resolve);\n });\n clearInterval(heartbeatTimer);\n } catch (error) {\n logLine(\n \"error\",\n \"Relay connection failed: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n } finally {\n ws.removeAllListeners();\n ws.close();\n }\n\n if (!stopped) {\n logLine(\n \"warn\",\n \"Relay disconnected · retrying in \" + Math.round(backoff / 1000) + \"s\",\n );\n await sleep(backoff);\n backoff = Math.min(backoff * 2, 30_000);\n }\n }\n}\n\nasync function main() {\n if (argFlag(\"--help\") || argFlag(\"-h\")) {\n process.stdout.write(\n [\n \"Remote Arc\",\n \"\",\n \"Usage:\",\n \" npx remotelink\",\n \"\",\n \"After the npm release:\",\n \" npx remotelink\",\n \"\",\n \"Options:\",\n \" --safe Hard local read-only cap; dashboard cannot enable write tools\",\n \" --developer Legacy alias for dashboard-managed capabilities\",\n \" --reset Remove this computer's saved pairing\",\n \" --version Print CLI version\",\n \" --help Show this help\",\n \"\",\n ].join(\"\\n\"),\n );\n return;\n }\n\n if (argFlag(\"--version\") || argFlag(\"-v\")) {\n process.stdout.write(VERSION + \"\\n\");\n return;\n }\n\n if (argFlag(\"--reset\")) {\n await resetConfig();\n return;\n }\n\n const origin =\n process.env.REMOTEARC_ORIGIN || process.env.REMOTE_LINK_ORIGIN ||\n process.argv.find((value) => value.startsWith(\"--origin=\"))?.slice(9) ||\n DEFAULT_ORIGIN;\n\n let config = await readConfig();\n if (config && [\"https://remote.samyao.me\", \"https://remotearc.app\"].includes(config.origin)) {\n config.origin = DEFAULT_ORIGIN;\n await writeConfig(config);\n logLine(\"info\", \"Migrated relay origin to \" + DEFAULT_ORIGIN);\n }\n if (!config) {\n config = await pair(origin, selectedMode());\n } else if (argFlag(\"--safe\") || argFlag(\"--developer\")) {\n config.mode = argFlag(\"--safe\") ? \"safe\" : \"managed\";\n await writeConfig(config);\n }\n\n if (config) {\n logLine(\"info\", `Using paired device identity ${dim(config.deviceId.slice(0, 8))}…`);\n }\n await connectAgent(config);\n}\n\nmain().catch((error) => {\n logLine(\n \"error\",\n \"Fatal: \" + (error instanceof Error ? error.message : String(error)),\n );\n process.exit(1);\n});\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nconst MAX_DIRECTORY_ENTRIES = 2000;\nconst DEFAULT_READ_LINES = 240;\nconst MAX_TEXT_FILE_BYTES = 20 * 1024 * 1024;\n\nconst printableSize = (bytes: number) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n};\n\nexport async function listDirectory(targetPath: string, depth = 2) {\n const maxDepth = Math.max(1, Math.min(10, Math.trunc(depth || 2)));\n const lines: string[] = [];\n let entriesSeen = 0;\n\n async function walk(directory: string, level: number, prefix: string) {\n if (entriesSeen >= MAX_DIRECTORY_ENTRIES) return;\n const entries = await fs.readdir(directory, { withFileTypes: true });\n entries.sort((a, b) => {\n if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1;\n return a.name.localeCompare(b.name);\n });\n\n for (const entry of entries) {\n if (entriesSeen >= MAX_DIRECTORY_ENTRIES) break;\n entriesSeen += 1;\n const absolute = path.join(directory, entry.name);\n const label = entry.isDirectory()\n ? \"[DIR]\"\n : entry.isSymbolicLink()\n ? \"[LINK]\"\n : \"[FILE]\";\n lines.push(`${prefix}${label} ${entry.name}`);\n\n if (entry.isDirectory() && level < maxDepth) {\n await walk(absolute, level + 1, prefix + \" \");\n }\n }\n }\n\n const stat = await fs.stat(targetPath);\n if (!stat.isDirectory()) throw new Error(\"Path is not a directory: \" + targetPath);\n\n await walk(targetPath, 1, \"\");\n if (entriesSeen >= MAX_DIRECTORY_ENTRIES) {\n lines.push(`… truncated after ${MAX_DIRECTORY_ENTRIES} entries`);\n }\n\n return `Directory: ${targetPath}\\nDepth: ${maxDepth}\\n\\n${lines.join(\"\\n\") || \"(empty)\"}`;\n}\n\nexport async function readTextFile(\n targetPath: string,\n offset?: number,\n length?: number,\n) {\n const stat = await fs.stat(targetPath);\n if (!stat.isFile()) throw new Error(\"Path is not a file: \" + targetPath);\n if (stat.size > MAX_TEXT_FILE_BYTES) {\n throw new Error(\n `File is too large for read_file (${printableSize(stat.size)} > 20 MB). Use a terminal command or a more targeted tool instead.`,\n );\n }\n\n const buffer = await fs.readFile(targetPath);\n const sample = buffer.subarray(0, Math.min(buffer.length, 8192));\n if (sample.includes(0)) {\n throw new Error(\"Binary file detected. read_file currently supports text files only.\");\n }\n\n const text = buffer.toString(\"utf8\");\n const lines = text.split(/\\r?\\n/);\n const requestedOffset = Number.isFinite(offset) ? Math.trunc(offset as number) : 0;\n const start =\n requestedOffset < 0\n ? Math.max(0, lines.length + requestedOffset)\n : Math.min(lines.length, Math.max(0, requestedOffset));\n const requestedLength =\n Number.isFinite(length) && (length as number) > 0\n ? Math.trunc(length as number)\n : DEFAULT_READ_LINES;\n const end = Math.min(lines.length, start + requestedLength);\n const chunk = lines.slice(start, end).join(\"\\n\");\n\n const location =\n start === 0\n ? \"start\"\n : end === lines.length\n ? `line ${start + 1} to end`\n : `lines ${start + 1}-${end}`;\n\n return `[Reading ${end - start} lines from ${location} (total: ${lines.length} lines, ${printableSize(stat.size)})]\\n\\n${chunk}`;\n}\n\nexport async function getFileInfo(targetPath: string) {\n const stat = await fs.lstat(targetPath);\n return {\n path: targetPath,\n type: stat.isFile()\n ? \"file\"\n : stat.isDirectory()\n ? \"directory\"\n : stat.isSymbolicLink()\n ? \"symlink\"\n : \"other\",\n size: stat.size,\n size_human: printableSize(stat.size),\n mode: stat.mode,\n created_at: stat.birthtime.toISOString(),\n modified_at: stat.mtime.toISOString(),\n accessed_at: stat.atime.toISOString(),\n };\n}\n\nasync function atomicWriteText(targetPath: string, content: string) {\n const directory = path.dirname(targetPath);\n await fs.mkdir(directory, { recursive: true });\n const temporary = path.join(\n directory,\n \".\" + path.basename(targetPath) + \".remotearc-\" + crypto.randomUUID() + \".tmp\",\n );\n\n try {\n await fs.writeFile(temporary, content, \"utf8\");\n await fs.rename(temporary, targetPath);\n } finally {\n await fs.rm(temporary, { force: true }).catch(() => undefined);\n }\n}\n\nexport async function writeTextFile(\n targetPath: string,\n content: string,\n mode: \"rewrite\" | \"append\" = \"rewrite\",\n) {\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n if (mode === \"append\") {\n await fs.appendFile(targetPath, content, \"utf8\");\n } else {\n await atomicWriteText(targetPath, content);\n }\n const stat = await fs.stat(targetPath);\n return {\n path: targetPath,\n mode,\n bytes: Buffer.byteLength(content),\n file_size: stat.size,\n atomic: mode === \"rewrite\",\n };\n}\n\nexport async function editTextBlock(\n filePath: string,\n oldString: string,\n newString: string,\n expectedReplacements = 1,\n) {\n if (!oldString) throw new Error(\"old_string cannot be empty.\");\n const current = await fs.readFile(filePath, \"utf8\");\n const parts = current.split(oldString);\n const replacements = parts.length - 1;\n\n if (replacements !== expectedReplacements) {\n throw new Error(\n `Expected ${expectedReplacements} replacement(s) in ${filePath}, found ${replacements}. No changes were written.`,\n );\n }\n\n const next = parts.join(newString);\n await atomicWriteText(filePath, next);\n return {\n path: filePath,\n replacements,\n bytes_before: Buffer.byteLength(current),\n bytes_after: Buffer.byteLength(next),\n atomic: true,\n };\n}\n","import { execFile, spawn } from \"node:child_process\";\nimport process from \"node:process\";\n\nconst MAX_CAPTURE_BYTES = 2 * 1024 * 1024;\n\nfunction appendCapped(current: string, chunk: Buffer | string) {\n if (Buffer.byteLength(current) >= MAX_CAPTURE_BYTES) return current;\n const next = current + chunk.toString();\n if (Buffer.byteLength(next) <= MAX_CAPTURE_BYTES) return next;\n return next.slice(0, MAX_CAPTURE_BYTES) + \"\\n… output truncated …\";\n}\n\nexport async function listProcesses() {\n const output = await new Promise<string>((resolve, reject) => {\n const command = process.platform === \"win32\" ? \"tasklist.exe\" : \"ps\";\n const args =\n process.platform === \"win32\"\n ? [\"/FO\", \"CSV\", \"/NH\"]\n : [\"-axo\", \"pid,ppid,user,%cpu,%mem,etime,command\"];\n execFile(command, args, { maxBuffer: MAX_CAPTURE_BYTES }, (error, stdout, stderr) => {\n if (error) {\n reject(new Error(`Could not list processes: ${stderr || error.message}`));\n return;\n }\n resolve(stdout.trim());\n });\n });\n\n return `Processes on ${process.platform}:\\n\\n${output}`;\n}\n\nasync function terminateTree(child: ReturnType<typeof spawn>) {\n if (!child.pid) return;\n if (process.platform === \"win32\") {\n await new Promise<void>((resolve) => {\n const killer = spawn(\n \"taskkill.exe\",\n [\"/PID\", String(child.pid), \"/T\", \"/F\"],\n { windowsHide: true, stdio: \"ignore\" },\n );\n killer.once(\"close\", () => resolve());\n killer.once(\"error\", () => resolve());\n });\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill(\"SIGTERM\");\n }\n await new Promise((resolve) => setTimeout(resolve, 300));\n try {\n process.kill(-child.pid, \"SIGKILL\");\n } catch {\n if (!child.killed) child.kill(\"SIGKILL\");\n }\n}\n\nexport async function runShellCommand(\n command: string,\n timeoutMs = 5000,\n cwd?: string,\n) {\n const timeout = Math.max(100, Math.min(120_000, Math.trunc(timeoutMs || 5000)));\n const startedAt = Date.now();\n\n return await new Promise<{\n command: string;\n cwd: string | null;\n exit_code: number | null;\n signal: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n duration_ms: number;\n timed_out: boolean;\n }>((resolve, reject) => {\n const child = spawn(command, {\n shell: true,\n cwd,\n windowsHide: true,\n detached: process.platform !== \"win32\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n\n child.stdout?.on(\"data\", (chunk) => {\n stdout = appendCapped(stdout, chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr = appendCapped(stderr, chunk);\n });\n\n const timer = setTimeout(async () => {\n timedOut = true;\n await terminateTree(child);\n }, timeout);\n\n child.once(\"error\", (error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(error);\n });\n\n child.once(\"close\", (code, signal) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve({\n command,\n cwd: cwd || null,\n exit_code: code,\n signal,\n stdout,\n stderr,\n duration_ms: Date.now() - startedAt,\n timed_out: timedOut,\n });\n });\n });\n}\n","import crypto from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000;\nconst MAX_SNAPSHOT_BYTES = 20 * 1024 * 1024;\nconst MAX_UNDO_BYTES = 200 * 1024 * 1024;\n\ntype UndoManifest = {\n id: string;\n createdAt: string;\n tool: \"write_file\" | \"edit_block\";\n targetPath: string;\n existed: boolean;\n mode?: number;\n bytes: number;\n postChangeHash?: string;\n};\n\nexport type UndoSnapshot = {\n id: string;\n directory: string;\n manifest: UndoManifest;\n};\n\nconst undoRoot = () =>\n process.env.REMOTEARC_UNDO_ROOT ||\n path.join(os.homedir(), \".remotearc\", \"undo\");\n\nasync function ensureUndoRoot() {\n await fs.mkdir(undoRoot(), { recursive: true, mode: 0o700 });\n}\n\nasync function readManifest(directory: string): Promise<UndoManifest | null> {\n try {\n return JSON.parse(\n await fs.readFile(path.join(directory, \"manifest.json\"), \"utf8\"),\n ) as UndoManifest;\n } catch {\n return null;\n }\n}\n\nasync function snapshotDirectories() {\n await ensureUndoRoot();\n const entries = await fs.readdir(undoRoot(), { withFileTypes: true });\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => path.join(undoRoot(), entry.name));\n}\n\nasync function cleanupUndoStore() {\n const now = Date.now();\n const snapshots: Array<{ directory: string; manifest: UndoManifest }> = [];\n\n for (const directory of await snapshotDirectories()) {\n const manifest = await readManifest(directory);\n if (!manifest) {\n await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);\n continue;\n }\n\n const created = Date.parse(manifest.createdAt);\n if (!Number.isFinite(created) || now - created > RETENTION_MS) {\n await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);\n continue;\n }\n\n snapshots.push({ directory, manifest });\n }\n\n snapshots.sort(\n (a, b) => Date.parse(a.manifest.createdAt) - Date.parse(b.manifest.createdAt),\n );\n\n let total = snapshots.reduce((sum, item) => sum + item.manifest.bytes, 0);\n for (const item of snapshots) {\n if (total <= MAX_UNDO_BYTES) break;\n await fs.rm(item.directory, { recursive: true, force: true }).catch(() => undefined);\n total -= item.manifest.bytes;\n }\n}\n\nfunction mutationPath(\n tool: \"write_file\" | \"edit_block\",\n args: Record<string, unknown>,\n) {\n const candidate = tool === \"write_file\" ? args.path : args.file_path;\n return typeof candidate === \"string\" && candidate.trim() ? candidate : null;\n}\n\nexport async function createUndoSnapshot(\n tool: \"write_file\" | \"edit_block\",\n args: Record<string, unknown>,\n): Promise<UndoSnapshot | null> {\n const targetPath = mutationPath(tool, args);\n if (!targetPath) return null;\n\n await cleanupUndoStore();\n\n let existed = false;\n let mode: number | undefined;\n let bytes = 0;\n let original: Buffer | null = null;\n\n try {\n const stat = await fs.stat(targetPath);\n if (!stat.isFile()) return null;\n existed = true;\n mode = stat.mode;\n bytes = stat.size;\n if (bytes > MAX_SNAPSHOT_BYTES) return null;\n original = await fs.readFile(targetPath);\n } catch (error) {\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : \"\";\n if (code !== \"ENOENT\") throw error;\n }\n\n const id = `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;\n const directory = path.join(undoRoot(), id);\n await fs.mkdir(directory, { recursive: true, mode: 0o700 });\n\n if (original) {\n await fs.writeFile(path.join(directory, \"content.bin\"), original, { mode: 0o600 });\n }\n\n const manifest: UndoManifest = {\n id,\n createdAt: new Date().toISOString(),\n tool,\n targetPath,\n existed,\n ...(mode !== undefined ? { mode } : {}),\n bytes,\n };\n\n await fs.writeFile(\n path.join(directory, \"manifest.json\"),\n JSON.stringify(manifest, null, 2) + \"\\n\",\n { mode: 0o600 },\n );\n\n await cleanupUndoStore();\n return { id, directory, manifest };\n}\n\nasync function hashFile(filePath: string) {\n const hash = crypto.createHash(\"sha256\");\n for await (const chunk of createReadStream(filePath)) hash.update(chunk);\n return hash.digest(\"hex\");\n}\n\nexport async function finalizeUndoSnapshot(snapshot: UndoSnapshot | null) {\n if (!snapshot) return false;\n try {\n snapshot.manifest.postChangeHash = await hashFile(snapshot.manifest.targetPath);\n await fs.writeFile(\n path.join(snapshot.directory, \"manifest.json\"),\n JSON.stringify(snapshot.manifest, null, 2) + \"\\n\",\n { mode: 0o600 },\n );\n return true;\n } catch {\n await discardUndoSnapshot(snapshot);\n return false;\n }\n}\n\nexport async function discardUndoSnapshot(snapshot: UndoSnapshot | null) {\n if (!snapshot) return;\n await fs.rm(snapshot.directory, { recursive: true, force: true }).catch(() => undefined);\n}\n\nasync function undoCandidates() {\n await cleanupUndoStore();\n const candidates: Array<{ directory: string; manifest: UndoManifest }> = [];\n for (const directory of await snapshotDirectories()) {\n const manifest = await readManifest(directory);\n if (manifest) candidates.push({ directory, manifest });\n }\n candidates.sort(\n (a, b) => Date.parse(b.manifest.createdAt) - Date.parse(a.manifest.createdAt),\n );\n return candidates;\n}\n\nexport async function listUndoActions(limit = 20) {\n const candidates = await undoCandidates();\n return candidates.slice(0, Math.max(1, Math.min(100, Math.trunc(limit)))).map(({ manifest }) => ({\n id: manifest.id,\n created_at: manifest.createdAt,\n tool: manifest.tool,\n path: manifest.targetPath,\n bytes: manifest.bytes,\n existed_before: manifest.existed,\n conflict_safe: Boolean(manifest.postChangeHash),\n }));\n}\n\nasync function restoreUndoCandidate(candidate: { directory: string; manifest: UndoManifest }) {\n const { directory, manifest } = candidate;\n\n if (!manifest.postChangeHash) {\n throw new Error(\n \"This snapshot predates conflict-safe Local Undo and cannot be restored automatically.\",\n );\n }\n\n let currentHash: string;\n try {\n currentHash = await hashFile(manifest.targetPath);\n } catch {\n throw new Error(\n \"The target file changed or disappeared after the Remote Arc edit. Automatic undo was refused to avoid overwriting newer work.\",\n );\n }\n\n if (currentHash !== manifest.postChangeHash) {\n throw new Error(\n \"The target file changed again after the Remote Arc edit. Automatic undo was refused to avoid overwriting newer work.\",\n );\n }\n\n if (manifest.existed) {\n const original = await fs.readFile(path.join(directory, \"content.bin\"));\n await fs.mkdir(path.dirname(manifest.targetPath), { recursive: true });\n await fs.writeFile(manifest.targetPath, original);\n if (manifest.mode !== undefined) {\n await fs.chmod(manifest.targetPath, manifest.mode).catch(() => undefined);\n }\n } else {\n await fs.rm(manifest.targetPath, { force: true });\n }\n\n await fs.rm(directory, { recursive: true, force: true });\n\n return {\n restored: true,\n action_id: manifest.id,\n tool: manifest.tool,\n path: manifest.targetPath,\n snapshot_location: \"local-device-only\",\n };\n}\n\nexport async function undoChange(actionId: string) {\n const candidate = (await undoCandidates()).find(({ manifest }) => manifest.id === actionId);\n if (!candidate) {\n throw new Error(\"Undo action not found or expired on this device.\");\n }\n return restoreUndoCandidate(candidate);\n}\n\nexport async function undoLastChange() {\n const latest = (await undoCandidates())[0];\n if (!latest) {\n throw new Error(\"No reversible Remote Arc file change is available on this device.\");\n }\n return restoreUndoCandidate(latest);\n}\n\ntype GuardRule = { pattern: RegExp; reason: string };\n\nconst DESTRUCTIVE_COMMAND_RULES: GuardRule[] = [\n {\n pattern: /(?:^|[;&|]\\s*)(?:sudo\\s+)?rm\\s+[^\\n]*(?:-rf|-fr|-[a-z]*r[a-z]*f)[^\\n]*(?:\\s\\/\\s*$|\\s\\/\\*|\\s~(?:\\s|$)|\\s\\$HOME(?:\\s|$))/i,\n reason: \"recursive deletion of a root or home path\",\n },\n {\n pattern: /\\b(?:mkfs(?:\\.\\w+)?|wipefs|fdisk|parted)\\b/i,\n reason: \"disk or filesystem destructive operation\",\n },\n {\n pattern: /\\bdd\\b[^\\n]*\\bof=\\/dev\\/(?:sd|nvme|vd|xvd|mmcblk)/i,\n reason: \"raw disk overwrite\",\n },\n {\n pattern: /\\bdiskutil\\s+erase(?:disk|volume)\\b/i,\n reason: \"disk erase\",\n },\n {\n pattern: /\\b(?:format(?:\\.com)?\\s+[a-z]:|diskpart\\b|clear-disk\\b|initialize-disk\\b)/i,\n reason: \"Windows disk destructive operation\",\n },\n {\n pattern: /\\b(?:shutdown|reboot|halt|poweroff)\\b/i,\n reason: \"system shutdown or reboot\",\n },\n {\n pattern: /\\bremove-item\\b[^\\n]*(?:-recurse[^\\n]*-force|-force[^\\n]*-recurse)[^\\n]*(?:[a-z]:\\\\(?:\\*|\\s|$)|\\$env:systemdrive)/i,\n reason: \"recursive forced deletion of a drive root\",\n },\n {\n pattern: /\\b(?:del|erase|rd|rmdir)\\b[^\\n]*\\/s[^\\n]*\\/q[^\\n]*[a-z]:\\\\/i,\n reason: \"recursive Windows drive deletion\",\n },\n {\n pattern: /:\\(\\)\\s*\\{\\s*:\\|:&\\s*\\};\\s*:/,\n reason: \"fork bomb\",\n },\n];\n\nexport function assertCommandAllowed(command: string) {\n if (process.env.REMOTEARC_ALLOW_DESTRUCTIVE === \"1\") return;\n\n for (const rule of DESTRUCTIVE_COMMAND_RULES) {\n if (rule.pattern.test(command)) {\n throw new Error(\n \"Blocked by Remote Arc Safety Guard: \" +\n rule.reason +\n \". Run this action manually on the device if you intentionally need it.\",\n );\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type ExecutionPolicy = {\n workspaceRoots?: string[];\n protectSensitivePaths?: boolean;\n sensitivePaths?: string[];\n undoEnabled?: boolean;\n};\n\nconst SENSITIVE_BASENAMES = new Set([\n \".npmrc\",\n \".pypirc\",\n \".netrc\",\n \".git-credentials\",\n \"id_rsa\",\n \"id_ed25519\",\n \"credentials\",\n]);\n\nconst expandPath = (value: string) => {\n const trimmed = value.trim();\n if (trimmed === \"~\") return os.homedir();\n if (trimmed.startsWith(\"~/\") || trimmed.startsWith(\"~\\\\\")) {\n return path.join(os.homedir(), trimmed.slice(2));\n }\n return trimmed\n .replace(/%USERPROFILE%/gi, os.homedir())\n .replace(/\\$HOME\\b/g, os.homedir());\n};\n\nconst comparePath = (value: string) => {\n const resolved = path.resolve(expandPath(value));\n return process.platform === \"win32\" ? resolved.toLowerCase() : resolved;\n};\n\nasync function canonicalTarget(targetPath: string) {\n const expanded = path.resolve(expandPath(targetPath));\n try {\n return comparePath(await fs.realpath(expanded));\n } catch {\n const missing: string[] = [];\n let cursor = expanded;\n\n while (true) {\n try {\n const realParent = await fs.realpath(cursor);\n return comparePath(path.join(realParent, ...missing.reverse()));\n } catch {\n const parent = path.dirname(cursor);\n if (parent === cursor) return comparePath(expanded);\n missing.push(path.basename(cursor));\n cursor = parent;\n }\n }\n }\n}\n\nconst isInside = (target: string, root: string) => {\n const relative = path.relative(root, target);\n return (\n relative === \"\" ||\n (!relative.startsWith(\"..\") && !path.isAbsolute(relative))\n );\n};\n\nfunction defaultSensitiveRoots() {\n const home = os.homedir();\n const roots = [\n path.join(home, \".ssh\"),\n path.join(home, \".aws\"),\n path.join(home, \".gnupg\"),\n path.join(home, \".azure\"),\n path.join(home, \".kube\"),\n path.join(home, \".docker\"),\n path.join(home, \".config\", \"gcloud\"),\n ];\n\n if (process.platform === \"darwin\") {\n roots.push(\n path.join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\"),\n path.join(home, \"Library\", \"Application Support\", \"Microsoft Edge\"),\n path.join(home, \"Library\", \"Application Support\", \"Firefox\"),\n );\n }\n\n if (process.platform === \"win32\") {\n const appData = process.env.APPDATA;\n const localAppData = process.env.LOCALAPPDATA;\n if (appData) {\n roots.push(path.join(appData, \"Mozilla\", \"Firefox\"));\n }\n if (localAppData) {\n roots.push(\n path.join(localAppData, \"Google\", \"Chrome\", \"User Data\"),\n path.join(localAppData, \"Microsoft\", \"Edge\", \"User Data\"),\n );\n }\n }\n\n return roots;\n}\n\nfunction looksLikeSensitiveFile(target: string) {\n const basename = path.basename(target).toLowerCase();\n if (basename === \".env\" || basename.startsWith(\".env.\")) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n\n const normalized = target.replace(/\\\\/g, \"/\").toLowerCase();\n if (normalized.endsWith(\"/.docker/config.json\")) return true;\n if (normalized.endsWith(\"/.kube/config\")) return true;\n\n return false;\n}\n\nexport async function enforcePathPolicy(\n targetPath: string,\n policy: ExecutionPolicy = {},\n) {\n const target = await canonicalTarget(targetPath);\n\n const workspaceInputs = (policy.workspaceRoots || []).filter(\n (item) => typeof item === \"string\" && item.trim(),\n );\n const roots = await Promise.all(workspaceInputs.map(canonicalTarget));\n\n if (roots.length && !roots.some((root) => isInside(target, root))) {\n throw new Error(\n \"Blocked by Remote Arc Workspace Scope: path is outside the allowed workspace roots.\",\n );\n }\n\n if (policy.protectSensitivePaths !== false) {\n const sensitiveInputs = [\n ...defaultSensitiveRoots(),\n ...(policy.sensitivePaths || []),\n ].filter((item) => typeof item === \"string\" && item.trim());\n const sensitiveRoots = await Promise.all(\n sensitiveInputs.map(canonicalTarget),\n );\n\n if (\n looksLikeSensitiveFile(target) ||\n sensitiveRoots.some((root) => isInside(target, root))\n ) {\n throw new Error(\n \"Blocked by Remote Arc Sensitive Path Policy. Change this device policy in the dashboard if you intentionally need access.\",\n );\n }\n }\n\n return target;\n}\n\nexport function normalizePolicy(policy?: ExecutionPolicy): ExecutionPolicy {\n return {\n workspaceRoots: Array.from(\n new Set((policy?.workspaceRoots || []).filter((item) => typeof item === \"string\" && item.trim())),\n ).slice(0, 32),\n protectSensitivePaths: policy?.protectSensitivePaths !== false,\n sensitivePaths: Array.from(\n new Set((policy?.sensitivePaths || []).filter((item) => typeof item === \"string\" && item.trim())),\n ).slice(0, 32),\n undoEnabled: policy?.undoEnabled !== false,\n };\n}\n","import {\n editTextBlock,\n getFileInfo,\n listDirectory,\n readTextFile,\n writeTextFile,\n} from \"./filesystem.js\";\nimport { listProcesses, runShellCommand } from \"./process.js\";\nimport {\n assertCommandAllowed,\n createUndoSnapshot,\n discardUndoSnapshot,\n finalizeUndoSnapshot,\n listUndoActions,\n undoChange,\n} from \"./safety.js\";\nimport {\n enforcePathPolicy,\n normalizePolicy,\n type ExecutionPolicy,\n} from \"./policy.js\";\nimport type {\n ExecutionMode,\n ToolArguments,\n ToolDefinition,\n ToolName,\n ToolResult,\n} from \"./types.js\";\n\nconst SAFE_TOOLS = new Set<ToolName>([\n \"list_directory\",\n \"read_file\",\n \"get_file_info\",\n \"list_processes\",\n \"list_undo_actions\",\n]);\n\nconst DEVELOPER_TOOLS = new Set<ToolName>([\n ...SAFE_TOOLS,\n \"write_file\",\n \"edit_block\",\n \"undo_change\",\n \"undo_last_change\",\n]);\n\nconst FULL_TOOLS = new Set<ToolName>([\n ...DEVELOPER_TOOLS,\n \"start_process\",\n]);\n\nconst DEFINITIONS: ToolDefinition[] = [\n {\n name: \"list_directory\",\n description: \"List files and directories on this computer without following directory symlinks.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n depth: { type: \"integer\", minimum: 1, maximum: 10, default: 2 },\n },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n {\n name: \"read_file\",\n description: \"Read a text file by line range. Negative offsets read from the end.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n offset: { type: \"integer\" },\n length: { type: \"integer\", minimum: 1 },\n },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n {\n name: \"get_file_info\",\n description: \"Get local file or directory metadata.\",\n inputSchema: {\n type: \"object\",\n properties: { path: { type: \"string\" } },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n {\n name: \"list_processes\",\n description: \"List processes running on this computer.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"write_file\",\n description: \"Write or append UTF-8 text. Remote Arc creates a local-only Undo snapshot first.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n content: { type: \"string\" },\n mode: { type: \"string\", enum: [\"rewrite\", \"append\"], default: \"rewrite\" },\n },\n required: [\"path\", \"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"edit_block\",\n description: \"Apply an exact text replacement with conflict-safe Local Undo.\",\n inputSchema: {\n type: \"object\",\n properties: {\n file_path: { type: \"string\" },\n old_string: { type: \"string\" },\n new_string: { type: \"string\" },\n expected_replacements: { type: \"integer\", minimum: 1, default: 1 },\n },\n required: [\"file_path\", \"old_string\", \"new_string\"],\n additionalProperties: false,\n },\n },\n {\n name: \"list_undo_actions\",\n description: \"List reversible Remote Arc file changes currently stored on this device.\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: { type: \"integer\", minimum: 1, maximum: 100, default: 20 },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"undo_change\",\n description: \"Restore one specific local Remote Arc undo snapshot by action id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n action_id: { type: \"string\" },\n },\n required: [\"action_id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"undo_last_change\",\n description: \"Undo the newest reversible Remote Arc file edit stored only on this device.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"start_process\",\n description: \"Run a shell command with timeout and output capture. Catastrophic command patterns are blocked locally.\",\n inputSchema: {\n type: \"object\",\n properties: {\n command: { type: \"string\" },\n timeout_ms: { type: \"integer\", minimum: 100, maximum: 120000, default: 5000 },\n cwd: { type: \"string\" },\n },\n required: [\"command\"],\n additionalProperties: false,\n },\n },\n];\n\nconst textResult = (value: unknown): ToolResult => ({\n content: [\n {\n type: \"text\",\n text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2),\n },\n ],\n});\n\nfunction requiredString(args: ToolArguments, key: string) {\n const value = args[key];\n if (typeof value !== \"string\") throw new Error(`${key} must be a string.`);\n return value;\n}\n\nfunction optionalNumber(args: ToolArguments, key: string) {\n const value = args[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction optionalString(args: ToolArguments, key: string) {\n const value = args[key];\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nexport class RemoteArcExecutionCore {\n constructor(private readonly mode: ExecutionMode = \"managed\") {}\n\n private allowedTools() {\n if (this.mode === \"safe\") return SAFE_TOOLS;\n if (this.mode === \"developer\") return DEVELOPER_TOOLS;\n return FULL_TOOLS;\n }\n\n listTools() {\n const allowed = this.allowedTools();\n return DEFINITIONS.filter((tool) => allowed.has(tool.name));\n }\n\n async callTool(\n name: string,\n args: ToolArguments = {},\n policyInput: ExecutionPolicy = {},\n ): Promise<ToolResult> {\n const toolName = name as ToolName;\n if (!this.allowedTools().has(toolName)) {\n throw new Error(`Tool blocked by local permission mode: ${name}`);\n }\n\n const policy = normalizePolicy(policyInput);\n\n switch (toolName) {\n case \"list_directory\": {\n const target = await enforcePathPolicy(requiredString(args, \"path\"), policy);\n return textResult(\n await listDirectory(target, optionalNumber(args, \"depth\") ?? 2),\n );\n }\n case \"read_file\": {\n const target = await enforcePathPolicy(requiredString(args, \"path\"), policy);\n return textResult(\n await readTextFile(\n target,\n optionalNumber(args, \"offset\"),\n optionalNumber(args, \"length\"),\n ),\n );\n }\n case \"get_file_info\": {\n const target = await enforcePathPolicy(requiredString(args, \"path\"), policy);\n return textResult(await getFileInfo(target));\n }\n case \"list_processes\":\n return textResult(await listProcesses());\n case \"list_undo_actions\": {\n const actions = await listUndoActions(optionalNumber(args, \"limit\") ?? 20);\n const visible = [];\n for (const action of actions) {\n try {\n await enforcePathPolicy(action.path, policy);\n visible.push(action);\n } catch {\n // Do not reveal protected or out-of-scope paths through undo metadata.\n }\n }\n return textResult(visible);\n }\n case \"undo_change\": {\n if (policy.undoEnabled === false) {\n throw new Error(\"Local Undo is disabled for this device.\");\n }\n const actionId = requiredString(args, \"action_id\");\n const action = (await listUndoActions(100)).find((item) => item.id === actionId);\n if (!action) throw new Error(\"Undo action not found or expired on this device.\");\n await enforcePathPolicy(action.path, policy);\n return textResult(await undoChange(actionId));\n }\n case \"undo_last_change\": {\n if (policy.undoEnabled === false) {\n throw new Error(\"Local Undo is disabled for this device.\");\n }\n const actions = await listUndoActions(100);\n for (const action of actions) {\n try {\n await enforcePathPolicy(action.path, policy);\n return textResult(await undoChange(action.id));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.startsWith(\"Blocked by Remote Arc\")) throw error;\n }\n }\n throw new Error(\"No reversible in-scope Remote Arc file change is available.\");\n }\n case \"start_process\": {\n const command = requiredString(args, \"command\");\n assertCommandAllowed(command);\n const cwdInput = optionalString(args, \"cwd\");\n if ((policy.workspaceRoots || []).length && !cwdInput) {\n throw new Error(\n \"Workspace Scope is enabled. start_process requires an in-scope cwd. Terminal commands are not an OS sandbox and may still access paths outside that directory.\",\n );\n }\n const cwd = cwdInput ? await enforcePathPolicy(cwdInput, policy) : undefined;\n return textResult(\n await runShellCommand(\n command,\n optionalNumber(args, \"timeout_ms\") ?? 5000,\n cwd,\n ),\n );\n }\n case \"write_file\":\n case \"edit_block\": {\n const pathKey = toolName === \"write_file\" ? \"path\" : \"file_path\";\n const target = await enforcePathPolicy(requiredString(args, pathKey), policy);\n const scopedArgs = { ...args, [pathKey]: target };\n const snapshot =\n policy.undoEnabled === false\n ? null\n : await createUndoSnapshot(toolName, scopedArgs);\n try {\n const result =\n toolName === \"write_file\"\n ? await writeTextFile(\n target,\n requiredString(args, \"content\"),\n args.mode === \"append\" ? \"append\" : \"rewrite\",\n )\n : await editTextBlock(\n target,\n requiredString(args, \"old_string\"),\n requiredString(args, \"new_string\"),\n optionalNumber(args, \"expected_replacements\") ?? 1,\n );\n\n const undoAvailable = await finalizeUndoSnapshot(snapshot);\n return textResult({\n ...result,\n undo_available: undoAvailable,\n undo_storage: undoAvailable ? \"local-device-only\" : null,\n });\n } catch (error) {\n await discardUndoSnapshot(snapshot);\n throw error;\n }\n }\n default:\n throw new Error(\"Unknown Remote Arc tool: \" + name);\n }\n }\n\n async close() {\n // Native execution has no persistent child process to close.\n }\n}\n\nexport const toolDefinitions = DEFINITIONS;\n"],"mappings":";;;AACA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,OAAOC,SAAQ;AACf,SAAS,SAAAC,cAAa;AACtB,OAAOC,cAAa;AACpB,OAAO,eAAe;;;ACNtB,OAAO,YAAY;AACnB,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,IAAM,wBAAwB;AAC9B,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB,KAAK,OAAO;AAExC,IAAM,gBAAgB,CAAC,UAAkB;AACvC,MAAI,QAAQ,KAAM,QAAO,GAAG,KAAK;AACjC,MAAI,QAAQ,OAAO,KAAM,QAAO,IAAI,QAAQ,MAAM,QAAQ,CAAC,CAAC;AAC5D,SAAO,IAAI,SAAS,OAAO,OAAO,QAAQ,CAAC,CAAC;AAC9C;AAEA,eAAsB,cAAc,YAAoB,QAAQ,GAAG;AACjE,QAAM,WAAW,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK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AQ,KAAK,KAAK,CAAC,UAAU,MAAM,WAAW,WAAW,CAAC,GAAG,MAAM,CAAC,KACpE;AAEF,MAAI,SAAS,MAAM,WAAW;AAC9B,MAAI,UAAU,CAAC,4BAA4B,uBAAuB,EAAE,SAAS,OAAO,MAAM,GAAG;AAC3F,WAAO,SAAS;AAChB,UAAM,YAAY,MAAM;AACxB,YAAQ,QAAQ,8BAA8B,cAAc;AAAA,EAC9D;AACA,MAAI,CAAC,QAAQ;AACX,aAAS,MAAM,KAAK,QAAQ,aAAa,CAAC;AAAA,EAC5C,WAAW,QAAQ,QAAQ,KAAK,QAAQ,aAAa,GAAG;AACtD,WAAO,OAAO,QAAQ,QAAQ,IAAI,SAAS;AAC3C,UAAM,YAAY,MAAM;AAAA,EAC1B;AAEA,MAAI,QAAQ;AACV,YAAQ,QAAQ,gCAAgC,IAAI,OAAO,SAAS,MAAM,GAAG,CAAC,CAAC,CAAC,QAAG;AAAA,EACrF;AACA,QAAM,aAAa,MAAM;AAC3B;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB;AAAA,IACE;AAAA,IACA,aAAa,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,EACpE;AACA,EAAAA,SAAQ,KAAK,CAAC;AAChB,CAAC;","names":["os","path","fs","spawn","process","process","crypto","fs","path","fs","os","path","path","os","process","fs","spawn"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../execution-core/src/filesystem.ts","../../execution-core/src/process.ts","../../execution-core/src/safety.ts","../../execution-core/src/policy.ts","../../execution-core/src/core.ts"],"sourcesContent":["#!/usr/bin/env node\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { spawn } from \"node:child_process\";\nimport process from \"node:process\";\nimport WebSocket from \"ws\";\nimport {\n RemoteArcExecutionCore,\n type ExecutionPolicy,\n} from \"@remotearc/execution-core\";\n\nconst VERSION = \"0.3.11\";\nconst DEFAULT_ORIGIN = \"https://mcp.remotearc.app\";\nconst CONFIG_DIR = path.join(os.homedir(), \".remotearc\");\nconst CONFIG_PATH = path.join(CONFIG_DIR, \"config.json\");\nconst LEGACY_CONFIG_PATH = path.join(os.homedir(), \".remote-link\", \"config.json\");\n\ntype Mode = \"managed\" | \"safe\" | \"developer\";\n\ntype SavedConfig = {\n deviceId: string;\n deviceToken: string;\n deviceName: string;\n origin: string;\n mode: Mode;\n};\n\ntype PairingStart = {\n device_code: string;\n device_secret: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete: string;\n expires_in: number;\n interval: number;\n};\n\ntype PairingToken = {\n device_id: string;\n device_token: string;\n relay_url: string;\n};\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst supportsColor = process.stdout.isTTY && !process.env.NO_COLOR;\nconst paint = (code: string, value: string) =>\n supportsColor ? `\\x1b[${code}m${value}\\x1b[0m` : value;\nconst dim = (value: string) => paint(\"2\", value);\nconst cyan = (value: string) => paint(\"36\", value);\nconst green = (value: string) => paint(\"32\", value);\nconst yellow = (value: string) => paint(\"33\", value);\nconst red = (value: string) => paint(\"31\", value);\nconst bold = (value: string) => paint(\"1\", value);\n\nfunction nowTime() {\n return new Date().toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n}\n\nfunction logLine(\n level: \"info\" | \"success\" | \"warn\" | \"error\" | \"event\",\n message: string,\n) {\n const icon =\n level === \"success\" ? green(\"✓\") :\n level === \"warn\" ? yellow(\"!\") :\n level === \"error\" ? red(\"×\") :\n level === \"event\" ? cyan(\"→\") :\n cyan(\"•\");\n process.stdout.write(`${dim(nowTime())} ${icon} ${message}\\n`);\n}\n\nfunction banner() {\n process.stdout.write(\"\\n\");\n process.stdout.write(bold(\"Remote Arc\") + \" \" + dim(`v${VERSION}`) + \"\\n\");\n process.stdout.write(dim(\"Secure remote MCP bridge\") + \"\\n\\n\");\n}\n\nfunction argFlag(name: string) {\n return process.argv.includes(name);\n}\n\nfunction selectedMode(): Mode {\n if (argFlag(\"--safe\")) return \"safe\";\n return \"managed\";\n}\n\nfunction isLocalSafeMode(mode: Mode) {\n return mode === \"safe\";\n}\n\nfunction modeLabel(mode: Mode) {\n return isLocalSafeMode(mode) ? \"safe local cap\" : \"dashboard-managed\";\n}\n\nasync function readConfig(): Promise<SavedConfig | null> {\n try {\n return JSON.parse(await fs.readFile(CONFIG_PATH, \"utf8\")) as SavedConfig;\n } catch {\n try {\n const legacy = JSON.parse(\n await fs.readFile(LEGACY_CONFIG_PATH, \"utf8\"),\n ) as SavedConfig;\n await writeConfig(legacy);\n logLine(\"success\", \"Migrated existing Remote Link pairing to Remote Arc.\");\n return legacy;\n } catch {\n return null;\n }\n }\n}\n\nasync function writeConfig(config: SavedConfig) {\n await fs.mkdir(CONFIG_DIR, { recursive: true });\n await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n mode: 0o600,\n });\n}\n\nasync function resetConfig() {\n await Promise.all([\n fs.rm(CONFIG_PATH, { force: true }),\n fs.rm(LEGACY_CONFIG_PATH, { force: true }),\n ]);\n logLine(\"success\", \"Removed saved device credentials.\");\n}\n\nfunction openBrowser(url: string) {\n const command =\n process.platform === \"win32\"\n ? \"cmd\"\n : process.platform === \"darwin\"\n ? \"open\"\n : \"xdg-open\";\n const args =\n process.platform === \"win32\"\n ? [\"/c\", \"start\", \"\", url]\n : [url];\n\n const child = spawn(command, args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n}\n\nasync function pair(origin: string, mode: Mode): Promise<SavedConfig> {\n const deviceName = os.hostname();\n const response = await fetch(origin + \"/api/device/start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n device_name: deviceName,\n platform: process.platform,\n arch: process.arch,\n hostname: os.hostname(),\n }),\n });\n\n if (!response.ok) {\n throw new Error(\"Could not start device pairing: \" + response.status);\n }\n\n const pairing = (await response.json()) as PairingStart;\n\n banner();\n logLine(\"info\", `Device: ${bold(deviceName)} · ${process.platform}/${process.arch} · ${modeLabel(mode)}`);\n logLine(\"event\", \"Pairing required — opening secure browser approval.\");\n process.stdout.write(\"\\n Pairing code \" + bold(cyan(pairing.user_code)) + \"\\n\");\n process.stdout.write(\" \" + dim(pairing.verification_uri_complete) + \"\\n\\n\");\n openBrowser(pairing.verification_uri_complete);\n logLine(\"info\", \"Waiting for authorization…\");\n\n const startedAt = Date.now();\n while (Date.now() - startedAt < pairing.expires_in * 1000) {\n await sleep(Math.max(pairing.interval, 2) * 1000);\n\n const tokenResponse = await fetch(origin + \"/api/device/token\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n device_code: pairing.device_code,\n device_secret: pairing.device_secret,\n }),\n });\n\n if (tokenResponse.status === 428) {\n if (process.stdout.isTTY) process.stdout.write(dim(\"·\"));\n continue;\n }\n\n if (!tokenResponse.ok) {\n const body = await tokenResponse.text();\n throw new Error(\"Pairing failed: \" + body);\n }\n\n const result = (await tokenResponse.json()) as PairingToken;\n process.stdout.write(\"\\n\");\n logLine(\"success\", \"Device authorized.\");\n\n const config: SavedConfig = {\n deviceId: result.device_id,\n deviceToken: result.device_token,\n deviceName,\n origin,\n mode,\n };\n await writeConfig(config);\n return config;\n }\n\n throw new Error(\"Pairing expired. Run Remote Arc again to retry.\");\n}\n\nclass ExecutionCore {\n private readonly core: RemoteArcExecutionCore;\n\n constructor(mode: Mode) {\n this.core = new RemoteArcExecutionCore(\n isLocalSafeMode(mode) ? \"safe\" : \"managed\",\n );\n }\n\n async tools() {\n return this.core.listTools();\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n policy?: ExecutionPolicy,\n ) {\n return this.core.callTool(name, args, policy);\n }\n\n async close() {\n await this.core.close();\n }\n}\n\nasync function connectAgent(config: SavedConfig) {\n const core = new ExecutionCore(config.mode);\n banner();\n logLine(\"info\", `Device: ${bold(config.deviceName)} · ${process.platform}/${process.arch}`);\n logLine(\n \"info\",\n `Permission profile: ${isLocalSafeMode(config.mode) ? green(\"safe local cap\") : cyan(\"dashboard-managed\")}`,\n );\n\n const tools = await core.tools();\n logLine(\"success\", `Local tools ready: ${tools.length} exposed`);\n process.stdout.write(\" \" + dim(tools.map((tool) => tool.name).join(\" · \")) + \"\\n\");\n const wsUrl = new URL(\"/agent\", config.origin.replace(/^http/, \"ws\"));\n\n let stopped = false;\n let backoff = 1000;\n\n const shutdown = async () => {\n stopped = true;\n await core.close().catch(() => undefined);\n process.exit(0);\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n while (!stopped) {\n logLine(\"event\", `Connecting relay ${dim(wsUrl.host)}…`);\n const ws = new WebSocket(wsUrl, {\n headers: {\n Authorization: \"Bearer \" + config.deviceToken,\n },\n });\n\n try {\n await new Promise<void>((resolve, reject) => {\n ws.once(\"open\", resolve);\n ws.once(\"error\", reject);\n });\n\n backoff = 1000;\n ws.send(\n JSON.stringify({\n type: \"hello\",\n device: {\n id: config.deviceId,\n name: config.deviceName,\n platform: process.platform,\n arch: process.arch,\n hostname: os.hostname(),\n agentVersion: VERSION,\n },\n tools: tools.map((tool) => tool.name),\n capabilities: [\"native_core_v1\", \"device_policy_v1\", \"undo_history_v1\"],\n }),\n );\n\n logLine(\"success\", `Relay connected · ${bold(config.deviceName)} · ${config.mode} mode`);\n logLine(\"success\", \"Device presence published.\");\n process.stdout.write(\" \" + dim(config.origin) + \"\\n\");\n process.stdout.write(\" \" + dim(\"Ctrl+C to disconnect\") + \"\\n\\n\");\n\n const sendHeartbeat = async () => {\n try {\n await fetch(new URL(\"/api/device/heartbeat\", config.origin), {\n method: \"POST\",\n headers: { Authorization: \"Bearer \" + config.deviceToken },\n });\n } catch {\n // WebSocket reconnect logic remains the source of truth for connectivity.\n }\n };\n void sendHeartbeat();\n const heartbeatTimer = setInterval(\n () => void sendHeartbeat(),\n 15 * 60_000,\n );\n\n await new Promise<void>((resolve) => {\n ws.on(\"message\", async (raw) => {\n let message: {\n type?: string;\n id?: string;\n tool?: string;\n arguments?: Record<string, unknown>;\n policy?: ExecutionPolicy;\n };\n\n try {\n message = JSON.parse(raw.toString());\n } catch {\n return;\n }\n\n if (\n message.type !== \"call\" ||\n !message.id ||\n !message.tool\n ) {\n return;\n }\n\n const callStarted = Date.now();\n logLine(\"event\", `tool.call ${bold(message.tool)} · ${dim(message.id.slice(0, 8))}`);\n try {\n const result = await core.call(\n message.tool,\n message.arguments || {},\n message.policy,\n );\n logLine(\"success\", `tool.done ${message.tool} · ${Date.now() - callStarted}ms`);\n ws.send(\n JSON.stringify({\n type: \"result\",\n id: message.id,\n result,\n }),\n );\n } catch (error) {\n logLine(\"error\", `tool.fail ${message.tool} · ${error instanceof Error ? error.message : String(error)}`);\n ws.send(\n JSON.stringify({\n type: \"result\",\n id: message.id,\n error: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n });\n\n ws.once(\"close\", resolve);\n ws.once(\"error\", resolve);\n });\n clearInterval(heartbeatTimer);\n } catch (error) {\n logLine(\n \"error\",\n \"Relay connection failed: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n } finally {\n ws.removeAllListeners();\n ws.close();\n }\n\n if (!stopped) {\n logLine(\n \"warn\",\n \"Relay disconnected · retrying in \" + Math.round(backoff / 1000) + \"s\",\n );\n await sleep(backoff);\n backoff = Math.min(backoff * 2, 30_000);\n }\n }\n}\n\nasync function main() {\n if (argFlag(\"--help\") || argFlag(\"-h\")) {\n process.stdout.write(\n [\n \"Remote Arc\",\n \"\",\n \"Usage:\",\n \" npx remotelink\",\n \"\",\n \"After the npm release:\",\n \" npx remotelink\",\n \"\",\n \"Options:\",\n \" --safe Hard local read-only cap; dashboard cannot enable write tools\",\n \" --developer Legacy alias for dashboard-managed capabilities\",\n \" --reset Remove this computer's saved pairing\",\n \" --version Print CLI version\",\n \" --help Show this help\",\n \"\",\n ].join(\"\\n\"),\n );\n return;\n }\n\n if (argFlag(\"--version\") || argFlag(\"-v\")) {\n process.stdout.write(VERSION + \"\\n\");\n return;\n }\n\n if (argFlag(\"--reset\")) {\n await resetConfig();\n return;\n }\n\n const origin =\n process.env.REMOTEARC_ORIGIN || process.env.REMOTE_LINK_ORIGIN ||\n process.argv.find((value) => value.startsWith(\"--origin=\"))?.slice(9) ||\n DEFAULT_ORIGIN;\n\n let config = await readConfig();\n if (config && [\"https://remote.samyao.me\", \"https://remotearc.app\"].includes(config.origin)) {\n config.origin = DEFAULT_ORIGIN;\n await writeConfig(config);\n logLine(\"info\", \"Migrated relay origin to \" + DEFAULT_ORIGIN);\n }\n if (!config) {\n config = await pair(origin, selectedMode());\n } else if (argFlag(\"--safe\") || argFlag(\"--developer\")) {\n config.mode = argFlag(\"--safe\") ? \"safe\" : \"managed\";\n await writeConfig(config);\n }\n\n if (config) {\n logLine(\"info\", `Using paired device identity ${dim(config.deviceId.slice(0, 8))}…`);\n }\n await connectAgent(config);\n}\n\nmain().catch((error) => {\n logLine(\n \"error\",\n \"Fatal: \" + (error instanceof Error ? error.message : String(error)),\n );\n process.exit(1);\n});\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nconst MAX_DIRECTORY_ENTRIES = 2000;\nconst DEFAULT_READ_LINES = 240;\nconst MAX_TEXT_FILE_BYTES = 20 * 1024 * 1024;\n\nconst printableSize = (bytes: number) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n};\n\nexport async function listDirectory(\n targetPath: string,\n depth = 2,\n canReveal?: (candidatePath: string) => Promise<boolean>,\n) {\n const maxDepth = Math.max(1, Math.min(10, Math.trunc(depth || 2)));\n const lines: string[] = [];\n let entriesSeen = 0;\n let protectedEntries = 0;\n\n async function walk(directory: string, level: number, prefix: string) {\n if (entriesSeen >= MAX_DIRECTORY_ENTRIES) return;\n const entries = await fs.readdir(directory, { withFileTypes: true });\n entries.sort((a, b) => {\n if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1;\n return a.name.localeCompare(b.name);\n });\n\n for (const entry of entries) {\n if (entriesSeen >= MAX_DIRECTORY_ENTRIES) break;\n const absolute = path.join(directory, entry.name);\n\n if (canReveal && !(await canReveal(absolute))) {\n protectedEntries += 1;\n continue;\n }\n\n entriesSeen += 1;\n const label = entry.isDirectory()\n ? \"[DIR]\"\n : entry.isSymbolicLink()\n ? \"[LINK]\"\n : \"[FILE]\";\n lines.push(`${prefix}${label} ${entry.name}`);\n\n if (entry.isDirectory() && level < maxDepth) {\n await walk(absolute, level + 1, prefix + \" \");\n }\n }\n }\n\n const stat = await fs.stat(targetPath);\n if (!stat.isDirectory()) throw new Error(\"Path is not a directory: \" + targetPath);\n\n await walk(targetPath, 1, \"\");\n if (entriesSeen >= MAX_DIRECTORY_ENTRIES) {\n lines.push(`… truncated after ${MAX_DIRECTORY_ENTRIES} entries`);\n }\n\n const protectionNote = protectedEntries\n ? `\\n\\n[Remote Arc omitted ${protectedEntries} protected or out-of-scope entr${protectedEntries === 1 ? \"y\" : \"ies\"}.]`\n : \"\";\n\n return `Directory: ${targetPath}\\nDepth: ${maxDepth}\\n\\n${lines.join(\"\\n\") || \"(empty)\"}${protectionNote}`;\n}\n\nexport async function readTextFile(\n targetPath: string,\n offset?: number,\n length?: number,\n) {\n const stat = await fs.stat(targetPath);\n if (!stat.isFile()) throw new Error(\"Path is not a file: \" + targetPath);\n if (stat.size > MAX_TEXT_FILE_BYTES) {\n throw new Error(\n `File is too large for read_file (${printableSize(stat.size)} > 20 MB). Use a terminal command or a more targeted tool instead.`,\n );\n }\n\n const buffer = await fs.readFile(targetPath);\n const sample = buffer.subarray(0, Math.min(buffer.length, 8192));\n if (sample.includes(0)) {\n throw new Error(\"Binary file detected. read_file currently supports text files only.\");\n }\n\n const text = buffer.toString(\"utf8\");\n const lines = text.split(/\\r?\\n/);\n const requestedOffset = Number.isFinite(offset) ? Math.trunc(offset as number) : 0;\n const start =\n requestedOffset < 0\n ? Math.max(0, lines.length + requestedOffset)\n : Math.min(lines.length, Math.max(0, requestedOffset));\n const requestedLength =\n Number.isFinite(length) && (length as number) > 0\n ? Math.trunc(length as number)\n : DEFAULT_READ_LINES;\n const end = Math.min(lines.length, start + requestedLength);\n const chunk = lines.slice(start, end).join(\"\\n\");\n\n const location =\n start === 0\n ? \"start\"\n : end === lines.length\n ? `line ${start + 1} to end`\n : `lines ${start + 1}-${end}`;\n\n return `[Reading ${end - start} lines from ${location} (total: ${lines.length} lines, ${printableSize(stat.size)})]\\n\\n${chunk}`;\n}\n\nexport async function getFileInfo(targetPath: string) {\n const stat = await fs.lstat(targetPath);\n return {\n path: targetPath,\n type: stat.isFile()\n ? \"file\"\n : stat.isDirectory()\n ? \"directory\"\n : stat.isSymbolicLink()\n ? \"symlink\"\n : \"other\",\n size: stat.size,\n size_human: printableSize(stat.size),\n mode: stat.mode,\n created_at: stat.birthtime.toISOString(),\n modified_at: stat.mtime.toISOString(),\n accessed_at: stat.atime.toISOString(),\n };\n}\n\nasync function atomicWriteText(targetPath: string, content: string) {\n const directory = path.dirname(targetPath);\n await fs.mkdir(directory, { recursive: true });\n const temporary = path.join(\n directory,\n \".\" + path.basename(targetPath) + \".remotearc-\" + crypto.randomUUID() + \".tmp\",\n );\n\n try {\n await fs.writeFile(temporary, content, \"utf8\");\n await fs.rename(temporary, targetPath);\n } finally {\n await fs.rm(temporary, { force: true }).catch(() => undefined);\n }\n}\n\nexport async function writeTextFile(\n targetPath: string,\n content: string,\n mode: \"rewrite\" | \"append\" = \"rewrite\",\n) {\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n if (mode === \"append\") {\n await fs.appendFile(targetPath, content, \"utf8\");\n } else {\n await atomicWriteText(targetPath, content);\n }\n const stat = await fs.stat(targetPath);\n return {\n path: targetPath,\n mode,\n bytes: Buffer.byteLength(content),\n file_size: stat.size,\n atomic: mode === \"rewrite\",\n };\n}\n\nexport async function editTextBlock(\n filePath: string,\n oldString: string,\n newString: string,\n expectedReplacements = 1,\n) {\n if (!oldString) throw new Error(\"old_string cannot be empty.\");\n const current = await fs.readFile(filePath, \"utf8\");\n const parts = current.split(oldString);\n const replacements = parts.length - 1;\n\n if (replacements !== expectedReplacements) {\n throw new Error(\n `Expected ${expectedReplacements} replacement(s) in ${filePath}, found ${replacements}. No changes were written.`,\n );\n }\n\n const next = parts.join(newString);\n await atomicWriteText(filePath, next);\n return {\n path: filePath,\n replacements,\n bytes_before: Buffer.byteLength(current),\n bytes_after: Buffer.byteLength(next),\n atomic: true,\n };\n}\n","import { execFile, spawn, type ChildProcess } from \"node:child_process\";\nimport crypto from \"node:crypto\";\nimport process from \"node:process\";\n\nconst MAX_CAPTURE_BYTES = 2 * 1024 * 1024;\n\nfunction appendCapped(current: string, chunk: Buffer | string) {\n if (Buffer.byteLength(current) >= MAX_CAPTURE_BYTES) return current;\n const next = current + chunk.toString();\n if (Buffer.byteLength(next) <= MAX_CAPTURE_BYTES) return next;\n return next.slice(0, MAX_CAPTURE_BYTES) + \"\\n… output truncated …\";\n}\n\nexport async function listProcesses() {\n const output = await new Promise<string>((resolve, reject) => {\n const command = process.platform === \"win32\" ? \"tasklist.exe\" : \"ps\";\n const args =\n process.platform === \"win32\"\n ? [\"/FO\", \"CSV\", \"/NH\"]\n : [\"-axo\", \"pid,ppid,user,%cpu,%mem,etime,command\"];\n execFile(command, args, { maxBuffer: MAX_CAPTURE_BYTES }, (error, stdout, stderr) => {\n if (error) {\n reject(new Error(`Could not list processes: ${stderr || error.message}`));\n return;\n }\n resolve(stdout.trim());\n });\n });\n\n return `Processes on ${process.platform}:\\n\\n${output}`;\n}\n\nasync function terminateTree(child: ReturnType<typeof spawn>) {\n if (!child.pid) return;\n if (process.platform === \"win32\") {\n await new Promise<void>((resolve) => {\n const killer = spawn(\n \"taskkill.exe\",\n [\"/PID\", String(child.pid), \"/T\", \"/F\"],\n { windowsHide: true, stdio: \"ignore\" },\n );\n killer.once(\"close\", () => resolve());\n killer.once(\"error\", () => resolve());\n });\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill(\"SIGTERM\");\n }\n await new Promise((resolve) => setTimeout(resolve, 300));\n try {\n process.kill(-child.pid, \"SIGKILL\");\n } catch {\n if (!child.killed) child.kill(\"SIGKILL\");\n }\n}\n\nexport async function runShellCommand(\n command: string,\n timeoutMs = 5000,\n cwd?: string,\n) {\n const timeout = Math.max(100, Math.min(120_000, Math.trunc(timeoutMs || 5000)));\n const startedAt = Date.now();\n\n return await new Promise<{\n command: string;\n cwd: string | null;\n exit_code: number | null;\n signal: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n duration_ms: number;\n timed_out: boolean;\n }>((resolve, reject) => {\n const child = spawn(command, {\n shell: true,\n cwd,\n windowsHide: true,\n detached: process.platform !== \"win32\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n\n child.stdout?.on(\"data\", (chunk) => {\n stdout = appendCapped(stdout, chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr = appendCapped(stderr, chunk);\n });\n\n const timer = setTimeout(async () => {\n timedOut = true;\n await terminateTree(child);\n }, timeout);\n\n child.once(\"error\", (error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(error);\n });\n\n child.once(\"close\", (code, signal) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve({\n command,\n cwd: cwd || null,\n exit_code: code,\n signal,\n stdout,\n stderr,\n duration_ms: Date.now() - startedAt,\n timed_out: timedOut,\n });\n });\n });\n}\n\n\ntype ManagedProcess = {\n id: string;\n child: ChildProcess;\n command: string;\n cwd: string | null;\n startedAt: number;\n endedAt: number | null;\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n};\n\nconst managedProcesses = new Map<string, ManagedProcess>();\nconst MAX_MANAGED_PROCESSES = 32;\nconst FINISHED_PROCESS_RETENTION_MS = 30 * 60 * 1000;\n\nfunction cleanupManagedProcesses() {\n const now = Date.now();\n for (const [id, item] of managedProcesses) {\n if (\n item.endedAt !== null &&\n now - item.endedAt > FINISHED_PROCESS_RETENTION_MS\n ) {\n managedProcesses.delete(id);\n }\n }\n\n if (managedProcesses.size <= MAX_MANAGED_PROCESSES) return;\n const finished = [...managedProcesses.values()]\n .filter((item) => item.endedAt !== null)\n .sort((a, b) => (a.endedAt || 0) - (b.endedAt || 0));\n for (const item of finished) {\n if (managedProcesses.size <= MAX_MANAGED_PROCESSES) break;\n managedProcesses.delete(item.id);\n }\n}\n\nexport async function startBackgroundProcess(command: string, cwd?: string) {\n cleanupManagedProcesses();\n if (managedProcesses.size >= MAX_MANAGED_PROCESSES) {\n throw new Error(\n \"Remote Arc already has the maximum number of managed background processes on this device.\",\n );\n }\n\n const child = spawn(command, {\n shell: true,\n cwd,\n windowsHide: true,\n detached: process.platform !== \"win32\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n const id = crypto.randomUUID();\n const item: ManagedProcess = {\n id,\n child,\n command,\n cwd: cwd || null,\n startedAt: Date.now(),\n endedAt: null,\n exitCode: null,\n signal: null,\n stdout: \"\",\n stderr: \"\",\n };\n managedProcesses.set(id, item);\n\n child.stdout?.on(\"data\", (chunk) => {\n item.stdout = appendCapped(item.stdout, chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n item.stderr = appendCapped(item.stderr, chunk);\n });\n child.once(\"error\", (error) => {\n item.stderr = appendCapped(item.stderr, \"\\n\" + error.message);\n item.endedAt = Date.now();\n });\n child.once(\"close\", (code, signal) => {\n item.exitCode = code;\n item.signal = signal;\n item.endedAt = Date.now();\n });\n\n return {\n process_id: id,\n pid: child.pid || null,\n command,\n cwd: cwd || null,\n status: \"running\",\n started_at: new Date(item.startedAt).toISOString(),\n };\n}\n\nfunction managedProcessOrThrow(processId: string) {\n cleanupManagedProcesses();\n const item = managedProcesses.get(processId);\n if (!item) {\n throw new Error(\n \"Managed process not found or its local retention window has expired.\",\n );\n }\n return item;\n}\n\nexport function getManagedProcessStatus(processId: string) {\n const item = managedProcessOrThrow(processId);\n return {\n process_id: item.id,\n pid: item.child.pid || null,\n command: item.command,\n cwd: item.cwd,\n status: item.endedAt === null ? \"running\" : \"exited\",\n exit_code: item.exitCode,\n signal: item.signal,\n started_at: new Date(item.startedAt).toISOString(),\n ended_at: item.endedAt === null ? null : new Date(item.endedAt).toISOString(),\n duration_ms: (item.endedAt || Date.now()) - item.startedAt,\n };\n}\n\nexport function readManagedProcessOutput(processId: string) {\n const item = managedProcessOrThrow(processId);\n return {\n ...getManagedProcessStatus(processId),\n stdout: item.stdout,\n stderr: item.stderr,\n truncated:\n Buffer.byteLength(item.stdout) >= MAX_CAPTURE_BYTES ||\n Buffer.byteLength(item.stderr) >= MAX_CAPTURE_BYTES,\n };\n}\n\nexport async function stopManagedProcess(processId: string) {\n const item = managedProcessOrThrow(processId);\n if (item.endedAt !== null) {\n return {\n ...getManagedProcessStatus(processId),\n stopped: false,\n already_exited: true,\n };\n }\n\n await terminateTree(item.child);\n await new Promise((resolve) => setTimeout(resolve, 50));\n return {\n ...getManagedProcessStatus(processId),\n stopped: true,\n already_exited: false,\n };\n}\n\n\nexport async function stopAllManagedProcesses() {\n const running = [...managedProcesses.values()].filter(\n (item) => item.endedAt === null,\n );\n await Promise.all(\n running.map(async (item) => {\n await terminateTree(item.child).catch(() => undefined);\n }),\n );\n}\n","import crypto from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000;\nconst MAX_SNAPSHOT_BYTES = 20 * 1024 * 1024;\nconst MAX_UNDO_BYTES = 200 * 1024 * 1024;\n\ntype UndoManifest = {\n id: string;\n createdAt: string;\n tool: \"write_file\" | \"edit_block\";\n targetPath: string;\n existed: boolean;\n mode?: number;\n bytes: number;\n postChangeHash?: string;\n};\n\nexport type UndoSnapshot = {\n id: string;\n directory: string;\n manifest: UndoManifest;\n};\n\nconst undoRoot = () =>\n process.env.REMOTEARC_UNDO_ROOT ||\n path.join(os.homedir(), \".remotearc\", \"undo\");\n\nasync function ensureUndoRoot() {\n await fs.mkdir(undoRoot(), { recursive: true, mode: 0o700 });\n}\n\nasync function readManifest(directory: string): Promise<UndoManifest | null> {\n try {\n return JSON.parse(\n await fs.readFile(path.join(directory, \"manifest.json\"), \"utf8\"),\n ) as UndoManifest;\n } catch {\n return null;\n }\n}\n\nasync function snapshotDirectories() {\n await ensureUndoRoot();\n const entries = await fs.readdir(undoRoot(), { withFileTypes: true });\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => path.join(undoRoot(), entry.name));\n}\n\nasync function cleanupUndoStore() {\n const now = Date.now();\n const snapshots: Array<{ directory: string; manifest: UndoManifest }> = [];\n\n for (const directory of await snapshotDirectories()) {\n const manifest = await readManifest(directory);\n if (!manifest) {\n await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);\n continue;\n }\n\n const created = Date.parse(manifest.createdAt);\n if (!Number.isFinite(created) || now - created > RETENTION_MS) {\n await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);\n continue;\n }\n\n snapshots.push({ directory, manifest });\n }\n\n snapshots.sort(\n (a, b) => Date.parse(a.manifest.createdAt) - Date.parse(b.manifest.createdAt),\n );\n\n let total = snapshots.reduce((sum, item) => sum + item.manifest.bytes, 0);\n for (const item of snapshots) {\n if (total <= MAX_UNDO_BYTES) break;\n await fs.rm(item.directory, { recursive: true, force: true }).catch(() => undefined);\n total -= item.manifest.bytes;\n }\n}\n\nfunction mutationPath(\n tool: \"write_file\" | \"edit_block\",\n args: Record<string, unknown>,\n) {\n const candidate = tool === \"write_file\" ? args.path : args.file_path;\n return typeof candidate === \"string\" && candidate.trim() ? candidate : null;\n}\n\nexport async function createUndoSnapshot(\n tool: \"write_file\" | \"edit_block\",\n args: Record<string, unknown>,\n): Promise<UndoSnapshot | null> {\n const targetPath = mutationPath(tool, args);\n if (!targetPath) return null;\n\n await cleanupUndoStore();\n\n let existed = false;\n let mode: number | undefined;\n let bytes = 0;\n let original: Buffer | null = null;\n\n try {\n const stat = await fs.stat(targetPath);\n if (!stat.isFile()) return null;\n existed = true;\n mode = stat.mode;\n bytes = stat.size;\n if (bytes > MAX_SNAPSHOT_BYTES) return null;\n original = await fs.readFile(targetPath);\n } catch (error) {\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : \"\";\n if (code !== \"ENOENT\") throw error;\n }\n\n const id = `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;\n const directory = path.join(undoRoot(), id);\n await fs.mkdir(directory, { recursive: true, mode: 0o700 });\n\n if (original) {\n await fs.writeFile(path.join(directory, \"content.bin\"), original, { mode: 0o600 });\n }\n\n const manifest: UndoManifest = {\n id,\n createdAt: new Date().toISOString(),\n tool,\n targetPath,\n existed,\n ...(mode !== undefined ? { mode } : {}),\n bytes,\n };\n\n await fs.writeFile(\n path.join(directory, \"manifest.json\"),\n JSON.stringify(manifest, null, 2) + \"\\n\",\n { mode: 0o600 },\n );\n\n await cleanupUndoStore();\n return { id, directory, manifest };\n}\n\nasync function hashFile(filePath: string) {\n const hash = crypto.createHash(\"sha256\");\n for await (const chunk of createReadStream(filePath)) hash.update(chunk);\n return hash.digest(\"hex\");\n}\n\nexport async function finalizeUndoSnapshot(snapshot: UndoSnapshot | null) {\n if (!snapshot) return false;\n try {\n snapshot.manifest.postChangeHash = await hashFile(snapshot.manifest.targetPath);\n await fs.writeFile(\n path.join(snapshot.directory, \"manifest.json\"),\n JSON.stringify(snapshot.manifest, null, 2) + \"\\n\",\n { mode: 0o600 },\n );\n return true;\n } catch {\n await discardUndoSnapshot(snapshot);\n return false;\n }\n}\n\nexport async function discardUndoSnapshot(snapshot: UndoSnapshot | null) {\n if (!snapshot) return;\n await fs.rm(snapshot.directory, { recursive: true, force: true }).catch(() => undefined);\n}\n\nasync function undoCandidates() {\n await cleanupUndoStore();\n const candidates: Array<{ directory: string; manifest: UndoManifest }> = [];\n for (const directory of await snapshotDirectories()) {\n const manifest = await readManifest(directory);\n if (manifest) candidates.push({ directory, manifest });\n }\n candidates.sort(\n (a, b) => Date.parse(b.manifest.createdAt) - Date.parse(a.manifest.createdAt),\n );\n return candidates;\n}\n\nexport async function listUndoActions(limit = 20) {\n const candidates = (await undoCandidates()).slice(\n 0,\n Math.max(1, Math.min(100, Math.trunc(limit))),\n );\n\n return Promise.all(\n candidates.map(async ({ manifest }) => {\n let status: \"ready\" | \"conflict\" | \"missing\" | \"legacy\" = \"legacy\";\n\n if (manifest.postChangeHash) {\n try {\n const currentHash = await hashFile(manifest.targetPath);\n status =\n currentHash === manifest.postChangeHash ? \"ready\" : \"conflict\";\n } catch {\n status = \"missing\";\n }\n }\n\n return {\n id: manifest.id,\n created_at: manifest.createdAt,\n tool: manifest.tool,\n path: manifest.targetPath,\n bytes: manifest.bytes,\n existed_before: manifest.existed,\n conflict_safe: Boolean(manifest.postChangeHash),\n can_undo: status === \"ready\",\n status,\n };\n }),\n );\n}\n\nasync function restoreUndoCandidate(candidate: { directory: string; manifest: UndoManifest }) {\n const { directory, manifest } = candidate;\n\n if (!manifest.postChangeHash) {\n throw new Error(\n \"This snapshot predates conflict-safe Local Undo and cannot be restored automatically.\",\n );\n }\n\n let currentHash: string;\n try {\n currentHash = await hashFile(manifest.targetPath);\n } catch {\n throw new Error(\n \"The target file changed or disappeared after the Remote Arc edit. Automatic undo was refused to avoid overwriting newer work.\",\n );\n }\n\n if (currentHash !== manifest.postChangeHash) {\n throw new Error(\n \"The target file changed again after the Remote Arc edit. Automatic undo was refused to avoid overwriting newer work.\",\n );\n }\n\n if (manifest.existed) {\n const original = await fs.readFile(path.join(directory, \"content.bin\"));\n await fs.mkdir(path.dirname(manifest.targetPath), { recursive: true });\n await fs.writeFile(manifest.targetPath, original);\n if (manifest.mode !== undefined) {\n await fs.chmod(manifest.targetPath, manifest.mode).catch(() => undefined);\n }\n } else {\n await fs.rm(manifest.targetPath, { force: true });\n }\n\n await fs.rm(directory, { recursive: true, force: true });\n\n return {\n restored: true,\n action_id: manifest.id,\n tool: manifest.tool,\n path: manifest.targetPath,\n snapshot_location: \"local-device-only\",\n };\n}\n\nexport async function undoChange(actionId: string) {\n const candidate = (await undoCandidates()).find(({ manifest }) => manifest.id === actionId);\n if (!candidate) {\n throw new Error(\"Undo action not found or expired on this device.\");\n }\n return restoreUndoCandidate(candidate);\n}\n\nexport async function undoLastChange() {\n const latest = (await undoCandidates())[0];\n if (!latest) {\n throw new Error(\"No reversible Remote Arc file change is available on this device.\");\n }\n return restoreUndoCandidate(latest);\n}\n\ntype GuardRule = { pattern: RegExp; reason: string };\n\nconst DESTRUCTIVE_COMMAND_RULES: GuardRule[] = [\n {\n pattern: /(?:^|[;&|]\\s*)(?:sudo\\s+)?rm\\s+[^\\n]*(?:-rf|-fr|-[a-z]*r[a-z]*f)[^\\n]*(?:\\s\\/\\s*$|\\s\\/\\*|\\s~(?:\\s|$)|\\s\\$HOME(?:\\s|$))/i,\n reason: \"recursive deletion of a root or home path\",\n },\n {\n pattern: /\\b(?:mkfs(?:\\.\\w+)?|wipefs|fdisk|parted)\\b/i,\n reason: \"disk or filesystem destructive operation\",\n },\n {\n pattern: /\\bdd\\b[^\\n]*\\bof=\\/dev\\/(?:sd|nvme|vd|xvd|mmcblk)/i,\n reason: \"raw disk overwrite\",\n },\n {\n pattern: /\\bdiskutil\\s+erase(?:disk|volume)\\b/i,\n reason: \"disk erase\",\n },\n {\n pattern: /\\b(?:format(?:\\.com)?\\s+[a-z]:|diskpart\\b|clear-disk\\b|initialize-disk\\b)/i,\n reason: \"Windows disk destructive operation\",\n },\n {\n pattern: /\\b(?:shutdown|reboot|halt|poweroff)\\b/i,\n reason: \"system shutdown or reboot\",\n },\n {\n pattern: /\\bremove-item\\b[^\\n]*(?:-recurse[^\\n]*-force|-force[^\\n]*-recurse)[^\\n]*(?:[a-z]:\\\\(?:\\*|\\s|$)|\\$env:systemdrive)/i,\n reason: \"recursive forced deletion of a drive root\",\n },\n {\n pattern: /\\b(?:del|erase|rd|rmdir)\\b[^\\n]*\\/s[^\\n]*\\/q[^\\n]*[a-z]:\\\\/i,\n reason: \"recursive Windows drive deletion\",\n },\n {\n pattern: /:\\(\\)\\s*\\{\\s*:\\|:&\\s*\\};\\s*:/,\n reason: \"fork bomb\",\n },\n];\n\nexport function assertCommandAllowed(command: string) {\n if (process.env.REMOTEARC_ALLOW_DESTRUCTIVE === \"1\") return;\n\n for (const rule of DESTRUCTIVE_COMMAND_RULES) {\n if (rule.pattern.test(command)) {\n throw new Error(\n \"Blocked by Remote Arc Safety Guard: \" +\n rule.reason +\n \". Run this action manually on the device if you intentionally need it.\",\n );\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type ExecutionPolicy = {\n workspaceRoots?: string[];\n protectSensitivePaths?: boolean;\n sensitivePaths?: string[];\n sensitiveAllowPaths?: string[];\n undoEnabled?: boolean;\n};\n\nconst SENSITIVE_BASENAMES = new Set([\n \".npmrc\",\n \".pypirc\",\n \".netrc\",\n \".git-credentials\",\n \"id_rsa\",\n \"id_ed25519\",\n \"credentials\",\n]);\n\nconst expandPath = (value: string) => {\n const trimmed = value.trim();\n if (trimmed === \"~\") return os.homedir();\n if (trimmed.startsWith(\"~/\") || trimmed.startsWith(\"~\\\\\")) {\n return path.join(os.homedir(), trimmed.slice(2));\n }\n return trimmed\n .replace(/%USERPROFILE%/gi, os.homedir())\n .replace(/\\$HOME\\b/g, os.homedir());\n};\n\nconst comparePath = (value: string) => {\n const resolved = path.resolve(expandPath(value));\n return process.platform === \"win32\" ? resolved.toLowerCase() : resolved;\n};\n\nasync function canonicalTarget(targetPath: string) {\n const expanded = path.resolve(expandPath(targetPath));\n try {\n return comparePath(await fs.realpath(expanded));\n } catch {\n const missing: string[] = [];\n let cursor = expanded;\n\n while (true) {\n try {\n const realParent = await fs.realpath(cursor);\n return comparePath(path.join(realParent, ...missing.reverse()));\n } catch {\n const parent = path.dirname(cursor);\n if (parent === cursor) return comparePath(expanded);\n missing.push(path.basename(cursor));\n cursor = parent;\n }\n }\n }\n}\n\nconst isInside = (target: string, root: string) => {\n const relative = path.relative(root, target);\n return (\n relative === \"\" ||\n (!relative.startsWith(\"..\") && !path.isAbsolute(relative))\n );\n};\n\nfunction defaultSensitiveRoots() {\n const home = os.homedir();\n const roots = [\n path.join(home, \".ssh\"),\n path.join(home, \".aws\"),\n path.join(home, \".gnupg\"),\n path.join(home, \".azure\"),\n path.join(home, \".kube\"),\n path.join(home, \".docker\"),\n path.join(home, \".config\", \"gcloud\"),\n ];\n\n if (process.platform === \"darwin\") {\n roots.push(\n path.join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\"),\n path.join(home, \"Library\", \"Application Support\", \"Microsoft Edge\"),\n path.join(home, \"Library\", \"Application Support\", \"Firefox\"),\n );\n }\n\n if (process.platform === \"win32\") {\n const appData = process.env.APPDATA;\n const localAppData = process.env.LOCALAPPDATA;\n if (appData) {\n roots.push(path.join(appData, \"Mozilla\", \"Firefox\"));\n }\n if (localAppData) {\n roots.push(\n path.join(localAppData, \"Google\", \"Chrome\", \"User Data\"),\n path.join(localAppData, \"Microsoft\", \"Edge\", \"User Data\"),\n );\n }\n }\n\n return roots;\n}\n\nfunction looksLikeSensitiveFile(target: string) {\n const basename = path.basename(target).toLowerCase();\n if (basename === \".env\" || basename.startsWith(\".env.\")) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n\n const normalized = target.replace(/\\\\/g, \"/\").toLowerCase();\n if (normalized.endsWith(\"/.docker/config.json\")) return true;\n if (normalized.endsWith(\"/.kube/config\")) return true;\n\n return false;\n}\n\nexport async function enforcePathPolicy(\n targetPath: string,\n policy: ExecutionPolicy = {},\n) {\n const target = await canonicalTarget(targetPath);\n\n const workspaceInputs = (policy.workspaceRoots || []).filter(\n (item) => typeof item === \"string\" && item.trim(),\n );\n const roots = await Promise.all(workspaceInputs.map(canonicalTarget));\n\n if (roots.length && !roots.some((root) => isInside(target, root))) {\n throw new Error(\n \"Blocked by Remote Arc Workspace Scope: path is outside the allowed workspace roots.\",\n );\n }\n\n if (policy.protectSensitivePaths !== false) {\n const sensitiveInputs = [\n ...defaultSensitiveRoots(),\n ...(policy.sensitivePaths || []),\n ].filter((item) => typeof item === \"string\" && item.trim());\n const sensitiveRoots = await Promise.all(\n sensitiveInputs.map(canonicalTarget),\n );\n const allowedSensitiveRoots = await Promise.all(\n (policy.sensitiveAllowPaths || [])\n .filter((item) => typeof item === \"string\" && item.trim())\n .map(canonicalTarget),\n );\n const explicitlyAllowed = allowedSensitiveRoots.some((root) =>\n isInside(target, root),\n );\n\n if (\n !explicitlyAllowed &&\n (looksLikeSensitiveFile(target) ||\n sensitiveRoots.some((root) => isInside(target, root)))\n ) {\n throw new Error(\n \"Blocked by Remote Arc Sensitive Path Policy. Add a narrow sensitive-path exception for this device if you intentionally need access.\",\n );\n }\n }\n\n return target;\n}\n\nexport function normalizePolicy(policy?: ExecutionPolicy): ExecutionPolicy {\n return {\n workspaceRoots: Array.from(\n new Set((policy?.workspaceRoots || []).filter((item) => typeof item === \"string\" && item.trim())),\n ).slice(0, 32),\n protectSensitivePaths: policy?.protectSensitivePaths !== false,\n sensitivePaths: Array.from(\n new Set((policy?.sensitivePaths || []).filter((item) => typeof item === \"string\" && item.trim())),\n ).slice(0, 32),\n sensitiveAllowPaths: Array.from(\n new Set((policy?.sensitiveAllowPaths || []).filter((item) => typeof item === \"string\" && item.trim())),\n ).slice(0, 32),\n undoEnabled: policy?.undoEnabled !== false,\n };\n}\n","import {\n editTextBlock,\n getFileInfo,\n listDirectory,\n readTextFile,\n writeTextFile,\n} from \"./filesystem.js\";\nimport {\n getManagedProcessStatus,\n listProcesses,\n readManagedProcessOutput,\n runShellCommand,\n startBackgroundProcess,\n stopAllManagedProcesses,\n stopManagedProcess,\n} from \"./process.js\";\nimport {\n assertCommandAllowed,\n createUndoSnapshot,\n discardUndoSnapshot,\n finalizeUndoSnapshot,\n listUndoActions,\n undoChange,\n} from \"./safety.js\";\nimport {\n enforcePathPolicy,\n normalizePolicy,\n type ExecutionPolicy,\n} from \"./policy.js\";\nimport type {\n ExecutionMode,\n ToolArguments,\n ToolDefinition,\n ToolName,\n ToolResult,\n} from \"./types.js\";\n\nconst SAFE_TOOLS = new Set<ToolName>([\n \"list_directory\",\n \"read_file\",\n \"get_file_info\",\n \"list_processes\",\n \"list_undo_actions\",\n]);\n\nconst DEVELOPER_TOOLS = new Set<ToolName>([\n ...SAFE_TOOLS,\n \"write_file\",\n \"edit_block\",\n \"undo_change\",\n \"undo_last_change\",\n]);\n\nconst FULL_TOOLS = new Set<ToolName>([\n ...DEVELOPER_TOOLS,\n \"start_process\",\n \"process_status\",\n \"process_output\",\n \"stop_process\",\n]);\n\nconst DEFINITIONS: ToolDefinition[] = [\n {\n name: \"list_directory\",\n description: \"List files and directories on this computer without following directory symlinks.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n depth: { type: \"integer\", minimum: 1, maximum: 10, default: 2 },\n },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n {\n name: \"read_file\",\n description: \"Read a text file by line range. Negative offsets read from the end.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n offset: { type: \"integer\" },\n length: { type: \"integer\", minimum: 1 },\n },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n {\n name: \"get_file_info\",\n description: \"Get local file or directory metadata.\",\n inputSchema: {\n type: \"object\",\n properties: { path: { type: \"string\" } },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n {\n name: \"list_processes\",\n description: \"List processes running on this computer.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"write_file\",\n description: \"Write or append UTF-8 text. Remote Arc creates a local-only Undo snapshot first.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n content: { type: \"string\" },\n mode: { type: \"string\", enum: [\"rewrite\", \"append\"], default: \"rewrite\" },\n },\n required: [\"path\", \"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"edit_block\",\n description: \"Apply an exact text replacement with conflict-safe Local Undo.\",\n inputSchema: {\n type: \"object\",\n properties: {\n file_path: { type: \"string\" },\n old_string: { type: \"string\" },\n new_string: { type: \"string\" },\n expected_replacements: { type: \"integer\", minimum: 1, default: 1 },\n },\n required: [\"file_path\", \"old_string\", \"new_string\"],\n additionalProperties: false,\n },\n },\n {\n name: \"list_undo_actions\",\n description: \"List reversible Remote Arc file changes currently stored on this device.\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: { type: \"integer\", minimum: 1, maximum: 100, default: 20 },\n },\n additionalProperties: false,\n },\n },\n {\n name: \"undo_change\",\n description: \"Restore one specific local Remote Arc undo snapshot by action id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n action_id: { type: \"string\" },\n },\n required: [\"action_id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"undo_last_change\",\n description: \"Undo the newest reversible Remote Arc file edit stored only on this device.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"start_process\",\n description: \"Run a shell command with timeout and output capture. Catastrophic command patterns are blocked locally.\",\n inputSchema: {\n type: \"object\",\n properties: {\n command: { type: \"string\" },\n timeout_ms: { type: \"integer\", minimum: 100, maximum: 120000, default: 5000 },\n cwd: { type: \"string\" },\n background: { type: \"boolean\", default: false },\n },\n required: [\"command\"],\n additionalProperties: false,\n },\n },\n {\n name: \"process_status\",\n description: \"Get status for a Remote Arc managed background process.\",\n inputSchema: {\n type: \"object\",\n properties: { process_id: { type: \"string\" } },\n required: [\"process_id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"process_output\",\n description: \"Read captured stdout and stderr from a Remote Arc managed background process.\",\n inputSchema: {\n type: \"object\",\n properties: { process_id: { type: \"string\" } },\n required: [\"process_id\"],\n additionalProperties: false,\n },\n },\n {\n name: \"stop_process\",\n description: \"Stop a Remote Arc managed background process and its child process tree.\",\n inputSchema: {\n type: \"object\",\n properties: { process_id: { type: \"string\" } },\n required: [\"process_id\"],\n additionalProperties: false,\n },\n },\n];\n\nconst textResult = (value: unknown): ToolResult => ({\n content: [\n {\n type: \"text\",\n text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2),\n },\n ],\n});\n\nfunction requiredString(args: ToolArguments, key: string) {\n const value = args[key];\n if (typeof value !== \"string\") throw new Error(`${key} must be a string.`);\n return value;\n}\n\nfunction optionalNumber(args: ToolArguments, key: string) {\n const value = args[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction optionalString(args: ToolArguments, key: string) {\n const value = args[key];\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nexport class RemoteArcExecutionCore {\n constructor(private readonly mode: ExecutionMode = \"managed\") {}\n\n private allowedTools() {\n if (this.mode === \"safe\") return SAFE_TOOLS;\n if (this.mode === \"developer\") return DEVELOPER_TOOLS;\n return FULL_TOOLS;\n }\n\n listTools() {\n const allowed = this.allowedTools();\n return DEFINITIONS.filter((tool) => allowed.has(tool.name));\n }\n\n async callTool(\n name: string,\n args: ToolArguments = {},\n policyInput: ExecutionPolicy = {},\n ): Promise<ToolResult> {\n const toolName = name as ToolName;\n if (!this.allowedTools().has(toolName)) {\n throw new Error(`Tool blocked by local permission mode: ${name}`);\n }\n\n const policy = normalizePolicy(policyInput);\n\n switch (toolName) {\n case \"list_directory\": {\n const target = await enforcePathPolicy(requiredString(args, \"path\"), policy);\n return textResult(\n await listDirectory(\n target,\n optionalNumber(args, \"depth\") ?? 2,\n async (candidate) => {\n try {\n await enforcePathPolicy(candidate, policy);\n return true;\n } catch {\n return false;\n }\n },\n ),\n );\n }\n case \"read_file\": {\n const target = await enforcePathPolicy(requiredString(args, \"path\"), policy);\n return textResult(\n await readTextFile(\n target,\n optionalNumber(args, \"offset\"),\n optionalNumber(args, \"length\"),\n ),\n );\n }\n case \"get_file_info\": {\n const target = await enforcePathPolicy(requiredString(args, \"path\"), policy);\n return textResult(await getFileInfo(target));\n }\n case \"list_processes\":\n return textResult(await listProcesses());\n case \"list_undo_actions\": {\n const actions = await listUndoActions(optionalNumber(args, \"limit\") ?? 20);\n const visible = [];\n for (const action of actions) {\n try {\n await enforcePathPolicy(action.path, policy);\n visible.push(action);\n } catch {\n // Do not reveal protected or out-of-scope paths through undo metadata.\n }\n }\n return textResult(visible);\n }\n case \"undo_change\": {\n if (policy.undoEnabled === false) {\n throw new Error(\"Local Undo is disabled for this device.\");\n }\n const actionId = requiredString(args, \"action_id\");\n const action = (await listUndoActions(100)).find((item) => item.id === actionId);\n if (!action) throw new Error(\"Undo action not found or expired on this device.\");\n await enforcePathPolicy(action.path, policy);\n return textResult(await undoChange(actionId));\n }\n case \"undo_last_change\": {\n if (policy.undoEnabled === false) {\n throw new Error(\"Local Undo is disabled for this device.\");\n }\n const actions = await listUndoActions(100);\n for (const action of actions) {\n try {\n await enforcePathPolicy(action.path, policy);\n return textResult(await undoChange(action.id));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.startsWith(\"Blocked by Remote Arc\")) throw error;\n }\n }\n throw new Error(\"No reversible in-scope Remote Arc file change is available.\");\n }\n case \"start_process\": {\n const command = requiredString(args, \"command\");\n assertCommandAllowed(command);\n const cwdInput = optionalString(args, \"cwd\");\n if ((policy.workspaceRoots || []).length && !cwdInput) {\n throw new Error(\n \"Workspace Scope is enabled. start_process requires an in-scope cwd. Terminal commands are not an OS sandbox and may still access paths outside that directory.\",\n );\n }\n const cwd = cwdInput ? await enforcePathPolicy(cwdInput, policy) : undefined;\n if (args.background === true) {\n return textResult(await startBackgroundProcess(command, cwd));\n }\n return textResult(\n await runShellCommand(\n command,\n optionalNumber(args, \"timeout_ms\") ?? 5000,\n cwd,\n ),\n );\n }\n case \"process_status\":\n return textResult(\n getManagedProcessStatus(requiredString(args, \"process_id\")),\n );\n case \"process_output\":\n return textResult(\n readManagedProcessOutput(requiredString(args, \"process_id\")),\n );\n case \"stop_process\":\n return textResult(\n await stopManagedProcess(requiredString(args, \"process_id\")),\n );\n case \"write_file\":\n case \"edit_block\": {\n const pathKey = toolName === \"write_file\" ? \"path\" : \"file_path\";\n const target = await enforcePathPolicy(requiredString(args, pathKey), policy);\n const scopedArgs = { ...args, [pathKey]: target };\n const snapshot =\n policy.undoEnabled === false\n ? null\n : await createUndoSnapshot(toolName, scopedArgs);\n try {\n const result =\n toolName === \"write_file\"\n ? await writeTextFile(\n target,\n requiredString(args, \"content\"),\n args.mode === \"append\" ? \"append\" : \"rewrite\",\n )\n : await editTextBlock(\n target,\n requiredString(args, \"old_string\"),\n requiredString(args, \"new_string\"),\n optionalNumber(args, \"expected_replacements\") ?? 1,\n );\n\n const undoAvailable = await finalizeUndoSnapshot(snapshot);\n return textResult({\n ...result,\n undo_available: undoAvailable,\n undo_storage: undoAvailable ? \"local-device-only\" : null,\n });\n } catch (error) {\n await discardUndoSnapshot(snapshot);\n throw error;\n }\n }\n default:\n throw new Error(\"Unknown Remote Arc tool: \" + name);\n }\n }\n\n async close() {\n await stopAllManagedProcesses();\n }\n}\n\nexport const toolDefinitions = DEFINITIONS;\n"],"mappings":";;;AACA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,OAAOC,SAAQ;AACf,SAAS,SAAAC,cAAa;AACtB,OAAOC,cAAa;AACpB,OAAO,eAAe;;;ACNtB,OAAO,YAAY;AACnB,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,IAAM,wBAAwB;AAC9B,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB,KAAK,OAAO;AAExC,IAAM,gBAAgB,CAAC,UAAkB;AACvC,MAAI,QAAQ,KAAM,QAAO,GAAG,KAAK;AACjC,MAAI,QAAQ,OAAO,KAAM,QAAO,IAAI,QAAQ,MAAM,QAAQ,CAAC,CAAC;AAC5D,SAAO,IAAI,SAAS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