pi-remote-call 0.1.0 → 0.2.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 +20 -0
- package/README.md +26 -7
- package/package.json +2 -2
- package/src/errors.ts +3 -0
- package/src/host-manager.ts +3 -1
- package/src/index.ts +1 -1
- package/src/python-files.ts +170 -0
- package/src/remote-helper.ts +3 -0
- package/src/remote_helper.py +428 -0
- package/src/tools.ts +32 -11
- package/src/transport.ts +73 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0 - 2026-11-28
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Optional Python 3 fast path for remote-side text pagination, complete writes, and exact edits with native result formatting.
|
|
8
|
+
- Per-connection `fileMode` reporting and explicit Python/SFTP routing tests.
|
|
9
|
+
- Remote edit conflict detection, symbolic-link handling, ordinary metadata preservation, and safe rejection of unsupported replacements.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Hosts without Python retain the 0.1.1 SFTP implementation. Python failures after an operation starts are never replayed through SFTP.
|
|
14
|
+
- CI now provisions Python so helper contract tests run on Ubuntu, Windows, and macOS.
|
|
15
|
+
|
|
16
|
+
## 0.1.1 - 2026-11-28
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Clarified namespace, tool, and parameter instructions, including non-interactive Bash and exact multi-edit semantics.
|
|
21
|
+
- Clarified local Windows support and narrowed the documented path limitation to literal backslashes in remote file names read by `remote_read`.
|
|
22
|
+
|
|
3
23
|
## 0.1.0 - 2026-11-28
|
|
4
24
|
|
|
5
25
|
### Added
|
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.
|
|
28
|
+
pi install npm:pi-remote-call@0.2.0
|
|
27
29
|
```
|
|
28
30
|
|
|
29
31
|
### GitHub
|
|
30
32
|
|
|
31
33
|
```sh
|
|
32
|
-
pi install git:github.com/therainisme/pi-remote-call@v0.
|
|
34
|
+
pi install git:github.com/therainisme/pi-remote-call@v0.2.0
|
|
33
35
|
```
|
|
34
36
|
|
|
35
37
|
### Local directory
|
|
@@ -53,6 +55,15 @@ 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 or a permanent remote installation. Fallback is selected before an operation starts: a Python operation that fails is never replayed through SFTP.
|
|
66
|
+
|
|
56
67
|
## Tools
|
|
57
68
|
|
|
58
69
|
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 +106,7 @@ Every execution tool requires `host`. There is no global current host, so calls
|
|
|
95
106
|
|
|
96
107
|
The example reads `~/notes/todo.md`. An optional `cwd` changes the base for relative paths. Absolute paths and `~/...` ignore `cwd`.
|
|
97
108
|
|
|
98
|
-
Text pagination and head truncation
|
|
109
|
+
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
110
|
|
|
100
111
|
### `remote_write`
|
|
101
112
|
|
|
@@ -107,7 +118,7 @@ Text pagination and head truncation use Pi's native read implementation. Support
|
|
|
107
118
|
}
|
|
108
119
|
```
|
|
109
120
|
|
|
110
|
-
Creates parent directories
|
|
121
|
+
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
122
|
|
|
112
123
|
### `remote_edit`
|
|
113
124
|
|
|
@@ -121,7 +132,7 @@ Creates parent directories, then writes through a same-directory temporary SFTP
|
|
|
121
132
|
}
|
|
122
133
|
```
|
|
123
134
|
|
|
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.
|
|
135
|
+
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
136
|
|
|
126
137
|
## Command
|
|
127
138
|
|
|
@@ -140,6 +151,7 @@ Connections also close during Pi session shutdown. A later call reconnects on de
|
|
|
140
151
|
- Passwords, private-key passphrases, interactive 2FA, and keyboard-interactive authentication are not requested. Fix `ssh <alias>` so it works noninteractively first.
|
|
141
152
|
- A failed command or write is not automatically replayed after reconnecting.
|
|
142
153
|
- If a connection disappears before a command returns an exit status, the tool reports that its outcome is unknown.
|
|
154
|
+
- 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
155
|
- 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
156
|
|
|
145
157
|
## Limitations
|
|
@@ -147,9 +159,11 @@ Connections also close during Pi session shutdown. A later call reconnects on de
|
|
|
147
159
|
- Direct SSH aliases only. `ProxyJump` and `ProxyCommand` return an explicit unsupported-option error.
|
|
148
160
|
- Standard `known_hosts` public keys are supported; CA-based `@cert-authority` trust is not implemented.
|
|
149
161
|
- Remote targets are Linux/Bash systems, not Windows shells.
|
|
150
|
-
- Remote paths use POSIX `/`.
|
|
162
|
+
- 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
163
|
- 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
|
-
-
|
|
164
|
+
- 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.
|
|
165
|
+
- 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.
|
|
166
|
+
- 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
167
|
|
|
154
168
|
## Development
|
|
155
169
|
|
|
@@ -160,6 +174,8 @@ npm run check
|
|
|
160
174
|
|
|
161
175
|
`npm run check` typechecks, builds, and runs unit/integration tests without opening SSH connections.
|
|
162
176
|
|
|
177
|
+
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.
|
|
178
|
+
|
|
163
179
|
Package layout:
|
|
164
180
|
|
|
165
181
|
```text
|
|
@@ -170,6 +186,9 @@ src/transport.ts SSH authentication, host-key verification, Bash channels
|
|
|
170
186
|
src/sftp.ts SFTP streams, directories, atomic writes
|
|
171
187
|
src/file-tools.ts remote POSIX paths, exact edits, native result details
|
|
172
188
|
src/config.ts allowlist-only configuration
|
|
189
|
+
src/python-files.ts Python result validation and native read formatting
|
|
190
|
+
src/remote_helper.py one-shot remote text read/write/edit helper
|
|
191
|
+
src/remote-helper.ts loads the bundled Python helper source
|
|
173
192
|
```
|
|
174
193
|
|
|
175
194
|
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-remote-call",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.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
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 }> {
|
|
16
|
+
list(): Array<{ host: string; connected: boolean; home?: string; hostname?: string; user?: string; platform?: string; fileMode?: "python" | "sftp"; pythonVersion?: string }> {
|
|
17
17
|
return this.config.hosts.map((host) => {
|
|
18
18
|
const connection = this.entries.get(host)?.connection;
|
|
19
19
|
return {
|
|
@@ -25,6 +25,8 @@ 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,
|
|
28
30
|
}
|
|
29
31
|
: {}),
|
|
30
32
|
};
|
package/src/index.ts
CHANGED
|
@@ -12,7 +12,7 @@ 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
|
+
return `${host.host} — ${host.user}@${host.hostname} (${host.platform}, ${host.fileMode}), home: ${host.home}`;
|
|
16
16
|
}).join("\n");
|
|
17
17
|
}
|
|
18
18
|
|
|
@@ -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,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/tools.ts
CHANGED
|
@@ -7,13 +7,16 @@ 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 = {
|
|
13
15
|
name: "remote-call",
|
|
14
16
|
aliases: ["remote_call"],
|
|
15
17
|
description: "Shell and file tools on configured SSH hosts; no remote Pi or agent is installed.",
|
|
16
|
-
instructions:
|
|
18
|
+
instructions:
|
|
19
|
+
"remote_bash, remote_read, remote_write, and remote_edit require host. remote_hosts requires host only when action=diagnose. host must exactly match an entry in the configured hosts[] SSH alias allowlist. cwd defaults to the remote user's home directory.",
|
|
17
20
|
};
|
|
18
21
|
|
|
19
22
|
function textResult(text: string, details: unknown) {
|
|
@@ -21,7 +24,7 @@ function textResult(text: string, details: unknown) {
|
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): void {
|
|
24
|
-
const hostSchema = Type.Unsafe<string>({ type: "string", enum: manager.config.hosts, description: "
|
|
27
|
+
const hostSchema = Type.Unsafe<string>({ type: "string", enum: manager.config.hosts, description: "SSH alias from the configured hosts[] allowlist" });
|
|
25
28
|
const cwdSchema = Type.Optional(Type.String({ description: "Remote working directory; defaults to ~" }));
|
|
26
29
|
const bashOutputSchema = createBashTool(process.cwd()).outputSchema;
|
|
27
30
|
const readOutputSchema = createReadTool(process.cwd()).outputSchema;
|
|
@@ -29,11 +32,15 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
29
32
|
pi.registerTool(defineTool({
|
|
30
33
|
name: "remote_hosts",
|
|
31
34
|
label: "Remote Hosts",
|
|
32
|
-
description: "List
|
|
35
|
+
description: "List allowlisted SSH aliases, show cached connection status, or test SSH/SFTP/Bash connectivity",
|
|
33
36
|
promptSnippet: "List or check SSH hosts available to remote_* tools",
|
|
34
37
|
promptGuidelines: ["Use remote_hosts to discover valid host values before a remote_* call when the user has not named a configured host."],
|
|
35
38
|
parameters: Type.Object({
|
|
36
|
-
action: Type.Unsafe<"list" | "status" | "diagnose">({
|
|
39
|
+
action: Type.Unsafe<"list" | "status" | "diagnose">({
|
|
40
|
+
type: "string",
|
|
41
|
+
enum: ["list", "status", "diagnose"],
|
|
42
|
+
description: "list shows aliases; status shows cached state; diagnose opens a connection and requires host",
|
|
43
|
+
}),
|
|
37
44
|
host: Type.Optional(hostSchema),
|
|
38
45
|
}),
|
|
39
46
|
namespace,
|
|
@@ -60,7 +67,7 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
60
67
|
pi.registerTool(defineTool({
|
|
61
68
|
name: "remote_bash",
|
|
62
69
|
label: "Remote Bash",
|
|
63
|
-
description: "Execute a Bash command on
|
|
70
|
+
description: "Execute a non-interactive Bash command on an allowlisted SSH host. cwd defaults to the remote home; output and truncation follow Pi's native bash tool",
|
|
64
71
|
promptSnippet: "Execute Bash commands on a configured remote SSH host",
|
|
65
72
|
promptGuidelines: ["Use remote_bash for commands on a configured remote host; host is required and cwd defaults to ~."],
|
|
66
73
|
parameters: Type.Object({
|
|
@@ -86,7 +93,7 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
86
93
|
pi.registerTool(defineTool({
|
|
87
94
|
name: "remote_read",
|
|
88
95
|
label: "Remote Read",
|
|
89
|
-
description: "Read a text file or image from
|
|
96
|
+
description: "Read a text file or image from an allowlisted SSH host. Relative paths resolve against cwd or the remote home; pagination and truncation follow Pi's native read tool",
|
|
90
97
|
promptSnippet: "Read files on a configured remote SSH host",
|
|
91
98
|
promptGuidelines: ["Use remote_read instead of remote_bash cat for remote file reads; host is required and relative paths start at cwd or ~."],
|
|
92
99
|
parameters: Type.Object({
|
|
@@ -102,6 +109,9 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
102
109
|
async execute(id, { host, path, cwd, offset, limit }, signal, onUpdate) {
|
|
103
110
|
const connection = await manager.get(host);
|
|
104
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
|
+
}
|
|
105
115
|
const tool = createReadTool("/", { operations: remoteReadOperations(connection.readOperations()) });
|
|
106
116
|
return tool.execute(id, { path: absolutePath, offset, limit }, signal, onUpdate);
|
|
107
117
|
},
|
|
@@ -110,7 +120,7 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
110
120
|
pi.registerTool(defineTool({
|
|
111
121
|
name: "remote_write",
|
|
112
122
|
label: "Remote Write",
|
|
113
|
-
description: "Create or completely overwrite a file on
|
|
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",
|
|
114
124
|
promptSnippet: "Create or overwrite files on a configured remote SSH host",
|
|
115
125
|
promptGuidelines: ["Use remote_write only for new remote files or complete rewrites; use remote_edit for targeted changes."],
|
|
116
126
|
parameters: Type.Object({
|
|
@@ -123,6 +133,10 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
123
133
|
annotations: { destructiveHint: true, openWorldHint: true },
|
|
124
134
|
async execute(id, { host, path, content, cwd }, signal, onUpdate) {
|
|
125
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
|
+
}
|
|
126
140
|
return writeRemoteFile(connection.facts.home, cwd ?? "~", path, content, connection.writeOperations(), signal);
|
|
127
141
|
},
|
|
128
142
|
}));
|
|
@@ -130,7 +144,7 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
130
144
|
pi.registerTool(defineTool({
|
|
131
145
|
name: "remote_edit",
|
|
132
146
|
label: "Remote Edit",
|
|
133
|
-
description: "Apply exact
|
|
147
|
+
description: "Apply exact, uniquely matched, non-overlapping replacements to one file on an allowlisted SSH host. All edits target the same original content; validation failure writes nothing",
|
|
134
148
|
promptSnippet: "Make exact-text edits on a configured remote SSH host",
|
|
135
149
|
promptGuidelines: ["Use remote_edit for targeted remote changes. Every edits[].oldText must exactly and uniquely match the remote file."],
|
|
136
150
|
parameters: Type.Object({
|
|
@@ -138,14 +152,21 @@ export function registerRemoteTools(pi: ExtensionAPI, manager: HostManager): voi
|
|
|
138
152
|
path: Type.String({ description: "Remote absolute path, ~/path, or path relative to cwd" }),
|
|
139
153
|
cwd: cwdSchema,
|
|
140
154
|
edits: Type.Array(Type.Object({
|
|
141
|
-
oldText: Type.String(),
|
|
142
|
-
newText: Type.String(),
|
|
143
|
-
}), {
|
|
155
|
+
oldText: Type.String({ description: "Exact text to replace; it must occur exactly once in the original file" }),
|
|
156
|
+
newText: Type.String({ description: "Replacement text" }),
|
|
157
|
+
}), {
|
|
158
|
+
minItems: 1,
|
|
159
|
+
description: "One or more unique, non-overlapping replacements matched against the same original file",
|
|
160
|
+
}),
|
|
144
161
|
}),
|
|
145
162
|
namespace,
|
|
146
163
|
annotations: { destructiveHint: true, openWorldHint: true },
|
|
147
164
|
async execute(id, { host, path, cwd, edits }, signal, onUpdate) {
|
|
148
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
|
+
}
|
|
149
170
|
return editRemoteFile(connection.facts.home, cwd ?? "~", path, edits, connection.editOperations(), signal);
|
|
150
171
|
},
|
|
151
172
|
}));
|
package/src/transport.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
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_SOURCE } from "./remote-helper.ts";
|
|
6
10
|
import { remoteCommandScript, shellQuote } from "./remote-path.ts";
|
|
7
11
|
import { resolveSshConfig, type EffectiveSshConfig } from "./ssh-config.ts";
|
|
8
12
|
import {
|
|
@@ -11,6 +15,7 @@ import {
|
|
|
11
15
|
sftpMkdirP,
|
|
12
16
|
sftpReadFile,
|
|
13
17
|
sftpRealpath,
|
|
18
|
+
sftpUnlink,
|
|
14
19
|
sftpWriteFileAtomic,
|
|
15
20
|
} from "./sftp.ts";
|
|
16
21
|
|
|
@@ -20,6 +25,8 @@ export interface RemoteHostFacts {
|
|
|
20
25
|
hostname: string;
|
|
21
26
|
user: string;
|
|
22
27
|
platform: string;
|
|
28
|
+
fileMode: "python" | "sftp";
|
|
29
|
+
python?: { path: string; version: string };
|
|
23
30
|
}
|
|
24
31
|
|
|
25
32
|
type AuthAttempt =
|
|
@@ -50,22 +57,40 @@ async function openChannel(client: Client, command: string): Promise<ClientChann
|
|
|
50
57
|
return new Promise((resolve, reject) => client.exec(command, (error, channel) => (error ? reject(error) : resolve(channel))));
|
|
51
58
|
}
|
|
52
59
|
|
|
60
|
+
export function hostProbeScript(): string {
|
|
61
|
+
return `python_path=
|
|
62
|
+
python_version=
|
|
63
|
+
if python_path=$(command -v python3 2>/dev/null); then
|
|
64
|
+
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
|
|
65
|
+
python_path=
|
|
66
|
+
python_version=
|
|
67
|
+
fi
|
|
68
|
+
fi
|
|
69
|
+
printf '%s\\n' "$(hostname)" "$(id -un)" "$(uname -s)" "$python_path" "$python_version"
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function parseHostProbe(alias: string, home: string, output: string, exitCode: number | null): RemoteHostFacts {
|
|
74
|
+
const [hostname = "", user = "", platform = "", pythonPath = "", pythonVersion = ""] = output.trimEnd().split(/\r?\n/);
|
|
75
|
+
if (exitCode !== 0 || !hostname || !user) {
|
|
76
|
+
throw new RemoteCallError("E_CONNECT", `Connected to ${alias}, but the Bash probe failed`, "Ensure bash, hostname, id, and uname are available remotely");
|
|
77
|
+
}
|
|
78
|
+
const python = pythonPath && pythonVersion ? { path: pythonPath, version: pythonVersion } : undefined;
|
|
79
|
+
return { alias, home, hostname, user, platform, fileMode: python ? "python" : "sftp", ...(python ? { python } : {}) };
|
|
80
|
+
}
|
|
81
|
+
|
|
53
82
|
async function probeHost(client: Client, alias: string, home: string): Promise<RemoteHostFacts> {
|
|
54
83
|
const channel = await openChannel(client, "bash -s");
|
|
55
84
|
let output = "";
|
|
56
85
|
channel.stdout.on("data", (data: Buffer) => (output += data.toString("utf8")));
|
|
57
|
-
channel.end(
|
|
86
|
+
channel.end(hostProbeScript());
|
|
58
87
|
const exitCode = await new Promise<number | null>((resolve, reject) => {
|
|
59
88
|
let code: number | null = null;
|
|
60
89
|
channel.on("exit", (value: number | null) => (code = value));
|
|
61
90
|
channel.once("error", reject);
|
|
62
91
|
channel.once("close", () => resolve(code));
|
|
63
92
|
});
|
|
64
|
-
|
|
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 };
|
|
93
|
+
return parseHostProbe(alias, home, output, exitCode);
|
|
69
94
|
}
|
|
70
95
|
|
|
71
96
|
async function connectWithAttempt(
|
|
@@ -283,6 +308,48 @@ export class SshConnection {
|
|
|
283
308
|
});
|
|
284
309
|
}
|
|
285
310
|
|
|
311
|
+
async runPythonFileOperation(request: PythonFileRequest, signal?: AbortSignal): Promise<unknown> {
|
|
312
|
+
const python = this.facts.python;
|
|
313
|
+
if (!python) throw new RemoteCallError("E_REMOTE_HELPER", `Python 3 is not available for ${this.facts.alias}`);
|
|
314
|
+
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
315
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
316
|
+
const requestPath = posix.join("/tmp", `pi-remote-call-${process.pid}-${randomBytes(12).toString("hex")}.json`);
|
|
317
|
+
try {
|
|
318
|
+
await sftpWriteFileAtomic(this.sftp, requestPath, JSON.stringify(request));
|
|
319
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
320
|
+
const chunks: Buffer[] = [];
|
|
321
|
+
const command = `${shellQuote(python.path)} -c ${shellQuote(PYTHON_HELPER_SOURCE)} ${shellQuote(requestPath)}`;
|
|
322
|
+
const { exitCode } = await this.exec(command, this.facts.home, {
|
|
323
|
+
onData: (data) => chunks.push(Buffer.from(data)),
|
|
324
|
+
signal,
|
|
325
|
+
});
|
|
326
|
+
const output = Buffer.concat(chunks).toString("utf8").trim();
|
|
327
|
+
let envelope: { ok?: unknown; result?: unknown; error?: { code?: unknown; message?: unknown } };
|
|
328
|
+
try {
|
|
329
|
+
envelope = JSON.parse(output) as typeof envelope;
|
|
330
|
+
} catch (error) {
|
|
331
|
+
throw new RemoteCallError(
|
|
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);
|
|
348
|
+
} finally {
|
|
349
|
+
await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
286
353
|
close(): void {
|
|
287
354
|
if (this.closed) return;
|
|
288
355
|
this.closed = true;
|