pi-remote-call 0.2.0 → 0.3.1
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/CHANGELOG.md +26 -0
- package/README.md +7 -4
- package/package.json +1 -1
- package/src/host-manager.ts +2 -1
- package/src/index.ts +2 -1
- package/src/python-protocol.ts +32 -0
- package/src/remote-helper.ts +9 -0
- package/src/sftp.ts +40 -2
- package/src/ssh-config.ts +18 -2
- package/src/transport.ts +73 -30
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.1 - 2026-11-28
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Python helper requests now use exclusive direct writes (`wx`, mode `0600`), removing redundant request-file stat and rename round trips.
|
|
8
|
+
- Successful helper commands clean up their request file in the same remote command while preserving the helper exit status. Interrupted setup or execution retains best-effort SFTP cleanup.
|
|
9
|
+
|
|
10
|
+
### Performance
|
|
11
|
+
|
|
12
|
+
- Real SSH benchmarks measured 25–34% lower small-file cached-read p50 latency and 28–38% lower large-file ranged-read p50 latency.
|
|
13
|
+
|
|
14
|
+
## 0.3.0 - 2026-11-28
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- Versioned remote helper caching keyed by the protocol and complete source SHA-256, with per-connection verification, shared initialization, secure modes, `fsync`, and atomic installation.
|
|
19
|
+
- `helperCache` host state reporting for `installed`, `hit`, and pre-operation `inline` fallback.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- Helper JSON is parsed exclusively from stdout. Stderr is retained for diagnostics, while stdout contamination remains an explicit protocol error.
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- Windows Git Bash/MSYS and Cygwin SSH paths such as `/c/...` now resolve as local files; Windows OpenSSH `__PROGRAMDATA__` known-hosts paths are expanded correctly.
|
|
28
|
+
|
|
3
29
|
## 0.2.0 - 2026-11-28
|
|
4
30
|
|
|
5
31
|
### Added
|
package/README.md
CHANGED
|
@@ -25,13 +25,13 @@ Remote machine:
|
|
|
25
25
|
### npm
|
|
26
26
|
|
|
27
27
|
```sh
|
|
28
|
-
pi install npm:pi-remote-call@0.
|
|
28
|
+
pi install npm:pi-remote-call@0.3.1
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
### GitHub
|
|
32
32
|
|
|
33
33
|
```sh
|
|
34
|
-
pi install git:github.com/therainisme/pi-remote-call@v0.
|
|
34
|
+
pi install git:github.com/therainisme/pi-remote-call@v0.3.1
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
### Local directory
|
|
@@ -62,7 +62,9 @@ Each new connection probes for Python 3 and reports `fileMode` in host status an
|
|
|
62
62
|
- `python`: a bundled, standard-library-only helper runs once per text operation. Reads return only the requested range plus pagination metadata; edits return diff details without transferring the whole file to the local machine. Writes and edits use temporary files, metadata checks, and atomic replacement.
|
|
63
63
|
- `sftp`: the original 0.1.1 behavior remains as a compatibility path. Pi's native read streams through SFTP, while edits are computed locally and written back through SFTP.
|
|
64
64
|
|
|
65
|
-
Python is never installed by this extension. The helper runs without a daemon or
|
|
65
|
+
Python is never installed by this extension. The helper runs without a daemon, remote Pi, Node.js, or MCP server. Its source is cached at `~/.pi/agent/cache/pi-remote-call/helper-v1-<sha256>.py`; the directory is mode `0700` and the helper is `0600`. Each connection verifies the regular file, size, and SHA-256 before its first cached operation, and concurrent callers share that initialization. Cache installation uses a temporary file, `fsync`, and atomic rename. Old versions are not deleted automatically.
|
|
66
|
+
|
|
67
|
+
If the cache cannot be prepared, the helper source is sent inline instead. Fallback is selected before an operation starts: a Python operation that fails is never replayed through SFTP. Host status reports `helperCache` as `installed`, `hit`, or `inline` after initialization.
|
|
66
68
|
|
|
67
69
|
## Tools
|
|
68
70
|
|
|
@@ -188,7 +190,8 @@ src/file-tools.ts remote POSIX paths, exact edits, native result details
|
|
|
188
190
|
src/config.ts allowlist-only configuration
|
|
189
191
|
src/python-files.ts Python result validation and native read formatting
|
|
190
192
|
src/remote_helper.py one-shot remote text read/write/edit helper
|
|
191
|
-
src/remote-helper.ts
|
|
193
|
+
src/remote-helper.ts helper source identity and versioned cache path
|
|
194
|
+
src/python-protocol.ts helper stdout/stderr and JSON response handling
|
|
192
195
|
```
|
|
193
196
|
|
|
194
197
|
MIT
|
package/package.json
CHANGED
package/src/host-manager.ts
CHANGED
|
@@ -13,7 +13,7 @@ export class HostManager {
|
|
|
13
13
|
|
|
14
14
|
constructor(readonly config: RemoteCallConfig) {}
|
|
15
15
|
|
|
16
|
-
list(): Array<{ host: string; connected: boolean; home?: string; hostname?: string; user?: string; platform?: string; fileMode?: "python" | "sftp"; pythonVersion?: string }> {
|
|
16
|
+
list(): Array<{ host: string; connected: boolean; home?: string; hostname?: string; user?: string; platform?: string; fileMode?: "python" | "sftp"; pythonVersion?: string; helperCache?: "hit" | "installed" | "inline" }> {
|
|
17
17
|
return this.config.hosts.map((host) => {
|
|
18
18
|
const connection = this.entries.get(host)?.connection;
|
|
19
19
|
return {
|
|
@@ -27,6 +27,7 @@ export class HostManager {
|
|
|
27
27
|
platform: connection.facts.platform,
|
|
28
28
|
fileMode: connection.facts.fileMode,
|
|
29
29
|
pythonVersion: connection.facts.python?.version,
|
|
30
|
+
...(connection.facts.helperCache ? { helperCache: connection.facts.helperCache } : {}),
|
|
30
31
|
}
|
|
31
32
|
: {}),
|
|
32
33
|
};
|
package/src/index.ts
CHANGED
|
@@ -12,7 +12,8 @@ function errorMessage(error: unknown): string {
|
|
|
12
12
|
function formatHosts(manager: HostManager): string {
|
|
13
13
|
return manager.list().map((host) => {
|
|
14
14
|
if (!host.connected) return `${host.host} — disconnected`;
|
|
15
|
-
|
|
15
|
+
const cache = host.helperCache ? `, helper: ${host.helperCache}` : "";
|
|
16
|
+
return `${host.host} — ${host.user}@${host.hostname} (${host.platform}, ${host.fileMode}${cache}), home: ${host.home}`;
|
|
16
17
|
}).join("\n");
|
|
17
18
|
}
|
|
18
19
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { RemoteCallError } from "./errors.ts";
|
|
2
|
+
|
|
3
|
+
export function parsePythonHelperResponse(
|
|
4
|
+
alias: string,
|
|
5
|
+
stdout: string,
|
|
6
|
+
stderr: string,
|
|
7
|
+
exitCode: number | null,
|
|
8
|
+
): unknown {
|
|
9
|
+
const output = stdout.trim();
|
|
10
|
+
const diagnostic = stderr.trim().slice(0, 2000);
|
|
11
|
+
let envelope: { ok?: unknown; result?: unknown; error?: { code?: unknown; message?: unknown } };
|
|
12
|
+
try {
|
|
13
|
+
envelope = JSON.parse(output) as typeof envelope;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
throw new RemoteCallError(
|
|
16
|
+
"E_REMOTE_HELPER",
|
|
17
|
+
`Python helper on ${alias} returned invalid output (exit ${exitCode}): ${output.slice(0, 2000)}${diagnostic ? `\nRemote stderr: ${diagnostic}` : ""}`,
|
|
18
|
+
undefined,
|
|
19
|
+
{ cause: error },
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
if (envelope.ok === true && exitCode === 0) return envelope.result;
|
|
23
|
+
const code = typeof envelope.error?.code === "string" ? envelope.error.code : "E_REMOTE_HELPER";
|
|
24
|
+
const message = typeof envelope.error?.message === "string"
|
|
25
|
+
? envelope.error.message
|
|
26
|
+
: `Python helper on ${alias} failed with exit code ${exitCode}`;
|
|
27
|
+
if (code === "E_EDIT") throw new Error(message);
|
|
28
|
+
if (code === "E_REMOTE_FILE_CHANGED" || code === "E_REMOTE_METADATA" || code === "E_REMOTE_HELPER") {
|
|
29
|
+
throw new RemoteCallError(code, message);
|
|
30
|
+
}
|
|
31
|
+
throw new RemoteCallError("E_REMOTE_HELPER", message);
|
|
32
|
+
}
|
package/src/remote-helper.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { readFileSync } from "node:fs";
|
|
3
|
+
import { posix } from "node:path";
|
|
2
4
|
|
|
5
|
+
export const PYTHON_HELPER_PROTOCOL = 1;
|
|
3
6
|
export const PYTHON_HELPER_SOURCE = readFileSync(new URL("./remote_helper.py", import.meta.url), "utf8");
|
|
7
|
+
export const PYTHON_HELPER_SHA256 = createHash("sha256").update(PYTHON_HELPER_SOURCE).digest("hex");
|
|
8
|
+
export const PYTHON_HELPER_BYTES = Buffer.byteLength(PYTHON_HELPER_SOURCE, "utf8");
|
|
9
|
+
|
|
10
|
+
export function pythonHelperCachePath(home: string): string {
|
|
11
|
+
return posix.join(home, ".pi", "agent", "cache", "pi-remote-call", `helper-v${PYTHON_HELPER_PROTOCOL}-${PYTHON_HELPER_SHA256}.py`);
|
|
12
|
+
}
|
package/src/sftp.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { posix } from "node:path";
|
|
3
|
-
import type { SFTPWrapper, Stats } from "ssh2";
|
|
3
|
+
import type { InputAttributes, SFTPWrapper, Stats } from "ssh2";
|
|
4
4
|
|
|
5
5
|
export function sftpRealpath(sftp: SFTPWrapper, path: string): Promise<string> {
|
|
6
6
|
return new Promise((resolve, reject) => sftp.realpath(path, (error, result) => (error ? reject(error) : resolve(result))));
|
|
@@ -10,6 +10,14 @@ export function sftpStat(sftp: SFTPWrapper, path: string): Promise<Stats> {
|
|
|
10
10
|
return new Promise((resolve, reject) => sftp.stat(path, (error, stats) => (error ? reject(error) : resolve(stats))));
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
export function sftpLstat(sftp: SFTPWrapper, path: string): Promise<Stats> {
|
|
14
|
+
return new Promise((resolve, reject) => sftp.lstat(path, (error, stats) => (error ? reject(error) : resolve(stats))));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function sftpSetStat(sftp: SFTPWrapper, path: string, attributes: InputAttributes): Promise<void> {
|
|
18
|
+
return new Promise((resolve, reject) => sftp.setstat(path, attributes, (error) => (error ? reject(error) : resolve())));
|
|
19
|
+
}
|
|
20
|
+
|
|
13
21
|
export function sftpMkdir(sftp: SFTPWrapper, path: string): Promise<void> {
|
|
14
22
|
return new Promise((resolve, reject) => sftp.mkdir(path, (error) => (error ? reject(error) : resolve())));
|
|
15
23
|
}
|
|
@@ -59,7 +67,36 @@ function sftpRename(sftp: SFTPWrapper, source: string, destination: string): Pro
|
|
|
59
67
|
});
|
|
60
68
|
}
|
|
61
69
|
|
|
62
|
-
|
|
70
|
+
async function sftpFsyncFile(sftp: SFTPWrapper, path: string): Promise<void> {
|
|
71
|
+
const handle = await new Promise<Buffer>((resolve, reject) =>
|
|
72
|
+
sftp.open(path, "r", (error, value) => (error ? reject(error) : resolve(value))),
|
|
73
|
+
);
|
|
74
|
+
try {
|
|
75
|
+
await new Promise<void>((resolve, reject) =>
|
|
76
|
+
sftp.ext_openssh_fsync(handle, (error) => (error ? reject(error) : resolve())),
|
|
77
|
+
);
|
|
78
|
+
} finally {
|
|
79
|
+
await new Promise<void>((resolve, reject) => sftp.close(handle, (error) => (error ? reject(error) : resolve())));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function sftpWriteNewFile(sftp: SFTPWrapper, path: string, content: string): Promise<void> {
|
|
84
|
+
let created = false;
|
|
85
|
+
try {
|
|
86
|
+
await new Promise<void>((resolve, reject) => {
|
|
87
|
+
const stream = sftp.createWriteStream(path, { flags: "wx", mode: 0o600 });
|
|
88
|
+
stream.once("open", () => (created = true));
|
|
89
|
+
stream.once("error", reject);
|
|
90
|
+
stream.once("close", resolve);
|
|
91
|
+
stream.end(content, "utf8");
|
|
92
|
+
});
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (created) await sftpUnlink(sftp, path).catch(() => undefined);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function sftpWriteFileAtomic(sftp: SFTPWrapper, path: string, content: string, durable = false): Promise<void> {
|
|
63
100
|
const stats = await sftpStat(sftp, path).catch(() => undefined);
|
|
64
101
|
const temporary = posix.join(
|
|
65
102
|
posix.dirname(path),
|
|
@@ -72,6 +109,7 @@ export async function sftpWriteFileAtomic(sftp: SFTPWrapper, path: string, conte
|
|
|
72
109
|
stream.once("close", resolve);
|
|
73
110
|
stream.end(content, "utf8");
|
|
74
111
|
});
|
|
112
|
+
if (durable) await sftpFsyncFile(sftp, temporary);
|
|
75
113
|
await sftpRename(sftp, temporary, path);
|
|
76
114
|
} catch (error) {
|
|
77
115
|
await sftpUnlink(sftp, temporary).catch(() => undefined);
|
package/src/ssh-config.ts
CHANGED
|
@@ -56,6 +56,22 @@ function expandHome(path: string): string {
|
|
|
56
56
|
return path;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
export function normalizeLocalSshPath(
|
|
60
|
+
path: string,
|
|
61
|
+
platform: NodeJS.Platform = process.platform,
|
|
62
|
+
programData = process.env.ProgramData ?? "C:\\ProgramData",
|
|
63
|
+
): string {
|
|
64
|
+
const expanded = expandHome(path);
|
|
65
|
+
if (platform !== "win32") return expanded;
|
|
66
|
+
const drivePath = expanded.match(/^\/(?:cygdrive\/)?([A-Za-z])(?:\/(.*))?$/);
|
|
67
|
+
if (drivePath) return `${drivePath[1].toUpperCase()}:\\${(drivePath[2] ?? "").replace(/\//g, "\\")}`;
|
|
68
|
+
const programDataPath = expanded.match(/^__PROGRAMDATA__(?:[\\/](.*))?$/i);
|
|
69
|
+
if (programDataPath) {
|
|
70
|
+
return `${programData.replace(/[\\/]+$/, "")}\\${(programDataPath[1] ?? "").replace(/\//g, "\\")}`;
|
|
71
|
+
}
|
|
72
|
+
return expanded;
|
|
73
|
+
}
|
|
74
|
+
|
|
59
75
|
export function parseSshG(alias: string, output: string): EffectiveSshConfig {
|
|
60
76
|
const values = new Map<string, string[]>();
|
|
61
77
|
for (const line of output.split(/\r?\n/)) {
|
|
@@ -81,7 +97,7 @@ export function parseSshG(alias: string, output: string): EffectiveSshConfig {
|
|
|
81
97
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
82
98
|
throw new RemoteCallError("E_SSH_CONFIG", `Invalid SSH port for ${alias}: ${portText}`);
|
|
83
99
|
}
|
|
84
|
-
const identityFiles = (values.get("identityfile") ?? []).flatMap(splitSshWords).map(
|
|
100
|
+
const identityFiles = (values.get("identityfile") ?? []).flatMap(splitSshWords).map((path) => normalizeLocalSshPath(path));
|
|
85
101
|
const configuredAgent = one("identityagent");
|
|
86
102
|
let identityAgent = configuredAgent;
|
|
87
103
|
if (configuredAgent?.startsWith("$")) identityAgent = process.env[configuredAgent.slice(1)];
|
|
@@ -91,7 +107,7 @@ export function parseSshG(alias: string, output: string): EffectiveSshConfig {
|
|
|
91
107
|
const knownHostsFiles = [
|
|
92
108
|
...(values.get("userknownhostsfile") ?? []).flatMap(splitSshWords),
|
|
93
109
|
...(values.get("globalknownhostsfile") ?? []).flatMap(splitSshWords),
|
|
94
|
-
].map(
|
|
110
|
+
].map((path) => normalizeLocalSshPath(path));
|
|
95
111
|
if (knownHostsFiles.length === 0) knownHostsFiles.push(join(homedir(), ".ssh", "known_hosts"));
|
|
96
112
|
const proxyJump = one("proxyjump");
|
|
97
113
|
return {
|
package/src/transport.ts
CHANGED
|
@@ -6,7 +6,8 @@ import type { BashOperations, EditOperations, ReadOperations, WriteOperations }
|
|
|
6
6
|
import { asRemoteCallError, RemoteCallError } from "./errors.ts";
|
|
7
7
|
import { loadKnownHostEntries, verifyKnownHostKey, type KnownHostEntry } from "./host-key.ts";
|
|
8
8
|
import type { PythonFileRequest } from "./python-files.ts";
|
|
9
|
-
import { PYTHON_HELPER_SOURCE } from "./remote-helper.ts";
|
|
9
|
+
import { PYTHON_HELPER_BYTES, PYTHON_HELPER_SHA256, PYTHON_HELPER_SOURCE, pythonHelperCachePath } from "./remote-helper.ts";
|
|
10
|
+
import { parsePythonHelperResponse } from "./python-protocol.ts";
|
|
10
11
|
import { remoteCommandScript, shellQuote } from "./remote-path.ts";
|
|
11
12
|
import { resolveSshConfig, type EffectiveSshConfig } from "./ssh-config.ts";
|
|
12
13
|
import {
|
|
@@ -15,8 +16,11 @@ import {
|
|
|
15
16
|
sftpMkdirP,
|
|
16
17
|
sftpReadFile,
|
|
17
18
|
sftpRealpath,
|
|
19
|
+
sftpLstat,
|
|
20
|
+
sftpSetStat,
|
|
18
21
|
sftpUnlink,
|
|
19
22
|
sftpWriteFileAtomic,
|
|
23
|
+
sftpWriteNewFile,
|
|
20
24
|
} from "./sftp.ts";
|
|
21
25
|
|
|
22
26
|
export interface RemoteHostFacts {
|
|
@@ -27,6 +31,7 @@ export interface RemoteHostFacts {
|
|
|
27
31
|
platform: string;
|
|
28
32
|
fileMode: "python" | "sftp";
|
|
29
33
|
python?: { path: string; version: string };
|
|
34
|
+
helperCache?: "hit" | "installed" | "inline";
|
|
30
35
|
}
|
|
31
36
|
|
|
32
37
|
type AuthAttempt =
|
|
@@ -156,6 +161,7 @@ export class SshConnection {
|
|
|
156
161
|
readonly facts: RemoteHostFacts;
|
|
157
162
|
onClose?: () => void;
|
|
158
163
|
private closed = false;
|
|
164
|
+
private helperReady?: Promise<string | undefined>;
|
|
159
165
|
|
|
160
166
|
private constructor(
|
|
161
167
|
readonly client: Client,
|
|
@@ -255,7 +261,7 @@ export class SshConnection {
|
|
|
255
261
|
private async exec(
|
|
256
262
|
command: string,
|
|
257
263
|
cwd: string,
|
|
258
|
-
options: { onData: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
264
|
+
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
259
265
|
): Promise<{ exitCode: number | null }> {
|
|
260
266
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
261
267
|
if (options.signal?.aborted) throw new Error("Operation aborted");
|
|
@@ -280,7 +286,7 @@ export class SshConnection {
|
|
|
280
286
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
281
287
|
if (options.signal?.aborted) onAbort();
|
|
282
288
|
channel.stdout.on("data", options.onData);
|
|
283
|
-
channel.stderr.on("data", options.onData);
|
|
289
|
+
channel.stderr.on("data", options.onStderr ?? options.onData);
|
|
284
290
|
channel.on("exit", (code: number | null) => {
|
|
285
291
|
exitSeen = true;
|
|
286
292
|
exitCode = typeof code === "number" ? code : null;
|
|
@@ -308,45 +314,82 @@ export class SshConnection {
|
|
|
308
314
|
});
|
|
309
315
|
}
|
|
310
316
|
|
|
317
|
+
private async verifyPythonHelper(path: string): Promise<boolean> {
|
|
318
|
+
const python = this.facts.python;
|
|
319
|
+
if (!python) return false;
|
|
320
|
+
const stdoutChunks: Buffer[] = [];
|
|
321
|
+
const source = "import hashlib,sys;print(hashlib.sha256(open(sys.argv[1],\"rb\").read()).hexdigest())";
|
|
322
|
+
try {
|
|
323
|
+
const { exitCode } = await this.exec(`${shellQuote(python.path)} -c ${shellQuote(source)} ${shellQuote(path)}`, this.facts.home, {
|
|
324
|
+
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
325
|
+
onStderr: () => undefined,
|
|
326
|
+
});
|
|
327
|
+
return exitCode === 0 && Buffer.concat(stdoutChunks).toString("utf8").trim() === PYTHON_HELPER_SHA256;
|
|
328
|
+
} catch {
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private preparePythonHelper(): Promise<string | undefined> {
|
|
334
|
+
if (!this.helperReady) {
|
|
335
|
+
this.helperReady = (async () => {
|
|
336
|
+
const cachePath = pythonHelperCachePath(this.facts.home);
|
|
337
|
+
const cacheDirectory = posix.dirname(cachePath);
|
|
338
|
+
try {
|
|
339
|
+
const cached = await sftpLstat(this.sftp, cachePath).catch(() => undefined);
|
|
340
|
+
if (cached?.isFile() && cached.size === PYTHON_HELPER_BYTES && (cached.mode & 0o077) === 0 && await this.verifyPythonHelper(cachePath)) {
|
|
341
|
+
this.facts.helperCache = "hit";
|
|
342
|
+
return cachePath;
|
|
343
|
+
}
|
|
344
|
+
await sftpMkdirP(this.sftp, cacheDirectory);
|
|
345
|
+
await sftpSetStat(this.sftp, cacheDirectory, { mode: 0o700 });
|
|
346
|
+
await sftpWriteFileAtomic(this.sftp, cachePath, PYTHON_HELPER_SOURCE, true);
|
|
347
|
+
await sftpSetStat(this.sftp, cachePath, { mode: 0o600 });
|
|
348
|
+
if (!await this.verifyPythonHelper(cachePath)) throw new Error("Cached helper hash verification failed");
|
|
349
|
+
this.facts.helperCache = "installed";
|
|
350
|
+
return cachePath;
|
|
351
|
+
} catch {
|
|
352
|
+
this.facts.helperCache = "inline";
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
})();
|
|
356
|
+
}
|
|
357
|
+
return this.helperReady;
|
|
358
|
+
}
|
|
359
|
+
|
|
311
360
|
async runPythonFileOperation(request: PythonFileRequest, signal?: AbortSignal): Promise<unknown> {
|
|
312
361
|
const python = this.facts.python;
|
|
313
362
|
if (!python) throw new RemoteCallError("E_REMOTE_HELPER", `Python 3 is not available for ${this.facts.alias}`);
|
|
314
363
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
315
364
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
365
|
+
const helperPath = await this.preparePythonHelper();
|
|
316
366
|
const requestPath = posix.join("/tmp", `pi-remote-call-${process.pid}-${randomBytes(12).toString("hex")}.json`);
|
|
367
|
+
let requestCreated = false;
|
|
368
|
+
let remoteCleanup = false;
|
|
317
369
|
try {
|
|
318
|
-
await
|
|
370
|
+
await sftpWriteNewFile(this.sftp, requestPath, JSON.stringify(request));
|
|
371
|
+
requestCreated = true;
|
|
319
372
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
320
|
-
const
|
|
321
|
-
const
|
|
373
|
+
const stdoutChunks: Buffer[] = [];
|
|
374
|
+
const stderrChunks: Buffer[] = [];
|
|
375
|
+
const helperCommand = helperPath
|
|
376
|
+
? `${shellQuote(python.path)} ${shellQuote(helperPath)} ${shellQuote(requestPath)}`
|
|
377
|
+
: `${shellQuote(python.path)} -c ${shellQuote(PYTHON_HELPER_SOURCE)} ${shellQuote(requestPath)}`;
|
|
378
|
+
const command = `${helperCommand}; helper_status=$?; rm -f -- ${shellQuote(requestPath)}; exit "$helper_status"`;
|
|
322
379
|
const { exitCode } = await this.exec(command, this.facts.home, {
|
|
323
|
-
onData: (data) =>
|
|
380
|
+
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
381
|
+
onStderr: (data) => stderrChunks.push(Buffer.from(data)),
|
|
324
382
|
signal,
|
|
325
383
|
});
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
`Python helper on ${this.facts.alias} returned invalid output (exit ${exitCode}): ${output.slice(0, 2000)}`,
|
|
334
|
-
undefined,
|
|
335
|
-
{ cause: error },
|
|
336
|
-
);
|
|
337
|
-
}
|
|
338
|
-
if (envelope.ok === true && exitCode === 0) return envelope.result;
|
|
339
|
-
const code = typeof envelope.error?.code === "string" ? envelope.error.code : "E_REMOTE_HELPER";
|
|
340
|
-
const message = typeof envelope.error?.message === "string"
|
|
341
|
-
? envelope.error.message
|
|
342
|
-
: `Python helper on ${this.facts.alias} failed with exit code ${exitCode}`;
|
|
343
|
-
if (code === "E_EDIT") throw new Error(message);
|
|
344
|
-
if (code === "E_REMOTE_FILE_CHANGED" || code === "E_REMOTE_METADATA" || code === "E_REMOTE_HELPER") {
|
|
345
|
-
throw new RemoteCallError(code, message);
|
|
346
|
-
}
|
|
347
|
-
throw new RemoteCallError("E_REMOTE_HELPER", message);
|
|
384
|
+
remoteCleanup = true;
|
|
385
|
+
return parsePythonHelperResponse(
|
|
386
|
+
this.facts.alias,
|
|
387
|
+
Buffer.concat(stdoutChunks).toString("utf8"),
|
|
388
|
+
Buffer.concat(stderrChunks).toString("utf8"),
|
|
389
|
+
exitCode,
|
|
390
|
+
);
|
|
348
391
|
} finally {
|
|
349
|
-
await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
392
|
+
if (requestCreated && !remoteCleanup) await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
350
393
|
}
|
|
351
394
|
}
|
|
352
395
|
|