pi-remote-call 0.2.0 → 0.3.0
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 +15 -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 +24 -2
- package/src/ssh-config.ts +18 -2
- package/src/transport.ts +65 -28
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 - 2026-11-28
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
- `helperCache` host state reporting for `installed`, `hit`, and pre-operation `inline` fallback.
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- Helper JSON is parsed exclusively from stdout. Stderr is retained for diagnostics, while stdout contamination remains an explicit protocol error.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
3
18
|
## 0.2.0 - 2026-11-28
|
|
4
19
|
|
|
5
20
|
### 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.0
|
|
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.0
|
|
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,20 @@ 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 sftpWriteFileAtomic(sftp: SFTPWrapper, path: string, content: string, durable = false): Promise<void> {
|
|
63
84
|
const stats = await sftpStat(sftp, path).catch(() => undefined);
|
|
64
85
|
const temporary = posix.join(
|
|
65
86
|
posix.dirname(path),
|
|
@@ -72,6 +93,7 @@ export async function sftpWriteFileAtomic(sftp: SFTPWrapper, path: string, conte
|
|
|
72
93
|
stream.once("close", resolve);
|
|
73
94
|
stream.end(content, "utf8");
|
|
74
95
|
});
|
|
96
|
+
if (durable) await sftpFsyncFile(sftp, temporary);
|
|
75
97
|
await sftpRename(sftp, temporary, path);
|
|
76
98
|
} catch (error) {
|
|
77
99
|
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,6 +16,8 @@ import {
|
|
|
15
16
|
sftpMkdirP,
|
|
16
17
|
sftpReadFile,
|
|
17
18
|
sftpRealpath,
|
|
19
|
+
sftpLstat,
|
|
20
|
+
sftpSetStat,
|
|
18
21
|
sftpUnlink,
|
|
19
22
|
sftpWriteFileAtomic,
|
|
20
23
|
} from "./sftp.ts";
|
|
@@ -27,6 +30,7 @@ export interface RemoteHostFacts {
|
|
|
27
30
|
platform: string;
|
|
28
31
|
fileMode: "python" | "sftp";
|
|
29
32
|
python?: { path: string; version: string };
|
|
33
|
+
helperCache?: "hit" | "installed" | "inline";
|
|
30
34
|
}
|
|
31
35
|
|
|
32
36
|
type AuthAttempt =
|
|
@@ -156,6 +160,7 @@ export class SshConnection {
|
|
|
156
160
|
readonly facts: RemoteHostFacts;
|
|
157
161
|
onClose?: () => void;
|
|
158
162
|
private closed = false;
|
|
163
|
+
private helperReady?: Promise<string | undefined>;
|
|
159
164
|
|
|
160
165
|
private constructor(
|
|
161
166
|
readonly client: Client,
|
|
@@ -255,7 +260,7 @@ export class SshConnection {
|
|
|
255
260
|
private async exec(
|
|
256
261
|
command: string,
|
|
257
262
|
cwd: string,
|
|
258
|
-
options: { onData: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
263
|
+
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
259
264
|
): Promise<{ exitCode: number | null }> {
|
|
260
265
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
261
266
|
if (options.signal?.aborted) throw new Error("Operation aborted");
|
|
@@ -280,7 +285,7 @@ export class SshConnection {
|
|
|
280
285
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
281
286
|
if (options.signal?.aborted) onAbort();
|
|
282
287
|
channel.stdout.on("data", options.onData);
|
|
283
|
-
channel.stderr.on("data", options.onData);
|
|
288
|
+
channel.stderr.on("data", options.onStderr ?? options.onData);
|
|
284
289
|
channel.on("exit", (code: number | null) => {
|
|
285
290
|
exitSeen = true;
|
|
286
291
|
exitCode = typeof code === "number" ? code : null;
|
|
@@ -308,43 +313,75 @@ export class SshConnection {
|
|
|
308
313
|
});
|
|
309
314
|
}
|
|
310
315
|
|
|
316
|
+
private async verifyPythonHelper(path: string): Promise<boolean> {
|
|
317
|
+
const python = this.facts.python;
|
|
318
|
+
if (!python) return false;
|
|
319
|
+
const stdoutChunks: Buffer[] = [];
|
|
320
|
+
const source = "import hashlib,sys;print(hashlib.sha256(open(sys.argv[1],\"rb\").read()).hexdigest())";
|
|
321
|
+
try {
|
|
322
|
+
const { exitCode } = await this.exec(`${shellQuote(python.path)} -c ${shellQuote(source)} ${shellQuote(path)}`, this.facts.home, {
|
|
323
|
+
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
324
|
+
onStderr: () => undefined,
|
|
325
|
+
});
|
|
326
|
+
return exitCode === 0 && Buffer.concat(stdoutChunks).toString("utf8").trim() === PYTHON_HELPER_SHA256;
|
|
327
|
+
} catch {
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
private preparePythonHelper(): Promise<string | undefined> {
|
|
333
|
+
if (!this.helperReady) {
|
|
334
|
+
this.helperReady = (async () => {
|
|
335
|
+
const cachePath = pythonHelperCachePath(this.facts.home);
|
|
336
|
+
const cacheDirectory = posix.dirname(cachePath);
|
|
337
|
+
try {
|
|
338
|
+
const cached = await sftpLstat(this.sftp, cachePath).catch(() => undefined);
|
|
339
|
+
if (cached?.isFile() && cached.size === PYTHON_HELPER_BYTES && (cached.mode & 0o077) === 0 && await this.verifyPythonHelper(cachePath)) {
|
|
340
|
+
this.facts.helperCache = "hit";
|
|
341
|
+
return cachePath;
|
|
342
|
+
}
|
|
343
|
+
await sftpMkdirP(this.sftp, cacheDirectory);
|
|
344
|
+
await sftpSetStat(this.sftp, cacheDirectory, { mode: 0o700 });
|
|
345
|
+
await sftpWriteFileAtomic(this.sftp, cachePath, PYTHON_HELPER_SOURCE, true);
|
|
346
|
+
await sftpSetStat(this.sftp, cachePath, { mode: 0o600 });
|
|
347
|
+
if (!await this.verifyPythonHelper(cachePath)) throw new Error("Cached helper hash verification failed");
|
|
348
|
+
this.facts.helperCache = "installed";
|
|
349
|
+
return cachePath;
|
|
350
|
+
} catch {
|
|
351
|
+
this.facts.helperCache = "inline";
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|
|
354
|
+
})();
|
|
355
|
+
}
|
|
356
|
+
return this.helperReady;
|
|
357
|
+
}
|
|
358
|
+
|
|
311
359
|
async runPythonFileOperation(request: PythonFileRequest, signal?: AbortSignal): Promise<unknown> {
|
|
312
360
|
const python = this.facts.python;
|
|
313
361
|
if (!python) throw new RemoteCallError("E_REMOTE_HELPER", `Python 3 is not available for ${this.facts.alias}`);
|
|
314
362
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
315
363
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
364
|
+
const helperPath = await this.preparePythonHelper();
|
|
316
365
|
const requestPath = posix.join("/tmp", `pi-remote-call-${process.pid}-${randomBytes(12).toString("hex")}.json`);
|
|
317
366
|
try {
|
|
318
367
|
await sftpWriteFileAtomic(this.sftp, requestPath, JSON.stringify(request));
|
|
319
368
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
320
|
-
const
|
|
321
|
-
const
|
|
369
|
+
const stdoutChunks: Buffer[] = [];
|
|
370
|
+
const stderrChunks: Buffer[] = [];
|
|
371
|
+
const command = helperPath
|
|
372
|
+
? `${shellQuote(python.path)} ${shellQuote(helperPath)} ${shellQuote(requestPath)}`
|
|
373
|
+
: `${shellQuote(python.path)} -c ${shellQuote(PYTHON_HELPER_SOURCE)} ${shellQuote(requestPath)}`;
|
|
322
374
|
const { exitCode } = await this.exec(command, this.facts.home, {
|
|
323
|
-
onData: (data) =>
|
|
375
|
+
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
376
|
+
onStderr: (data) => stderrChunks.push(Buffer.from(data)),
|
|
324
377
|
signal,
|
|
325
378
|
});
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
"E_REMOTE_HELPER",
|
|
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);
|
|
379
|
+
return parsePythonHelperResponse(
|
|
380
|
+
this.facts.alias,
|
|
381
|
+
Buffer.concat(stdoutChunks).toString("utf8"),
|
|
382
|
+
Buffer.concat(stderrChunks).toString("utf8"),
|
|
383
|
+
exitCode,
|
|
384
|
+
);
|
|
348
385
|
} finally {
|
|
349
386
|
await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
350
387
|
}
|