pi-remote-call 0.0.0-stage → 0.1.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 +11 -0
- package/LICENSE +21 -0
- package/README.md +174 -2
- package/package.json +59 -4
- package/pi-remote-call.json.example +4 -0
- package/src/config.ts +66 -0
- package/src/errors.ts +33 -0
- package/src/file-tools.ts +208 -0
- package/src/host-key.ts +83 -0
- package/src/host-manager.ts +79 -0
- package/src/index.ts +58 -0
- package/src/remote-path.ts +18 -0
- package/src/sftp.ts +96 -0
- package/src/ssh-config.ts +128 -0
- package/src/tools.ts +152 -0
- package/src/transport.ts +291 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 - 2026-11-28
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Five typed `remote_*` tools for host discovery, Bash execution, file reads, complete writes, and exact edits over SSH/SFTP.
|
|
8
|
+
- Per-call SSH alias selection from an allowlist-only configuration, with home-directory and per-call working-directory support.
|
|
9
|
+
- Lazy persistent connections, explicit disconnects, session cleanup, timeout/cancellation handling, and unknown-outcome reporting after disconnects.
|
|
10
|
+
- Strict existing `known_hosts` verification and noninteractive agent/private-key authentication without password or passphrase prompts.
|
|
11
|
+
- Pi-native command/read results and edit diff details, with no remote software installation and no forced remote write queue.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pi-remote-call contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,175 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-remote-call
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A local Pi extension that exposes five typed tools for operating SSH-accessible Linux hosts. It uses local SSH exec channels and SFTP. **Nothing is installed on the remote machines**: no remote Pi, Node.js, npm package, MCP server, agent, or daemon.
|
|
4
|
+
|
|
5
|
+
The extension adds `remote_*` tools. It never replaces Pi's local `bash`, `read`, `write`, or `edit` tools.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
Local machine:
|
|
10
|
+
|
|
11
|
+
- Pi 1.7.0 or a compatible newer release
|
|
12
|
+
- Node.js 22.19+
|
|
13
|
+
- OpenSSH-compatible `ssh` and `ssh-keygen` commands on `PATH`
|
|
14
|
+
- Existing noninteractive SSH authentication and a verified `known_hosts` entry
|
|
15
|
+
|
|
16
|
+
Remote machine:
|
|
17
|
+
|
|
18
|
+
- `sshd`, Bash, and SFTP already enabled
|
|
19
|
+
- Standard `hostname`, `id`, `uname`, `kill`, and `sleep` commands
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
### npm
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pi install npm:pi-remote-call@0.1.0
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### GitHub
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
pi install git:github.com/therainisme/pi-remote-call@v0.1.0
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Local directory
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pi install /absolute/path/to/pi-remote-call
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Create `~/.pi/agent/pi-remote-call.json`:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"version": 1,
|
|
46
|
+
"hosts": ["server-a", "server-b"]
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Only aliases in `hosts[]` can be used. User, hostname, port, identity files, agent, `HostKeyAlias`, and known-hosts paths come from the existing OpenSSH configuration via `ssh -G <alias>`; secrets and connection fields are not duplicated into this file.
|
|
51
|
+
|
|
52
|
+
Set `PI_REMOTE_CALL_CONFIG` to use a different local config path.
|
|
53
|
+
|
|
54
|
+
Restart Pi after changing the allowlist. Connections are opened lazily and are not opened by `remote_hosts({action:"list"})`.
|
|
55
|
+
|
|
56
|
+
## Tools
|
|
57
|
+
|
|
58
|
+
Every execution tool requires `host`. There is no global current host, so calls to different hosts can be made independently in the same turn.
|
|
59
|
+
|
|
60
|
+
### `remote_hosts`
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{"action":"list"}
|
|
64
|
+
{"action":"status","host":"server-a"}
|
|
65
|
+
{"action":"diagnose","host":"server-a"}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- `list`: list configured aliases and cached connection state.
|
|
69
|
+
- `status`: inspect cached state without opening a connection.
|
|
70
|
+
- `diagnose`: resolve SSH configuration, verify the host key, authenticate, initialize SFTP, and run a Bash probe.
|
|
71
|
+
|
|
72
|
+
### `remote_bash`
|
|
73
|
+
|
|
74
|
+
```json
|
|
75
|
+
{
|
|
76
|
+
"host": "server-a",
|
|
77
|
+
"command": "pwd && uname -a",
|
|
78
|
+
"cwd": "~/work",
|
|
79
|
+
"timeout": 30
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`cwd` defaults to the remote user's home directory. `timeout` is in seconds. Output streaming, tail truncation, exit status, timeout handling, and result details use Pi's native bash implementation.
|
|
84
|
+
|
|
85
|
+
### `remote_read`
|
|
86
|
+
|
|
87
|
+
```json
|
|
88
|
+
{
|
|
89
|
+
"host": "server-a",
|
|
90
|
+
"path": "notes/todo.md",
|
|
91
|
+
"offset": 1,
|
|
92
|
+
"limit": 200
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The example reads `~/notes/todo.md`. An optional `cwd` changes the base for relative paths. Absolute paths and `~/...` ignore `cwd`.
|
|
97
|
+
|
|
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.
|
|
99
|
+
|
|
100
|
+
### `remote_write`
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"host": "server-a",
|
|
105
|
+
"path": "notes/todo.md",
|
|
106
|
+
"content": "new complete contents\n"
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
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.
|
|
111
|
+
|
|
112
|
+
### `remote_edit`
|
|
113
|
+
|
|
114
|
+
```json
|
|
115
|
+
{
|
|
116
|
+
"host": "server-a",
|
|
117
|
+
"path": "notes/todo.md",
|
|
118
|
+
"edits": [
|
|
119
|
+
{"oldText":"before","newText":"after"}
|
|
120
|
+
]
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
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.
|
|
125
|
+
|
|
126
|
+
## Command
|
|
127
|
+
|
|
128
|
+
```text
|
|
129
|
+
/remote-call
|
|
130
|
+
/remote-call list
|
|
131
|
+
/remote-call status server-a
|
|
132
|
+
/remote-call disconnect server-a
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Connections also close during Pi session shutdown. A later call reconnects on demand.
|
|
136
|
+
|
|
137
|
+
## Failure behavior
|
|
138
|
+
|
|
139
|
+
- Unknown or changed host keys fail. The extension never disables host-key checks or automatically trusts a new key.
|
|
140
|
+
- Passwords, private-key passphrases, interactive 2FA, and keyboard-interactive authentication are not requested. Fix `ssh <alias>` so it works noninteractively first.
|
|
141
|
+
- A failed command or write is not automatically replayed after reconnecting.
|
|
142
|
+
- If a connection disappears before a command returns an exit status, the tool reports that its outcome is unknown.
|
|
143
|
+
- 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
|
+
|
|
145
|
+
## Limitations
|
|
146
|
+
|
|
147
|
+
- Direct SSH aliases only. `ProxyJump` and `ProxyCommand` return an explicit unsupported-option error.
|
|
148
|
+
- Standard `known_hosts` public keys are supported; CA-based `@cert-authority` trust is not implemented.
|
|
149
|
+
- Remote targets are Linux/Bash systems, not Windows shells.
|
|
150
|
+
- Remote paths use POSIX `/`. Backslashes in remote file names are not supported when Pi itself runs on Windows because Pi's native read parser processes them first.
|
|
151
|
+
- 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.
|
|
153
|
+
|
|
154
|
+
## Development
|
|
155
|
+
|
|
156
|
+
```sh
|
|
157
|
+
npm install
|
|
158
|
+
npm run check
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`npm run check` typechecks, builds, and runs unit/integration tests without opening SSH connections.
|
|
162
|
+
|
|
163
|
+
Package layout:
|
|
164
|
+
|
|
165
|
+
```text
|
|
166
|
+
src/index.ts extension entry and /remote-call command
|
|
167
|
+
src/tools.ts five typed tool registrations
|
|
168
|
+
src/host-manager.ts per-alias lazy connection reuse
|
|
169
|
+
src/transport.ts SSH authentication, host-key verification, Bash channels
|
|
170
|
+
src/sftp.ts SFTP streams, directories, atomic writes
|
|
171
|
+
src/file-tools.ts remote POSIX paths, exact edits, native result details
|
|
172
|
+
src/config.ts allowlist-only configuration
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-remote-call",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Call shell and file tools on SSH hosts from one local Pi, with zero remote installation.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/therainisme/pi-remote-call.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/therainisme/pi-remote-call#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/therainisme/pi-remote-call/issues"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"CHANGELOG.md",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE",
|
|
19
|
+
"pi-remote-call.json.example"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22.19.0"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"pi-package",
|
|
30
|
+
"pi-extension",
|
|
31
|
+
"ssh",
|
|
32
|
+
"remote"
|
|
33
|
+
],
|
|
34
|
+
"pi": {
|
|
35
|
+
"extensions": [
|
|
36
|
+
"./src/index.ts"
|
|
37
|
+
]
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.json",
|
|
41
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
42
|
+
"test": "npm run build && node --test dist/test/*.test.js",
|
|
43
|
+
"check": "npm run typecheck && npm test",
|
|
44
|
+
"prepublishOnly": "npm run check && npm pack --dry-run"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"diff": "^8.0.4",
|
|
48
|
+
"ssh2": "^1.16.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@earendil-works/pi-ai": "*",
|
|
52
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
53
|
+
"typebox": "*"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/node": "^22.19.0",
|
|
57
|
+
"@types/ssh2": "^1.15.5",
|
|
58
|
+
"typebox": "1.3.27",
|
|
59
|
+
"typescript": "^5.9.3"
|
|
60
|
+
}
|
|
61
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { RemoteCallError } from "./errors.ts";
|
|
5
|
+
|
|
6
|
+
export interface RemoteCallConfig {
|
|
7
|
+
version: 1;
|
|
8
|
+
hosts: string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function defaultConfigPath(): string {
|
|
12
|
+
return process.env.PI_REMOTE_CALL_CONFIG || join(homedir(), ".pi", "agent", "pi-remote-call.json");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseConfig(text: string): RemoteCallConfig {
|
|
16
|
+
let value: unknown;
|
|
17
|
+
try {
|
|
18
|
+
value = JSON.parse(text);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
throw new RemoteCallError("E_CONFIG", "Invalid JSON in pi-remote-call.json", undefined, { cause: error });
|
|
21
|
+
}
|
|
22
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
23
|
+
throw new RemoteCallError("E_CONFIG", 'Config must be an object: {"version":1,"hosts":["ssh-alias"]}');
|
|
24
|
+
}
|
|
25
|
+
const candidate = value as Record<string, unknown>;
|
|
26
|
+
for (const key of Object.keys(candidate)) {
|
|
27
|
+
if (key !== "version" && key !== "hosts") throw new RemoteCallError("E_CONFIG", `Unknown config field: ${key}. Only version and hosts[] are allowed.`);
|
|
28
|
+
}
|
|
29
|
+
if (candidate.version !== 1 || !Array.isArray(candidate.hosts)) {
|
|
30
|
+
throw new RemoteCallError("E_CONFIG", 'Config must be an object: {"version":1,"hosts":["ssh-alias"]}');
|
|
31
|
+
}
|
|
32
|
+
const hosts = candidate.hosts.map((host) => {
|
|
33
|
+
if (typeof host !== "string" || !host.trim() || /\s/.test(host) || host.startsWith("-")) {
|
|
34
|
+
throw new RemoteCallError("E_CONFIG", "Every hosts[] entry must be a non-empty SSH alias without whitespace or a leading -");
|
|
35
|
+
}
|
|
36
|
+
return host;
|
|
37
|
+
});
|
|
38
|
+
if (hosts.length === 0) {
|
|
39
|
+
throw new RemoteCallError("E_CONFIG", "hosts[] must contain at least one SSH alias");
|
|
40
|
+
}
|
|
41
|
+
if (new Set(hosts).size !== hosts.length) {
|
|
42
|
+
throw new RemoteCallError("E_CONFIG", "hosts[] contains a duplicate SSH alias");
|
|
43
|
+
}
|
|
44
|
+
return { version: 1, hosts };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function loadConfig(path = defaultConfigPath()): RemoteCallConfig {
|
|
48
|
+
let text: string;
|
|
49
|
+
try {
|
|
50
|
+
text = readFileSync(path, "utf8");
|
|
51
|
+
} catch (error) {
|
|
52
|
+
throw new RemoteCallError(
|
|
53
|
+
"E_CONFIG",
|
|
54
|
+
`Cannot read pi-remote-call config: ${path}`,
|
|
55
|
+
`Create it with {\"version\":1,\"hosts\":[\"your-ssh-alias\"]}. See pi-remote-call.json.example.`,
|
|
56
|
+
{ cause: error },
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return parseConfig(text);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function assertKnownHost(config: RemoteCallConfig, host: string): void {
|
|
63
|
+
if (!config.hosts.includes(host)) {
|
|
64
|
+
throw new RemoteCallError("E_UNKNOWN_HOST", `Unknown SSH alias: ${host}`, `Use one of: ${config.hosts.join(", ")}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export type RemoteCallErrorCode =
|
|
2
|
+
| "E_CONFIG"
|
|
3
|
+
| "E_UNKNOWN_HOST"
|
|
4
|
+
| "E_SSH_CONFIG"
|
|
5
|
+
| "E_UNSUPPORTED_SSH_OPTION"
|
|
6
|
+
| "E_HOST_KEY_UNKNOWN"
|
|
7
|
+
| "E_HOST_KEY_CHANGED"
|
|
8
|
+
| "E_AUTH"
|
|
9
|
+
| "E_CONNECT"
|
|
10
|
+
| "E_DISCONNECTED"
|
|
11
|
+
| "E_CLOSED";
|
|
12
|
+
|
|
13
|
+
export class RemoteCallError extends Error {
|
|
14
|
+
readonly code: RemoteCallErrorCode;
|
|
15
|
+
readonly hint?: string;
|
|
16
|
+
|
|
17
|
+
constructor(code: RemoteCallErrorCode, message: string, hint?: string, options?: ErrorOptions) {
|
|
18
|
+
super(message, options);
|
|
19
|
+
this.name = "RemoteCallError";
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.hint = hint;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
toString(): string {
|
|
25
|
+
return `[${this.code}] ${this.message}${this.hint ? `\nFix: ${this.hint}` : ""}`;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function asRemoteCallError(error: unknown, fallbackCode: RemoteCallErrorCode, prefix: string): RemoteCallError {
|
|
30
|
+
if (error instanceof RemoteCallError) return error;
|
|
31
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
32
|
+
return new RemoteCallError(fallbackCode, `${prefix}: ${message}`, undefined, { cause: error });
|
|
33
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { createTwoFilesPatch, FILE_HEADERS_ONLY, structuredPatch } from "diff";
|
|
3
|
+
import type { EditOperations, EditToolDetails, ReadOperations, WriteOperations } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { resolveRemotePath } from "./remote-path.ts";
|
|
5
|
+
|
|
6
|
+
export interface ExactEdit {
|
|
7
|
+
oldText: string;
|
|
8
|
+
newText: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface Replacement {
|
|
12
|
+
editIndex: number;
|
|
13
|
+
matchIndex: number;
|
|
14
|
+
matchLength: number;
|
|
15
|
+
newText: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function normalizeToLF(text: string): string {
|
|
19
|
+
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function applyReplacements(content: string, replacements: Replacement[]): string {
|
|
23
|
+
let result = content;
|
|
24
|
+
for (const replacement of [...replacements].sort((a, b) => b.matchIndex - a.matchIndex)) {
|
|
25
|
+
result = result.slice(0, replacement.matchIndex) + replacement.newText + result.slice(replacement.matchIndex + replacement.matchLength);
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** All edits match the same original content; overlapping or ambiguous edits fail before anything is written. */
|
|
31
|
+
export function applyExactEdits(content: string, edits: ExactEdit[], path: string) {
|
|
32
|
+
const normalized = edits.map((edit) => ({ oldText: normalizeToLF(edit.oldText), newText: normalizeToLF(edit.newText) }));
|
|
33
|
+
const replacements: Replacement[] = [];
|
|
34
|
+
for (let editIndex = 0; editIndex < normalized.length; editIndex++) {
|
|
35
|
+
const edit = normalized[editIndex];
|
|
36
|
+
if (!edit.oldText) throw new Error(`edits[${editIndex}].oldText must not be empty in ${path}`);
|
|
37
|
+
const matchIndex = content.indexOf(edit.oldText);
|
|
38
|
+
if (matchIndex < 0) throw new Error(`Could not find edits[${editIndex}].oldText in ${path}. Match the original file exactly.`);
|
|
39
|
+
const second = content.indexOf(edit.oldText, matchIndex + 1);
|
|
40
|
+
if (second >= 0) throw new Error(`edits[${editIndex}].oldText is not unique in ${path}; found at least two matches.`);
|
|
41
|
+
replacements.push({ editIndex, matchIndex, matchLength: edit.oldText.length, newText: edit.newText });
|
|
42
|
+
}
|
|
43
|
+
replacements.sort((a, b) => a.matchIndex - b.matchIndex);
|
|
44
|
+
for (let i = 1; i < replacements.length; i++) {
|
|
45
|
+
const previous = replacements[i - 1];
|
|
46
|
+
const current = replacements[i];
|
|
47
|
+
if (previous.matchIndex + previous.matchLength > current.matchIndex) {
|
|
48
|
+
throw new Error(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const newContent = applyReplacements(content, replacements);
|
|
52
|
+
if (newContent === content) throw new Error(`No changes would be made to ${path}.`);
|
|
53
|
+
return { baseContent: content, newContent, replacements };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Adapted from Pi's edit-diff.ts: map LF-normalized offsets back to CRLF content.
|
|
57
|
+
function lineEndingAt(content: string, offset: number): string {
|
|
58
|
+
let lineFeed = content.indexOf("\n", offset);
|
|
59
|
+
if (lineFeed === -1) lineFeed = content.lastIndexOf("\n", offset);
|
|
60
|
+
if (lineFeed === -1) return content.includes("\r") ? "\r" : "\n";
|
|
61
|
+
return content[lineFeed - 1] === "\r" ? "\r\n" : "\n";
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function applyReplacementsToOriginal(originalContent: string, replacements: Replacement[]): string {
|
|
65
|
+
let crlfBefore = 0;
|
|
66
|
+
let nextCrlf = originalContent.indexOf("\r\n");
|
|
67
|
+
const toOriginal = (offset: number) => {
|
|
68
|
+
while (nextCrlf !== -1 && nextCrlf - crlfBefore < offset) {
|
|
69
|
+
crlfBefore++;
|
|
70
|
+
nextCrlf = originalContent.indexOf("\r\n", nextCrlf + 2);
|
|
71
|
+
}
|
|
72
|
+
return offset + crlfBefore;
|
|
73
|
+
};
|
|
74
|
+
const parts: string[] = [];
|
|
75
|
+
let endsWithCr = false;
|
|
76
|
+
const push = (part: string) => {
|
|
77
|
+
if (!part) return;
|
|
78
|
+
if (endsWithCr && part[0] === "\n") parts.push("\n");
|
|
79
|
+
parts.push(part);
|
|
80
|
+
endsWithCr = part[part.length - 1] === "\r";
|
|
81
|
+
};
|
|
82
|
+
let position = 0;
|
|
83
|
+
for (const replacement of replacements) {
|
|
84
|
+
const start = toOriginal(replacement.matchIndex);
|
|
85
|
+
push(originalContent.slice(position, start));
|
|
86
|
+
const ending = lineEndingAt(originalContent, start);
|
|
87
|
+
push(ending === "\n" ? replacement.newText : replacement.newText.replaceAll("\n", ending));
|
|
88
|
+
position = toOriginal(replacement.matchIndex + replacement.matchLength);
|
|
89
|
+
}
|
|
90
|
+
push(originalContent.slice(position));
|
|
91
|
+
return parts.join("");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function lineCount(text: string): number {
|
|
95
|
+
let count = 1;
|
|
96
|
+
for (let index = text.indexOf("\n"); index >= 0; index = text.indexOf("\n", index + 1)) count++;
|
|
97
|
+
return count;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function generateEditDetails(path: string, oldContent: string, newContent: string): EditToolDetails {
|
|
101
|
+
const patch = createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {
|
|
102
|
+
context: 4,
|
|
103
|
+
headerOptions: FILE_HEADERS_ONLY,
|
|
104
|
+
});
|
|
105
|
+
const structured = structuredPatch(path, path, oldContent, newContent, undefined, undefined, { context: 4 });
|
|
106
|
+
const width = String(Math.max(lineCount(oldContent), lineCount(newContent))).length;
|
|
107
|
+
const output: string[] = [];
|
|
108
|
+
let firstChangedLine: number | undefined;
|
|
109
|
+
for (let hunkIndex = 0; hunkIndex < structured.hunks.length; hunkIndex++) {
|
|
110
|
+
const hunk = structured.hunks[hunkIndex];
|
|
111
|
+
if (hunkIndex > 0) output.push(` ${"".padStart(width)} ...`);
|
|
112
|
+
let oldLine = Math.max(1, hunk.oldStart);
|
|
113
|
+
let newLine = Math.max(1, hunk.newStart);
|
|
114
|
+
for (const line of hunk.lines) {
|
|
115
|
+
const marker = line[0];
|
|
116
|
+
const text = line.slice(1);
|
|
117
|
+
if (marker === "+" || marker === "-") firstChangedLine ??= newLine;
|
|
118
|
+
if (marker === "+") {
|
|
119
|
+
output.push(`+${String(newLine).padStart(width)} ${text}`);
|
|
120
|
+
newLine++;
|
|
121
|
+
} else if (marker === "-") {
|
|
122
|
+
output.push(`-${String(oldLine).padStart(width)} ${text}`);
|
|
123
|
+
oldLine++;
|
|
124
|
+
} else if (marker === " ") {
|
|
125
|
+
output.push(` ${String(oldLine).padStart(width)} ${text}`);
|
|
126
|
+
oldLine++;
|
|
127
|
+
newLine++;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { diff: output.join("\n"), patch, firstChangedLine };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function throwIfAborted(signal?: AbortSignal): void {
|
|
135
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function writeRemoteFile(
|
|
139
|
+
home: string,
|
|
140
|
+
cwd: string | undefined,
|
|
141
|
+
inputPath: string,
|
|
142
|
+
content: string,
|
|
143
|
+
operations: WriteOperations,
|
|
144
|
+
signal?: AbortSignal,
|
|
145
|
+
) {
|
|
146
|
+
const path = resolveRemotePath(home, inputPath, cwd);
|
|
147
|
+
throwIfAborted(signal);
|
|
148
|
+
await operations.mkdir(posix.dirname(path));
|
|
149
|
+
throwIfAborted(signal);
|
|
150
|
+
await operations.writeFile(path, content);
|
|
151
|
+
throwIfAborted(signal);
|
|
152
|
+
return { content: [{ type: "text" as const, text: `Successfully wrote to ${inputPath}` }], details: undefined };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function editRemoteFile(
|
|
156
|
+
home: string,
|
|
157
|
+
cwd: string | undefined,
|
|
158
|
+
inputPath: string,
|
|
159
|
+
edits: ExactEdit[],
|
|
160
|
+
operations: EditOperations,
|
|
161
|
+
signal?: AbortSignal,
|
|
162
|
+
) {
|
|
163
|
+
if (edits.length === 0) throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");
|
|
164
|
+
const path = resolveRemotePath(home, inputPath, cwd);
|
|
165
|
+
throwIfAborted(signal);
|
|
166
|
+
try {
|
|
167
|
+
await operations.access(path);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
throwIfAborted(signal);
|
|
170
|
+
const code = error instanceof Error && "code" in error ? `Error code: ${error.code}` : String(error);
|
|
171
|
+
throw new Error(`Could not edit file: ${inputPath}. ${code}.`, { cause: error });
|
|
172
|
+
}
|
|
173
|
+
throwIfAborted(signal);
|
|
174
|
+
const raw = (await operations.readFile(path)).toString("utf8");
|
|
175
|
+
throwIfAborted(signal);
|
|
176
|
+
const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
177
|
+
const original = bom ? raw.slice(1) : raw;
|
|
178
|
+
const { baseContent, newContent, replacements } = applyExactEdits(normalizeToLF(original), edits, inputPath);
|
|
179
|
+
const details = generateEditDetails(inputPath, baseContent, newContent);
|
|
180
|
+
throwIfAborted(signal);
|
|
181
|
+
const finalContent = bom + (original === baseContent ? newContent : applyReplacementsToOriginal(original, replacements));
|
|
182
|
+
await operations.writeFile(path, finalContent);
|
|
183
|
+
throwIfAborted(signal);
|
|
184
|
+
return {
|
|
185
|
+
content: [{ type: "text" as const, text: `Successfully replaced ${edits.length} block(s) in ${inputPath}.` }],
|
|
186
|
+
details,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Pi resolves tool paths with the local OS first. Convert its absolute Windows path back to remote POSIX. */
|
|
191
|
+
export function nativeToolPathToRemote(path: string): string {
|
|
192
|
+
if (process.platform !== "win32") return path;
|
|
193
|
+
return path.replace(/^[A-Za-z]:/, "").replace(/\\/g, "/");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function remoteReadOperations(operations: ReadOperations): ReadOperations {
|
|
197
|
+
const createReadStream = operations.createReadStream;
|
|
198
|
+
const detectImageMimeType = operations.detectImageMimeType;
|
|
199
|
+
return {
|
|
200
|
+
readFile: (path) => operations.readFile(nativeToolPathToRemote(path)),
|
|
201
|
+
access: (path) => operations.access(nativeToolPathToRemote(path)),
|
|
202
|
+
detectImageMimeType: async (path) => (await detectImageMimeType?.(nativeToolPathToRemote(path))) ?? null,
|
|
203
|
+
createReadStream: (path, options) => {
|
|
204
|
+
if (!createReadStream) throw new Error("This remote read transport does not support streaming");
|
|
205
|
+
return createReadStream(nativeToolPathToRemote(path), options);
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
}
|
package/src/host-key.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import type { EffectiveSshConfig } from "./ssh-config.ts";
|
|
4
|
+
import { RemoteCallError } from "./errors.ts";
|
|
5
|
+
|
|
6
|
+
export interface KnownHostEntry {
|
|
7
|
+
key: string;
|
|
8
|
+
revoked: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function parseKnownHosts(output: string): KnownHostEntry[] {
|
|
12
|
+
const entries: KnownHostEntry[] = [];
|
|
13
|
+
for (const rawLine of output.split(/\r?\n/)) {
|
|
14
|
+
const line = rawLine.trim();
|
|
15
|
+
if (!line || line.startsWith("#")) continue;
|
|
16
|
+
const revoked = line.startsWith("@revoked ");
|
|
17
|
+
if (line.startsWith("@") && !revoked) continue;
|
|
18
|
+
const fields = line.split(/\s+/);
|
|
19
|
+
for (let i = 0; i < fields.length - 1; i++) {
|
|
20
|
+
if (/^(?:ssh|ecdsa|sk)-/.test(fields[i]) && /^[A-Za-z0-9+/]+={0,3}$/.test(fields[i + 1])) {
|
|
21
|
+
entries.push({ key: fields[i + 1], revoked });
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return entries;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function lookupKnownHosts(target: string, file: string): Promise<KnownHostEntry[]> {
|
|
30
|
+
if (!existsSync(file)) return [];
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
execFile("ssh-keygen", ["-F", target, "-f", file], { timeout: 10_000, windowsHide: true }, (error, stdout) => {
|
|
33
|
+
if (error && (error as NodeJS.ErrnoException).code !== "1") {
|
|
34
|
+
// A missing known_hosts file is equivalent to no matching entries.
|
|
35
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return resolve([]);
|
|
36
|
+
return reject(error);
|
|
37
|
+
}
|
|
38
|
+
resolve(parseKnownHosts(stdout));
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function loadKnownHostEntries(config: EffectiveSshConfig): Promise<KnownHostEntry[]> {
|
|
44
|
+
const host = config.hostKeyAlias ?? config.host;
|
|
45
|
+
const targets = config.hostKeyAlias ? [host] : config.port === 22 ? [host] : [`[${host}]:${config.port}`];
|
|
46
|
+
const entries: KnownHostEntry[] = [];
|
|
47
|
+
for (const file of config.knownHostsFiles) {
|
|
48
|
+
for (const target of targets) {
|
|
49
|
+
try {
|
|
50
|
+
entries.push(...(await lookupKnownHosts(target, file)));
|
|
51
|
+
} catch (error) {
|
|
52
|
+
throw new RemoteCallError(
|
|
53
|
+
"E_HOST_KEY_UNKNOWN",
|
|
54
|
+
`Cannot inspect known_hosts for ${config.alias}`,
|
|
55
|
+
`Verify the host once with: ssh ${config.alias}`,
|
|
56
|
+
{ cause: error },
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return [...new Map(entries.map((entry) => [`${entry.revoked}:${entry.key}`, entry])).values()];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function verifyKnownHostKey(config: EffectiveSshConfig, entries: KnownHostEntry[], key: Buffer): void {
|
|
65
|
+
const encoded = key.toString("base64");
|
|
66
|
+
const matches = entries.filter((entry) => entry.key === encoded);
|
|
67
|
+
if (matches.some((entry) => entry.revoked)) {
|
|
68
|
+
throw new RemoteCallError("E_HOST_KEY_CHANGED", `The host key for ${config.alias} is revoked`);
|
|
69
|
+
}
|
|
70
|
+
if (matches.length > 0) return;
|
|
71
|
+
if (entries.length > 0) {
|
|
72
|
+
throw new RemoteCallError(
|
|
73
|
+
"E_HOST_KEY_CHANGED",
|
|
74
|
+
`The presented host key does not match known_hosts for ${config.alias}`,
|
|
75
|
+
`Inspect the change manually with: ssh ${config.alias}`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
throw new RemoteCallError(
|
|
79
|
+
"E_HOST_KEY_UNKNOWN",
|
|
80
|
+
`No known_hosts entry found for ${config.alias}`,
|
|
81
|
+
`Verify the host once with: ssh ${config.alias}`,
|
|
82
|
+
);
|
|
83
|
+
}
|