pi-remote-call 0.1.1 → 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 CHANGED
@@ -1,5 +1,33 @@
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
+
18
+ ## 0.2.0 - 2026-11-28
19
+
20
+ ### Added
21
+
22
+ - Optional Python 3 fast path for remote-side text pagination, complete writes, and exact edits with native result formatting.
23
+ - Per-connection `fileMode` reporting and explicit Python/SFTP routing tests.
24
+ - Remote edit conflict detection, symbolic-link handling, ordinary metadata preservation, and safe rejection of unsupported replacements.
25
+
26
+ ### Changed
27
+
28
+ - Hosts without Python retain the 0.1.1 SFTP implementation. Python failures after an operation starts are never replayed through SFTP.
29
+ - CI now provisions Python so helper contract tests run on Ubuntu, Windows, and macOS.
30
+
3
31
  ## 0.1.1 - 2026-11-28
4
32
 
5
33
  ### Changed
package/README.md CHANGED
@@ -16,6 +16,8 @@ Local machine:
16
16
  Remote machine:
17
17
 
18
18
  - `sshd`, Bash, and SFTP already enabled
19
+ - Optional but recommended: `python3` 3.8+ for remote-side text reads and edits. No pip packages are needed.
20
+ - Without Python, text tools retain the SFTP behavior from version 0.1.1.
19
21
  - Standard `hostname`, `id`, `uname`, `kill`, and `sleep` commands
20
22
 
21
23
  ## Install
@@ -23,13 +25,13 @@ Remote machine:
23
25
  ### npm
24
26
 
25
27
  ```sh
26
- pi install npm:pi-remote-call@0.1.1
28
+ pi install npm:pi-remote-call@0.3.0
27
29
  ```
28
30
 
29
31
  ### GitHub
30
32
 
31
33
  ```sh
32
- pi install git:github.com/therainisme/pi-remote-call@v0.1.1
34
+ pi install git:github.com/therainisme/pi-remote-call@v0.3.0
33
35
  ```
34
36
 
35
37
  ### Local directory
@@ -53,6 +55,17 @@ Set `PI_REMOTE_CALL_CONFIG` to use a different local config path.
53
55
 
54
56
  Restart Pi after changing the allowlist. Connections are opened lazily and are not opened by `remote_hosts({action:"list"})`.
55
57
 
58
+ ## File execution modes
59
+
60
+ Each new connection probes for Python 3 and reports `fileMode` in host status and diagnostics:
61
+
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
+ - `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
+
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.
68
+
56
69
  ## Tools
57
70
 
58
71
  Every execution tool requires `host`. There is no global current host, so calls to different hosts can be made independently in the same turn.
@@ -95,7 +108,7 @@ Every execution tool requires `host`. There is no global current host, so calls
95
108
 
96
109
  The example reads `~/notes/todo.md`. An optional `cwd` changes the base for relative paths. Absolute paths and `~/...` ignore `cwd`.
97
110
 
98
- Text pagination and head truncation use Pi's native read implementation. Supported images are read over SFTP and returned as native Pi image content.
111
+ Text pagination and head truncation match Pi's native read behavior. In Python mode, the remote helper scans the file and returns only the selected range and pagination metadata. In SFTP mode, native read streams the file to the local machine as in 0.1.1. Supported images are always read over SFTP and returned as native Pi image content.
99
112
 
100
113
  ### `remote_write`
101
114
 
@@ -107,7 +120,7 @@ Text pagination and head truncation use Pi's native read implementation. Support
107
120
  }
108
121
  ```
109
122
 
110
- Creates parent directories, then writes through a same-directory temporary SFTP file and rename. Existing permission bits are preserved where SFTP supports them. This is for new files or complete rewrites.
123
+ Creates parent directories and completely replaces the target. Python mode preserves ordinary permission bits, owner/group, and available xattrs, resolves symbolic links, and rejects unsafe hard-link or special-mode replacements. SFTP mode retains the 0.1.1 temporary-file and rename behavior. This tool is for new files or complete rewrites.
111
124
 
112
125
  ### `remote_edit`
113
126
 
@@ -121,7 +134,7 @@ Creates parent directories, then writes through a same-directory temporary SFTP
121
134
  }
122
135
  ```
123
136
 
124
- All replacements must exactly and uniquely match disjoint regions of the same original file. Empty, missing, duplicate, overlapping, and no-op edits fail before writing. BOM and existing LF/CRLF line endings are preserved. Results contain Pi-native `diff`, `patch`, and `firstChangedLine` details.
137
+ All replacements must exactly and uniquely match disjoint regions of the same original file. Empty, missing, duplicate, overlapping, and no-op edits fail before writing. BOM and existing LF/CRLF line endings are preserved. Results contain Pi-native `diff`, `patch`, and `firstChangedLine` details. Python mode performs the edit remotely and checks the file hash and metadata again immediately before replacement; a changed file is left untouched and returns `E_REMOTE_FILE_CHANGED`.
125
138
 
126
139
  ## Command
127
140
 
@@ -140,6 +153,7 @@ Connections also close during Pi session shutdown. A later call reconnects on de
140
153
  - Passwords, private-key passphrases, interactive 2FA, and keyboard-interactive authentication are not requested. Fix `ssh <alias>` so it works noninteractively first.
141
154
  - A failed command or write is not automatically replayed after reconnecting.
142
155
  - If a connection disappears before a command returns an exit status, the tool reports that its outcome is unknown.
156
+ - Python is probed when a connection opens. There is no mid-operation fallback: once a helper starts, its failure is returned and the operation is not replayed through SFTP.
143
157
  - There are deliberately no request queues, concurrency limits, file locks, or forced serial writes. Avoid conflicting parallel edits. Concurrent writes to one path can overwrite one another.
144
158
 
145
159
  ## Limitations
@@ -149,7 +163,9 @@ Connections also close during Pi session shutdown. A later call reconnects on de
149
163
  - Remote targets are Linux/Bash systems, not Windows shells.
150
164
  - Remote paths use POSIX `/`. Local Windows is supported. However, when Pi runs on Windows, `remote_read` cannot address a remote POSIX file name containing a literal backslash (`\`), because Pi's native read parser treats it as a path separator. Normal `/` paths and the other remote tools are unaffected.
151
165
  - No interactive terminal, port forwarding, remote Pi worker, or separate search tool. Use `remote_bash` with existing remote tools such as `rg` for search.
152
- - Atomic rename reduces partial-file writes but does not make a disconnected operation's outcome certain and does not prevent races.
166
+ - SFTP compatibility mode retains 0.1.1 behavior, including whole-file network reads and whole-file edit download/upload. Use Python mode for large remote text files.
167
+ - Python edit loads file content into remote memory; read is line-streamed. Atomic rename reduces partial-file writes but cannot eliminate the small check/rename race or make a disconnected operation's outcome certain.
168
+ - Python mode refuses hard-linked files, special mode bits, and metadata it cannot preserve. SFTP mode has the original 0.1.1 metadata and race limitations.
153
169
 
154
170
  ## Development
155
171
 
@@ -160,6 +176,8 @@ npm run check
160
176
 
161
177
  `npm run check` typechecks, builds, and runs unit/integration tests without opening SSH connections.
162
178
 
179
+ Helper integration tests run when `python3` is available. Set `PI_REMOTE_CALL_PYTHON` to select a specific local interpreter; CI provisions Python explicitly. Tests use temporary local files and do not open SSH connections.
180
+
163
181
  Package layout:
164
182
 
165
183
  ```text
@@ -170,6 +188,10 @@ src/transport.ts SSH authentication, host-key verification, Bash channels
170
188
  src/sftp.ts SFTP streams, directories, atomic writes
171
189
  src/file-tools.ts remote POSIX paths, exact edits, native result details
172
190
  src/config.ts allowlist-only configuration
191
+ src/python-files.ts Python result validation and native read formatting
192
+ src/remote_helper.py one-shot remote text read/write/edit helper
193
+ src/remote-helper.ts helper source identity and versioned cache path
194
+ src/python-protocol.ts helper stdout/stderr and JSON response handling
173
195
  ```
174
196
 
175
197
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-remote-call",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Call shell and file tools on SSH hosts from one local Pi, with zero remote installation.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,7 +37,7 @@
37
37
  ]
38
38
  },
39
39
  "scripts": {
40
- "build": "tsc -p tsconfig.json",
40
+ "build": "tsc -p tsconfig.json && node scripts/copy-assets.mjs",
41
41
  "typecheck": "tsc -p tsconfig.json --noEmit",
42
42
  "test": "npm run build && node --test dist/test/*.test.js",
43
43
  "check": "npm run typecheck && npm test",
package/src/errors.ts CHANGED
@@ -8,6 +8,9 @@ export type RemoteCallErrorCode =
8
8
  | "E_AUTH"
9
9
  | "E_CONNECT"
10
10
  | "E_DISCONNECTED"
11
+ | "E_REMOTE_HELPER"
12
+ | "E_REMOTE_FILE_CHANGED"
13
+ | "E_REMOTE_METADATA"
11
14
  | "E_CLOSED";
12
15
 
13
16
  export class RemoteCallError extends Error {
@@ -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 }> {
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 {
@@ -25,6 +25,9 @@ export class HostManager {
25
25
  hostname: connection.facts.hostname,
26
26
  user: connection.facts.user,
27
27
  platform: connection.facts.platform,
28
+ fileMode: connection.facts.fileMode,
29
+ pythonVersion: connection.facts.python?.version,
30
+ ...(connection.facts.helperCache ? { helperCache: connection.facts.helperCache } : {}),
28
31
  }
29
32
  : {}),
30
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
- return `${host.host} — ${host.user}@${host.hostname} (${host.platform}), home: ${host.home}`;
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,170 @@
1
+ import {
2
+ DEFAULT_MAX_BYTES,
3
+ formatSize,
4
+ truncateHead,
5
+ type EditToolDetails,
6
+ type ReadToolDetails,
7
+ type TruncationResult,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import type { ExactEdit } from "./file-tools.ts";
10
+
11
+ export interface PythonFileRequest {
12
+ operation: "read" | "write" | "edit";
13
+ displayPath?: string;
14
+ path: string;
15
+ offset?: number;
16
+ limit?: number;
17
+ content?: string;
18
+ edits?: ExactEdit[];
19
+ }
20
+
21
+ export interface PythonFileExecutor {
22
+ runPythonFileOperation(request: PythonFileRequest, signal?: AbortSignal): Promise<unknown>;
23
+ }
24
+
25
+ interface PythonReadResult {
26
+ content: string;
27
+ totalFileLines: number;
28
+ selectedLines: number;
29
+ selectedBytes: number;
30
+ firstLineBytes: number;
31
+ lastLineEmpty: boolean;
32
+ }
33
+
34
+ function throwIfAborted(signal?: AbortSignal): void {
35
+ if (signal?.aborted) throw new Error("Operation aborted");
36
+ }
37
+
38
+ function record(value: unknown, label: string): Record<string, unknown> {
39
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
40
+ throw new Error(`Invalid Python helper ${label} response`);
41
+ }
42
+ return value as Record<string, unknown>;
43
+ }
44
+
45
+ function numberField(value: Record<string, unknown>, key: string): number {
46
+ const result = value[key];
47
+ if (typeof result !== "number" || !Number.isFinite(result)) throw new Error(`Invalid Python helper number field: ${key}`);
48
+ return result;
49
+ }
50
+
51
+ function stringField(value: Record<string, unknown>, key: string): string {
52
+ const result = value[key];
53
+ if (typeof result !== "string") throw new Error(`Invalid Python helper string field: ${key}`);
54
+ return result;
55
+ }
56
+
57
+ export function supportsPythonReadRange(offset?: number, limit?: number): boolean {
58
+ return (offset === undefined || Number.isInteger(offset))
59
+ && (limit === undefined || (Number.isInteger(limit) && limit >= 0));
60
+ }
61
+
62
+ function readResult(value: unknown): PythonReadResult {
63
+ const result = record(value, "read");
64
+ return {
65
+ content: stringField(result, "content"),
66
+ totalFileLines: numberField(result, "totalFileLines"),
67
+ selectedLines: numberField(result, "selectedLines"),
68
+ selectedBytes: numberField(result, "selectedBytes"),
69
+ firstLineBytes: numberField(result, "firstLineBytes"),
70
+ lastLineEmpty: result.lastLineEmpty === true,
71
+ };
72
+ }
73
+
74
+ function oversizedFirstLineTruncation(): TruncationResult {
75
+ return truncateHead("x".repeat(DEFAULT_MAX_BYTES + 1));
76
+ }
77
+
78
+ export function formatPythonRead(path: string, offset: number | undefined, limit: number | undefined, result: PythonReadResult) {
79
+ const startLine = offset ? Math.max(0, offset - 1) : 0;
80
+ const startLineDisplay = startLine + 1;
81
+ if (startLine >= result.totalFileLines) {
82
+ throw new Error(`Offset ${offset} is beyond end of file (${result.totalFileLines} lines total)`);
83
+ }
84
+
85
+ const baseTruncation = result.firstLineBytes > DEFAULT_MAX_BYTES
86
+ ? oversizedFirstLineTruncation()
87
+ : truncateHead(result.content);
88
+ const truncation: TruncationResult = {
89
+ ...baseTruncation,
90
+ totalLines: result.selectedBytes === 0 ? 0 : result.selectedLines - (result.lastLineEmpty ? 1 : 0),
91
+ totalBytes: result.selectedBytes,
92
+ };
93
+ const userLimitedLines = limit === undefined
94
+ ? undefined
95
+ : Math.min(startLine + limit, result.totalFileLines) - startLine;
96
+ let outputText: string;
97
+ let details: ReadToolDetails | undefined;
98
+
99
+ if (truncation.firstLineExceedsLimit) {
100
+ outputText = `[Line ${startLineDisplay} is ${formatSize(result.firstLineBytes)}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;
101
+ details = { truncation };
102
+ } else if (truncation.truncated) {
103
+ const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
104
+ const nextOffset = endLineDisplay + 1;
105
+ outputText = truncation.content;
106
+ if (truncation.truncatedBy === "lines") {
107
+ outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${result.totalFileLines}. Use offset=${nextOffset} to continue.]`;
108
+ } else {
109
+ outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${result.totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;
110
+ }
111
+ details = { truncation };
112
+ } else if (userLimitedLines !== undefined && startLine + userLimitedLines < result.totalFileLines) {
113
+ const remaining = result.totalFileLines - (startLine + userLimitedLines);
114
+ const nextOffset = startLine + userLimitedLines + 1;
115
+ outputText = `${truncation.content}\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;
116
+ } else {
117
+ outputText = truncation.content;
118
+ }
119
+
120
+ return {
121
+ content: [{ type: "text" as const, text: outputText }],
122
+ details,
123
+ structuredContent: outputText,
124
+ };
125
+ }
126
+
127
+ export async function pythonReadFile(
128
+ executor: PythonFileExecutor,
129
+ path: string,
130
+ offset: number | undefined,
131
+ limit: number | undefined,
132
+ signal?: AbortSignal,
133
+ ) {
134
+ throwIfAborted(signal);
135
+ const response = await executor.runPythonFileOperation({ operation: "read", path, offset, limit }, signal);
136
+ throwIfAborted(signal);
137
+ return formatPythonRead(path, offset, limit, readResult(response));
138
+ }
139
+
140
+ export async function pythonWriteFile(
141
+ executor: PythonFileExecutor,
142
+ path: string,
143
+ content: string,
144
+ signal?: AbortSignal,
145
+ displayPath = path,
146
+ ) {
147
+ throwIfAborted(signal);
148
+ await executor.runPythonFileOperation({ operation: "write", path, content }, signal);
149
+ throwIfAborted(signal);
150
+ return { content: [{ type: "text" as const, text: `Successfully wrote to ${displayPath}` }], details: undefined };
151
+ }
152
+
153
+ export async function pythonEditFile(
154
+ executor: PythonFileExecutor,
155
+ path: string,
156
+ edits: ExactEdit[],
157
+ signal?: AbortSignal,
158
+ displayPath = path,
159
+ ) {
160
+ if (edits.length === 0) throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");
161
+ throwIfAborted(signal);
162
+ const response = record(await executor.runPythonFileOperation({ operation: "edit", path, displayPath, edits }, signal), "edit");
163
+ throwIfAborted(signal);
164
+ const details = record(response.details, "edit details") as unknown as EditToolDetails;
165
+ return {
166
+ content: [{ type: "text" as const, text: `Successfully replaced ${edits.length} block(s) in ${displayPath}.` }],
167
+ details,
168
+ };
169
+ }
170
+
@@ -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
+ }
@@ -0,0 +1,12 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { posix } from "node:path";
4
+
5
+ export const PYTHON_HELPER_PROTOCOL = 1;
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
+ }
@@ -0,0 +1,428 @@
1
+ #!/usr/bin/env python3
2
+ """One-shot file helper for pi-remote-call. Standard library only."""
3
+
4
+ import difflib
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import stat
10
+ import sys
11
+ import tempfile
12
+
13
+ MAX_LINES = 2000
14
+ MAX_BYTES = 50 * 1024
15
+
16
+
17
+ class HelperError(Exception):
18
+ def __init__(self, code, message):
19
+ super().__init__(message)
20
+ self.code = code
21
+ self.message = message
22
+
23
+
24
+ def normalize_to_lf(text):
25
+ return text.replace("\r\n", "\n").replace("\r", "\n")
26
+
27
+
28
+ def apply_exact_edits(content, edits, path):
29
+ replacements = []
30
+ for edit_index, edit in enumerate(edits):
31
+ old_text = normalize_to_lf(edit["oldText"])
32
+ new_text = normalize_to_lf(edit["newText"])
33
+ if not old_text:
34
+ raise HelperError("E_EDIT", "edits[%d].oldText must not be empty in %s" % (edit_index, path))
35
+ match_index = content.find(old_text)
36
+ if match_index < 0:
37
+ raise HelperError(
38
+ "E_EDIT",
39
+ "Could not find edits[%d].oldText in %s. Match the original file exactly." % (edit_index, path),
40
+ )
41
+ second = content.find(old_text, match_index + 1)
42
+ if second >= 0:
43
+ raise HelperError(
44
+ "E_EDIT",
45
+ "edits[%d].oldText is not unique in %s; found at least two matches." % (edit_index, path),
46
+ )
47
+ replacements.append(
48
+ {
49
+ "editIndex": edit_index,
50
+ "matchIndex": match_index,
51
+ "matchLength": len(old_text),
52
+ "newText": new_text,
53
+ }
54
+ )
55
+
56
+ replacements.sort(key=lambda item: item["matchIndex"])
57
+ for index in range(1, len(replacements)):
58
+ previous = replacements[index - 1]
59
+ current = replacements[index]
60
+ if previous["matchIndex"] + previous["matchLength"] > current["matchIndex"]:
61
+ raise HelperError(
62
+ "E_EDIT",
63
+ "edits[%d] and edits[%d] overlap in %s. Merge them into one edit."
64
+ % (previous["editIndex"], current["editIndex"], path),
65
+ )
66
+
67
+ result = content
68
+ for replacement in reversed(replacements):
69
+ start = replacement["matchIndex"]
70
+ result = result[:start] + replacement["newText"] + result[start + replacement["matchLength"]:]
71
+ if result == content:
72
+ raise HelperError("E_EDIT", "No changes would be made to %s." % path)
73
+ return content, result, replacements
74
+
75
+
76
+ def line_ending_at(content, offset):
77
+ line_feed = content.find("\n", offset)
78
+ if line_feed == -1:
79
+ line_feed = content.rfind("\n", 0, offset)
80
+ if line_feed == -1:
81
+ return "\r" if "\r" in content else "\n"
82
+ return "\r\n" if line_feed > 0 and content[line_feed - 1] == "\r" else "\n"
83
+
84
+
85
+ def original_offset(content, normalized_offset):
86
+ original = 0
87
+ normalized = 0
88
+ while normalized < normalized_offset and original < len(content):
89
+ if content.startswith("\r\n", original):
90
+ original += 2
91
+ else:
92
+ original += 1
93
+ normalized += 1
94
+ return original
95
+
96
+
97
+ def apply_replacements_to_original(original, replacements):
98
+ parts = []
99
+ position = 0
100
+ for replacement in replacements:
101
+ start = original_offset(original, replacement["matchIndex"])
102
+ end = original_offset(original, replacement["matchIndex"] + replacement["matchLength"])
103
+ parts.append(original[position:start])
104
+ ending = line_ending_at(original, start)
105
+ new_text = replacement["newText"]
106
+ parts.append(new_text if ending == "\n" else new_text.replace("\n", ending))
107
+ position = end
108
+ parts.append(original[position:])
109
+ return "".join(parts)
110
+
111
+
112
+ def line_count(text):
113
+ return text.count("\n") + 1
114
+
115
+
116
+ def generate_edit_details(path, old_content, new_content):
117
+ diff_lines = list(
118
+ difflib.unified_diff(
119
+ old_content.splitlines(),
120
+ new_content.splitlines(),
121
+ fromfile=path,
122
+ tofile=path,
123
+ n=4,
124
+ lineterm="",
125
+ )
126
+ )
127
+ patch = "\n".join(diff_lines) + "\n"
128
+ width = len(str(max(line_count(old_content), line_count(new_content))))
129
+ output = []
130
+ first_changed_line = None
131
+ old_line = 0
132
+ new_line = 0
133
+ in_hunk = False
134
+
135
+ for line in diff_lines:
136
+ if line.startswith("@@"):
137
+ match = re.match(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
138
+ if not match:
139
+ raise HelperError("E_REMOTE_HELPER", "Could not parse generated diff hunk")
140
+ if in_hunk:
141
+ output.append(" %s ..." % (" " * width))
142
+ old_line = max(1, int(match.group(1)))
143
+ new_line = max(1, int(match.group(2)))
144
+ in_hunk = True
145
+ continue
146
+ if not in_hunk or not line:
147
+ continue
148
+ marker = line[0]
149
+ text = line[1:]
150
+ if marker in "+-" and first_changed_line is None:
151
+ first_changed_line = new_line
152
+ if marker == "+":
153
+ output.append("+%s %s" % (str(new_line).rjust(width), text))
154
+ new_line += 1
155
+ elif marker == "-":
156
+ output.append("-%s %s" % (str(old_line).rjust(width), text))
157
+ old_line += 1
158
+ elif marker == " ":
159
+ output.append(" %s %s" % (str(old_line).rjust(width), text))
160
+ old_line += 1
161
+ new_line += 1
162
+
163
+ details = {"diff": "\n".join(output), "patch": patch}
164
+ if first_changed_line is not None:
165
+ details["firstChangedLine"] = first_changed_line
166
+ return details
167
+
168
+
169
+ def utf8_prefix(text, byte_limit):
170
+ return text.encode("utf-8")[:byte_limit].decode("utf-8", "replace")
171
+
172
+
173
+ def read_operation(request):
174
+ path = request["path"]
175
+ offset = request.get("offset")
176
+ limit = request.get("limit")
177
+ start = max(0, offset - 1) if offset is not None else 0
178
+ end = start + limit if limit is not None else None
179
+
180
+ selected_lines = 0
181
+ selected_bytes = 0
182
+ first_line_bytes = 0
183
+ last_line_empty = True
184
+ stored_lines = []
185
+ stored_bytes = 0
186
+ storing = True
187
+ actual_lines = 0
188
+ last_had_newline = False
189
+
190
+ def consider(line_number, text):
191
+ nonlocal selected_lines, selected_bytes, first_line_bytes, last_line_empty
192
+ nonlocal stored_bytes, storing
193
+ index = line_number - 1
194
+ if index < start or (end is not None and index >= end):
195
+ return
196
+
197
+ selected_lines += 1
198
+ encoded = text.encode("utf-8")
199
+ line_bytes = len(encoded)
200
+ if selected_lines > 1:
201
+ selected_bytes += 1
202
+ selected_bytes += line_bytes
203
+ if selected_lines == 1:
204
+ first_line_bytes = line_bytes
205
+ last_line_empty = len(text) == 0
206
+
207
+ if not storing:
208
+ return
209
+ if selected_lines == 1 and line_bytes > MAX_BYTES:
210
+ storing = False
211
+ return
212
+ if len(stored_lines) >= MAX_LINES + 1:
213
+ storing = False
214
+ return
215
+
216
+ separator = 1 if stored_lines else 0
217
+ available = MAX_BYTES - stored_bytes - separator
218
+ if line_bytes <= available:
219
+ stored_lines.append(text)
220
+ stored_bytes += separator + line_bytes
221
+ if len(stored_lines) > MAX_LINES:
222
+ storing = False
223
+ return
224
+
225
+ needed = max(0, available) + 1
226
+ prefix = utf8_prefix(text, needed)
227
+ stored_lines.append(prefix)
228
+ stored_bytes += separator + len(prefix.encode("utf-8"))
229
+ storing = False
230
+
231
+ with open(path, "rb") as source:
232
+ for raw in source:
233
+ actual_lines += 1
234
+ last_had_newline = raw.endswith(b"\n")
235
+ if last_had_newline:
236
+ raw = raw[:-1]
237
+ consider(actual_lines, raw.decode("utf-8", "replace"))
238
+
239
+ total_file_lines = actual_lines
240
+ if actual_lines == 0 or last_had_newline:
241
+ total_file_lines += 1
242
+ consider(total_file_lines, "")
243
+
244
+ return {
245
+ "content": "\n".join(stored_lines),
246
+ "totalFileLines": total_file_lines,
247
+ "selectedLines": selected_lines,
248
+ "selectedBytes": selected_bytes,
249
+ "firstLineBytes": first_line_bytes,
250
+ "lastLineEmpty": last_line_empty,
251
+ }
252
+
253
+
254
+ def resolve_target(path):
255
+ return os.path.realpath(path) if os.path.islink(path) else path
256
+
257
+
258
+ def stat_signature(value):
259
+ return (
260
+ value.st_dev,
261
+ value.st_ino,
262
+ stat.S_IMODE(value.st_mode),
263
+ value.st_uid,
264
+ value.st_gid,
265
+ value.st_nlink,
266
+ value.st_size,
267
+ value.st_mtime_ns,
268
+ )
269
+
270
+
271
+ def validate_existing_file(path, value):
272
+ if not stat.S_ISREG(value.st_mode):
273
+ raise HelperError("E_REMOTE_METADATA", "Refusing to replace a non-regular file: %s" % path)
274
+ if value.st_nlink > 1:
275
+ raise HelperError(
276
+ "E_REMOTE_METADATA",
277
+ "Refusing atomic replacement of a hard-linked file: %s. Its other links would retain old content." % path,
278
+ )
279
+ if stat.S_IMODE(value.st_mode) & 0o7000:
280
+ raise HelperError(
281
+ "E_REMOTE_METADATA",
282
+ "Refusing to replace a file with setuid/setgid/sticky mode bits: %s" % path,
283
+ )
284
+
285
+
286
+ def hash_file(path):
287
+ digest = hashlib.sha256()
288
+ with open(path, "rb") as source:
289
+ while True:
290
+ chunk = source.read(1024 * 1024)
291
+ if not chunk:
292
+ break
293
+ digest.update(chunk)
294
+ return digest.hexdigest()
295
+
296
+
297
+ def copy_xattrs(source, destination):
298
+ if not hasattr(os, "listxattr"):
299
+ return
300
+ for name in os.listxattr(source):
301
+ value = os.getxattr(source, name)
302
+ try:
303
+ os.setxattr(destination, name, value)
304
+ except OSError as error:
305
+ raise HelperError(
306
+ "E_REMOTE_METADATA",
307
+ "Could not preserve extended attribute %s on %s: %s" % (name, source, error),
308
+ )
309
+
310
+
311
+ def atomic_write(path, data, expected_hash=None, expected_stat=None):
312
+ parent = os.path.dirname(path) or "."
313
+ os.makedirs(parent, exist_ok=True)
314
+ exists = os.path.exists(path)
315
+ original_stat = os.stat(path) if exists else None
316
+ if original_stat is not None:
317
+ validate_existing_file(path, original_stat)
318
+
319
+ descriptor = None
320
+ temporary = None
321
+ try:
322
+ descriptor, temporary = tempfile.mkstemp(prefix=".pi-remote-call-", dir=parent)
323
+ with os.fdopen(descriptor, "wb") as output:
324
+ descriptor = None
325
+ if original_stat is not None:
326
+ current = os.fstat(output.fileno())
327
+ if current.st_uid != original_stat.st_uid or current.st_gid != original_stat.st_gid:
328
+ try:
329
+ os.fchown(output.fileno(), original_stat.st_uid, original_stat.st_gid)
330
+ except OSError as error:
331
+ raise HelperError(
332
+ "E_REMOTE_METADATA",
333
+ "Could not preserve owner/group for %s: %s" % (path, error),
334
+ )
335
+ os.chmod(temporary, stat.S_IMODE(original_stat.st_mode))
336
+ output.write(data)
337
+ output.flush()
338
+ if original_stat is not None:
339
+ copy_xattrs(path, temporary)
340
+ os.fsync(output.fileno())
341
+
342
+ if expected_hash is not None:
343
+ if os.path.islink(path):
344
+ raise HelperError("E_REMOTE_FILE_CHANGED", "The file changed into a symbolic link during editing: %s" % path)
345
+ current_stat = os.stat(path)
346
+ validate_existing_file(path, current_stat)
347
+ if expected_stat is not None and stat_signature(current_stat) != stat_signature(expected_stat):
348
+ raise HelperError(
349
+ "E_REMOTE_FILE_CHANGED",
350
+ "The file changed after it was read: %s. No changes were written; read it again and retry." % path,
351
+ )
352
+ if hash_file(path) != expected_hash:
353
+ raise HelperError(
354
+ "E_REMOTE_FILE_CHANGED",
355
+ "The file changed after it was read: %s. No changes were written; read it again and retry." % path,
356
+ )
357
+
358
+ os.replace(temporary, path)
359
+ temporary = None
360
+ finally:
361
+ if descriptor is not None:
362
+ os.close(descriptor)
363
+ if temporary is not None:
364
+ try:
365
+ os.unlink(temporary)
366
+ except OSError:
367
+ pass
368
+
369
+
370
+ def write_operation(request):
371
+ path = resolve_target(request["path"])
372
+ atomic_write(path, request["content"].encode("utf-8"))
373
+ return {"path": path}
374
+
375
+
376
+ def edit_operation(request):
377
+ path = resolve_target(request["path"])
378
+ original_stat = os.stat(path)
379
+ validate_existing_file(path, original_stat)
380
+ with open(path, "rb") as source:
381
+ raw = source.read()
382
+
383
+ original_hash = hashlib.sha256(raw).hexdigest()
384
+ text = raw.decode("utf-8", "replace")
385
+ bom = "\ufeff" if text.startswith("\ufeff") else ""
386
+ original = text[1:] if bom else text
387
+ display_path = request.get("displayPath", request["path"])
388
+ base_content, new_content, replacements = apply_exact_edits(normalize_to_lf(original), request["edits"], display_path)
389
+ details = generate_edit_details(display_path, base_content, new_content)
390
+ final_content = bom + (new_content if original == base_content else apply_replacements_to_original(original, replacements))
391
+ atomic_write(path, final_content.encode("utf-8"), original_hash, original_stat)
392
+ return {"details": details}
393
+
394
+
395
+ def handle(request):
396
+ operation = request.get("operation")
397
+ if operation == "read":
398
+ return read_operation(request)
399
+ if operation == "write":
400
+ return write_operation(request)
401
+ if operation == "edit":
402
+ return edit_operation(request)
403
+ raise HelperError("E_REMOTE_HELPER", "Unknown helper operation: %s" % operation)
404
+
405
+
406
+ def main():
407
+ try:
408
+ with open(sys.argv[1], "r", encoding="utf-8") as request_file:
409
+ request = json.load(request_file)
410
+ result = handle(request)
411
+ response = {"ok": True, "result": result}
412
+ status = 0
413
+ except HelperError as error:
414
+ response = {"ok": False, "error": {"code": error.code, "message": error.message}}
415
+ status = 1
416
+ except Exception as error:
417
+ response = {
418
+ "ok": False,
419
+ "error": {"code": "E_REMOTE_HELPER", "message": "%s: %s" % (type(error).__name__, error)},
420
+ }
421
+ status = 1
422
+ sys.stdout.write(json.dumps(response, ensure_ascii=True, separators=(",", ":")))
423
+ sys.stdout.write("\n")
424
+ return status
425
+
426
+
427
+ if __name__ == "__main__":
428
+ sys.exit(main())
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
- export async function sftpWriteFileAtomic(sftp: SFTPWrapper, path: string, content: string): Promise<void> {
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(expandHome);
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(expandHome);
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/tools.ts CHANGED
@@ -7,6 +7,8 @@ import {
7
7
  import { Type } from "typebox";
8
8
  import { editRemoteFile, remoteReadOperations, writeRemoteFile } from "./file-tools.ts";
9
9
  import type { HostManager } from "./host-manager.ts";
10
+ import { pythonEditFile, pythonReadFile, pythonWriteFile, supportsPythonReadRange } from "./python-files.ts";
11
+ import { detectImageMimeType } from "./sftp.ts";
10
12
  import { resolveRemotePath } from "./remote-path.ts";
11
13
 
12
14
  const namespace = {
@@ -107,6 +109,9 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
107
109
  async execute(id, { host, path, cwd, offset, limit }, signal, onUpdate) {
108
110
  const connection = await manager.get(host);
109
111
  const absolutePath = resolveRemotePath(connection.facts.home, path, cwd ?? "~");
112
+ if (connection.facts.fileMode === "python" && !detectImageMimeType(absolutePath) && supportsPythonReadRange(offset, limit)) {
113
+ return pythonReadFile(connection, absolutePath, offset, limit, signal);
114
+ }
110
115
  const tool = createReadTool("/", { operations: remoteReadOperations(connection.readOperations()) });
111
116
  return tool.execute(id, { path: absolutePath, offset, limit }, signal, onUpdate);
112
117
  },
@@ -115,7 +120,7 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
115
120
  pi.registerTool(defineTool({
116
121
  name: "remote_write",
117
122
  label: "Remote Write",
118
- description: "Create or completely overwrite a file on an allowlisted SSH host through SFTP. Parent directories are created automatically",
123
+ description: "Create or completely overwrite a file on an allowlisted SSH host. Parent directories are created automatically; writes use a Python fast path when available and SFTP otherwise",
119
124
  promptSnippet: "Create or overwrite files on a configured remote SSH host",
120
125
  promptGuidelines: ["Use remote_write only for new remote files or complete rewrites; use remote_edit for targeted changes."],
121
126
  parameters: Type.Object({
@@ -128,6 +133,10 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
128
133
  annotations: { destructiveHint: true, openWorldHint: true },
129
134
  async execute(id, { host, path, content, cwd }, signal, onUpdate) {
130
135
  const connection = await manager.get(host);
136
+ const absolutePath = resolveRemotePath(connection.facts.home, path, cwd ?? "~");
137
+ if (connection.facts.fileMode === "python") {
138
+ return pythonWriteFile(connection, absolutePath, content, signal, path);
139
+ }
131
140
  return writeRemoteFile(connection.facts.home, cwd ?? "~", path, content, connection.writeOperations(), signal);
132
141
  },
133
142
  }));
@@ -154,6 +163,10 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
154
163
  annotations: { destructiveHint: true, openWorldHint: true },
155
164
  async execute(id, { host, path, cwd, edits }, signal, onUpdate) {
156
165
  const connection = await manager.get(host);
166
+ const absolutePath = resolveRemotePath(connection.facts.home, path, cwd ?? "~");
167
+ if (connection.facts.fileMode === "python") {
168
+ return pythonEditFile(connection, absolutePath, edits, signal, path);
169
+ }
157
170
  return editRemoteFile(connection.facts.home, cwd ?? "~", path, edits, connection.editOperations(), signal);
158
171
  },
159
172
  }));
package/src/transport.ts CHANGED
@@ -1,8 +1,13 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import { readFile } from "node:fs/promises";
3
+ import { posix } from "node:path";
2
4
  import { Client, type ClientChannel, type ConnectConfig, type SFTPWrapper } from "ssh2";
3
5
  import type { BashOperations, EditOperations, ReadOperations, WriteOperations } from "@earendil-works/pi-coding-agent";
4
6
  import { asRemoteCallError, RemoteCallError } from "./errors.ts";
5
7
  import { loadKnownHostEntries, verifyKnownHostKey, type KnownHostEntry } from "./host-key.ts";
8
+ import type { PythonFileRequest } from "./python-files.ts";
9
+ import { PYTHON_HELPER_BYTES, PYTHON_HELPER_SHA256, PYTHON_HELPER_SOURCE, pythonHelperCachePath } from "./remote-helper.ts";
10
+ import { parsePythonHelperResponse } from "./python-protocol.ts";
6
11
  import { remoteCommandScript, shellQuote } from "./remote-path.ts";
7
12
  import { resolveSshConfig, type EffectiveSshConfig } from "./ssh-config.ts";
8
13
  import {
@@ -11,6 +16,9 @@ import {
11
16
  sftpMkdirP,
12
17
  sftpReadFile,
13
18
  sftpRealpath,
19
+ sftpLstat,
20
+ sftpSetStat,
21
+ sftpUnlink,
14
22
  sftpWriteFileAtomic,
15
23
  } from "./sftp.ts";
16
24
 
@@ -20,6 +28,9 @@ export interface RemoteHostFacts {
20
28
  hostname: string;
21
29
  user: string;
22
30
  platform: string;
31
+ fileMode: "python" | "sftp";
32
+ python?: { path: string; version: string };
33
+ helperCache?: "hit" | "installed" | "inline";
23
34
  }
24
35
 
25
36
  type AuthAttempt =
@@ -50,22 +61,40 @@ async function openChannel(client: Client, command: string): Promise<ClientChann
50
61
  return new Promise((resolve, reject) => client.exec(command, (error, channel) => (error ? reject(error) : resolve(channel))));
51
62
  }
52
63
 
64
+ export function hostProbeScript(): string {
65
+ return `python_path=
66
+ python_version=
67
+ if python_path=$(command -v python3 2>/dev/null); then
68
+ if ! python_version=$("$python_path" -c 'import sys; print(".".join(map(str, sys.version_info[:3]))) if sys.version_info >= (3, 8) else sys.exit(1)' 2>/dev/null); then
69
+ python_path=
70
+ python_version=
71
+ fi
72
+ fi
73
+ printf '%s\\n' "$(hostname)" "$(id -un)" "$(uname -s)" "$python_path" "$python_version"
74
+ `;
75
+ }
76
+
77
+ export function parseHostProbe(alias: string, home: string, output: string, exitCode: number | null): RemoteHostFacts {
78
+ const [hostname = "", user = "", platform = "", pythonPath = "", pythonVersion = ""] = output.trimEnd().split(/\r?\n/);
79
+ if (exitCode !== 0 || !hostname || !user) {
80
+ throw new RemoteCallError("E_CONNECT", `Connected to ${alias}, but the Bash probe failed`, "Ensure bash, hostname, id, and uname are available remotely");
81
+ }
82
+ const python = pythonPath && pythonVersion ? { path: pythonPath, version: pythonVersion } : undefined;
83
+ return { alias, home, hostname, user, platform, fileMode: python ? "python" : "sftp", ...(python ? { python } : {}) };
84
+ }
85
+
53
86
  async function probeHost(client: Client, alias: string, home: string): Promise<RemoteHostFacts> {
54
87
  const channel = await openChannel(client, "bash -s");
55
88
  let output = "";
56
89
  channel.stdout.on("data", (data: Buffer) => (output += data.toString("utf8")));
57
- channel.end("printf '%s\\n' \"$(hostname)\" \"$(id -un)\" \"$(uname -s)\"\n");
90
+ channel.end(hostProbeScript());
58
91
  const exitCode = await new Promise<number | null>((resolve, reject) => {
59
92
  let code: number | null = null;
60
93
  channel.on("exit", (value: number | null) => (code = value));
61
94
  channel.once("error", reject);
62
95
  channel.once("close", () => resolve(code));
63
96
  });
64
- const [hostname = "", user = "", platform = ""] = output.trimEnd().split(/\r?\n/);
65
- if (exitCode !== 0 || !hostname || !user) {
66
- throw new RemoteCallError("E_CONNECT", `Connected to ${alias}, but the Bash probe failed`, "Ensure bash, hostname, id, and uname are available remotely");
67
- }
68
- return { alias, home, hostname, user, platform };
97
+ return parseHostProbe(alias, home, output, exitCode);
69
98
  }
70
99
 
71
100
  async function connectWithAttempt(
@@ -131,6 +160,7 @@ export class SshConnection {
131
160
  readonly facts: RemoteHostFacts;
132
161
  onClose?: () => void;
133
162
  private closed = false;
163
+ private helperReady?: Promise<string | undefined>;
134
164
 
135
165
  private constructor(
136
166
  readonly client: Client,
@@ -230,7 +260,7 @@ export class SshConnection {
230
260
  private async exec(
231
261
  command: string,
232
262
  cwd: string,
233
- options: { onData: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
263
+ options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
234
264
  ): Promise<{ exitCode: number | null }> {
235
265
  if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
236
266
  if (options.signal?.aborted) throw new Error("Operation aborted");
@@ -255,7 +285,7 @@ export class SshConnection {
255
285
  options.signal?.addEventListener("abort", onAbort, { once: true });
256
286
  if (options.signal?.aborted) onAbort();
257
287
  channel.stdout.on("data", options.onData);
258
- channel.stderr.on("data", options.onData);
288
+ channel.stderr.on("data", options.onStderr ?? options.onData);
259
289
  channel.on("exit", (code: number | null) => {
260
290
  exitSeen = true;
261
291
  exitCode = typeof code === "number" ? code : null;
@@ -283,6 +313,80 @@ export class SshConnection {
283
313
  });
284
314
  }
285
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
+
359
+ async runPythonFileOperation(request: PythonFileRequest, signal?: AbortSignal): Promise<unknown> {
360
+ const python = this.facts.python;
361
+ if (!python) throw new RemoteCallError("E_REMOTE_HELPER", `Python 3 is not available for ${this.facts.alias}`);
362
+ if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
363
+ if (signal?.aborted) throw new Error("Operation aborted");
364
+ const helperPath = await this.preparePythonHelper();
365
+ const requestPath = posix.join("/tmp", `pi-remote-call-${process.pid}-${randomBytes(12).toString("hex")}.json`);
366
+ try {
367
+ await sftpWriteFileAtomic(this.sftp, requestPath, JSON.stringify(request));
368
+ if (signal?.aborted) throw new Error("Operation aborted");
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)}`;
374
+ const { exitCode } = await this.exec(command, this.facts.home, {
375
+ onData: (data) => stdoutChunks.push(Buffer.from(data)),
376
+ onStderr: (data) => stderrChunks.push(Buffer.from(data)),
377
+ signal,
378
+ });
379
+ return parsePythonHelperResponse(
380
+ this.facts.alias,
381
+ Buffer.concat(stdoutChunks).toString("utf8"),
382
+ Buffer.concat(stderrChunks).toString("utf8"),
383
+ exitCode,
384
+ );
385
+ } finally {
386
+ await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
387
+ }
388
+ }
389
+
286
390
  close(): void {
287
391
  if (this.closed) return;
288
392
  this.closed = true;