aiterm-mcp 0.68.1 → 0.69.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 -1
- package/README.ja.md +2 -2
- package/README.md +2 -2
- package/dist/claude-catalog-root.js +51 -0
- package/dist/core.js +5 -1
- package/dist/harnesses/claude.js +22 -0
- package/dist/index.js +3 -2
- package/dist/remote-authorize.js +149 -0
- package/dist/remote-contract.js +1 -1
- package/dist/remote-path.js +86 -0
- package/dist/remote-provision.js +105 -0
- package/dist/remote-terminal-cli.js +40 -8
- package/dist/remote-terminal.js +44 -8
- package/dist/remote.js +3 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.69.0] - 2026-11-10
|
|
11
|
+
|
|
12
|
+
- Terminal self-service before a seat can open (docs/architecture/remote-terminal.md R14-R17; BellTeam PR 854 S2-S5).
|
|
13
|
+
- `aiterm-remote-terminal authorize-key --ref R`: the terminal's login password is the raw UTF-8 stdin until EOF (nothing stripped). After the binding's trust and held key are checked (before stdin is read), one password-only SSH login (no public key, no keyboard-interactive, one prompt) appends the held public key to `~/.ssh/authorized_keys` unless the same key type and blob is already there (`~/.ssh` 0700, file 0600, other entries kept). The password reaches ssh only through a one-shot askpass socket; never argv, env, files, logs or the PTY. Receipt `aiterm.remote-key-authorization.v1` `{ref, result: AUTHORIZED | ALREADY_AUTHORIZED}`; failures `PASSWORD_REJECTED`, `PASSWORD_AUTH_DISABLED`, `PASSWORD_INVALID`, `AUTHORIZED_KEYS_WRITE_FAILED` and the existing trust/key/network codes.
|
|
14
|
+
- `aiterm-remote-terminal provision --ref R` (macOS arm64/x86_64): over the binding's trusted key SSH and before any terminal MCP exists, the terminal downloads this version's runtime from the GitHub Release (official Node, the published aiterm-mcp, and a tmux with its libraries linked in), checks its sha256, stages and smokes it, then makes it `~/.aiterm/runtime/current` (the previous one stays as `previous`; running seats and tmux servers are untouched). No Homebrew, npm, Node, tmux, password or sudo on the terminal. Receipt `aiterm.remote-provision.v1` `{ref, result: PROVISIONED | ALREADY_CURRENT, version}`. Remote POSIX commands now put that runtime first on PATH. The release workflow `runtime.yml` builds and attaches the assets on the macOS runner.
|
|
15
|
+
- `remote_terminal_command` takes `path_status` and `make_dir` with an absolute `path` -> `{op, exists, directory, writable}`; `writable` is a real create-and-remove probe. Permission refusals (macOS privacy consent, ACL or POSIX, not told apart) answer `FOLDER_NOT_PERMITTED`, and a missing folder under an unreadable parent is not reported as missing. Needs this release on the terminal (`REMOTE_AITERM_TOO_OLD` otherwise).
|
|
16
|
+
- SSH "Connection refused" now answers `CONNECTION_REFUSED` instead of `UNREACHABLE` (evidence only: SSH may be off on the terminal). `trust-confirm` answers `UNREACHABLE` when the scan returns no host key at all (an asleep Mac is not another machine); keys without the confirmed fingerprint stay `HOST_KEY_FINGERPRINT_MISMATCH`.
|
|
17
|
+
- `agent_models` for claude-code returns the same list on every call. Claude Code keeps its served-catalog switch in the configuration root's shared global config, and seats or logins sharing that root rewrote it, so the list flipped between 5 and 14 models (Fable 5.2 missing at random). The catalog now runs in its own root per configuration root that only the catalog writes, holding only the root's access token (no refresh token, so the root's login is never rotated from there), and repeats until two runs agree while that root is cold (docs/architecture/harness-contracts.md C1-C4). Roots whose credentials are not a file (macOS Keychain), token/API-key environments and near-expiry tokens run on the root as before. New optional `configuration_root` (claude-code only, accepted like `agent_launch`; otherwise `AGENT_CONFIGURATION_ROOT_REJECTED`) reads the list of the account a seat is launched on.
|
|
18
|
+
|
|
10
19
|
## [0.68.1] - 2026-11-09
|
|
11
20
|
|
|
12
21
|
- Seat activity (`readSeatTurns`): a fresh Claude seat that has never been busy and has no recorded turn or completion, such as a no-prompt launch after a harness switch, now reads `idle` after the usual 250 ms settle. Before, its ready composer had no completed-progress line ("✻ Cooked for 12s"), so the reading stayed unknown until the first input and after-turn work never started. Once the seat has a recorded turn or completion, the completed-progress line is still required.
|
|
@@ -3144,7 +3153,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3144
3153
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3145
3154
|
provenance.
|
|
3146
3155
|
|
|
3147
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.
|
|
3156
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.69.0...HEAD
|
|
3157
|
+
[0.69.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.68.1...v0.69.0
|
|
3148
3158
|
[0.68.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.68.0...v0.68.1
|
|
3149
3159
|
[0.68.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.67.0...v0.68.0
|
|
3150
3160
|
[0.67.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.66.0...v0.67.0
|
package/README.ja.md
CHANGED
|
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
|
|
|
215
215
|
場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
|
|
216
216
|
Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
|
|
217
217
|
|
|
218
|
-
**状態:** 開発継続中 · 現行公開版 **v0.
|
|
218
|
+
**状態:** 開発継続中 · 現行公開版 **v0.69.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
|
|
219
219
|
|
|
220
220
|
### 更新と巻き戻し
|
|
221
221
|
|
|
@@ -618,7 +618,7 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
|
|
|
618
618
|
| `pty_observe` | pane/harnessの生存、native process identity、状態と活動 | `session_id`, `cursor?` |
|
|
619
619
|
| `agent_launch` | harnessとmodelを別軸で選ぶ正規agent起動入口 | `harness`, `prompt?`, `model?`, `reasoning_effort?`, `fast?`, `cwd?`, `write_scope?`, `trust_project?`, `env_vars?`, `throughline_source_session?`, `throughline_supplement_file?` |
|
|
620
620
|
| `agent_auth` | 公式CLIの認証を開始・確認・取消し、公式URL・device code・入力待ちを返す | `harness`, `action`, `session_id?`, `cwd?`, `env_vars?`, `relogin?`, `expected_binding?`, `response?` |
|
|
621
|
-
| `agent_models` | harnessが今選べるmodelとreasoning effortを、そのharness自身の一覧からpromptを送らずに取得 | `harness`, `cwd?`, `include_hidden
|
|
621
|
+
| `agent_models` | harnessが今選べるmodelとreasoning effortを、そのharness自身の一覧からpromptを送らずに取得 | `harness`, `cwd?`, `include_hidden?`, `configuration_root?`(claude-code) |
|
|
622
622
|
| `agent_approval` | Codexの現在の承認を検査し、単発許可・拒否を送る | `action`, `session_id`, `approval_choice?`, `observed_prompt_digest?` |
|
|
623
623
|
| `claude_agent` / `codex_agent` / `grok_agent` | deprecated互換alias(`composer_agent`は0.41.0で削除。Composerは`agent_launch`の`cursor-cli`で使う) | 旧launcher引数 |
|
|
624
624
|
| `agent_configure` | 起動中のClaude/Codex/Grok/Cursor/Antigravityを再起動せずmodel/effort/fast変更 | `session_id`, `model?`, `reasoning_effort?`, `fast?` |
|
package/README.md
CHANGED
|
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
|
|
|
227
227
|
tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
|
|
228
228
|
Release re-registers the Official MCP Registry entry.
|
|
229
229
|
|
|
230
|
-
**Status:** actively maintained · current public release **v0.
|
|
230
|
+
**Status:** actively maintained · current public release **v0.69.0** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
|
|
231
231
|
|
|
232
232
|
### Update and rollback
|
|
233
233
|
|
|
@@ -658,7 +658,7 @@ continue to use `claude_approval`.
|
|
|
658
658
|
| `pty_observe` | Pane/harness liveness, native process identity, state, and activity | `session_id`, `cursor?` |
|
|
659
659
|
| `agent_launch` | Canonical agent launch; harness and model are independent | `harness`, `prompt?`, `model?`, `reasoning_effort?`, `fast?`, `cwd?`, `write_scope?`, `trust_project?`, `env_vars?`, `throughline_source_session?`, `throughline_supplement_file?` |
|
|
660
660
|
| `agent_auth` | 公式CLIの認証を開始・確認・取消し、公式URL・device code・入力待ちを返す | `harness`, `action`, `session_id?`, `cwd?`, `env_vars?`, `relogin?`, `expected_binding?`, `response?` |
|
|
661
|
-
| `agent_models` | List the models and reasoning efforts a harness offers now, read from that harness's own catalog without sending a prompt | `harness`, `cwd?`, `include_hidden?` |
|
|
661
|
+
| `agent_models` | List the models and reasoning efforts a harness offers now, read from that harness's own catalog without sending a prompt | `harness`, `cwd?`, `include_hidden?`, `configuration_root?` (claude-code) |
|
|
662
662
|
| `agent_approval` | Inspect a Codex approval and submit a one-time approval or denial | `action`, `session_id`, `approval_choice?`, `observed_prompt_digest?` |
|
|
663
663
|
| `claude_agent` / `codex_agent` / `grok_agent` | Deprecated compatibility aliases (`composer_agent` was removed in 0.41.0; run Composer with `agent_launch` on `cursor-cli`) | legacy launcher arguments |
|
|
664
664
|
| `agent_configure` | Change model/effort/fast in a running Claude, Codex, Grok, or Cursor session without restarting it | `session_id`, `model?`, `reasoning_effort?`, `fast?` |
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Catalog-only Claude config root per configuration root (harness-contracts.md C1-C4).
|
|
2
|
+
// Claude Code writes its served-catalog flag into the root's global config regardless of identity, so seats and logins
|
|
3
|
+
// sharing a root make the model list flap. The catalog runs in its own root that only the catalog writes.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { ensureStateRoot } from "./agent-shared.js";
|
|
8
|
+
import { claudeDefaultConfigRoot } from "./claude-config-root.js";
|
|
9
|
+
const FRESH_MS = 10 * 60_000;
|
|
10
|
+
/**
|
|
11
|
+
* The catalog-only root for the root `env` selects, holding only the root's access token. null when the root has no
|
|
12
|
+
* file credential (macOS Keychain), the env authenticates by token/API key, or the access token is near expiry:
|
|
13
|
+
* the caller then runs on the root itself as before, which lets Claude Code refresh there.
|
|
14
|
+
*/
|
|
15
|
+
export function claudeCatalogRoot(env, now = Date.now()) {
|
|
16
|
+
if (env.CLAUDE_CODE_OAUTH_TOKEN || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN)
|
|
17
|
+
return null;
|
|
18
|
+
const root = env.CLAUDE_CONFIG_DIR || claudeDefaultConfigRoot(env);
|
|
19
|
+
let oauth;
|
|
20
|
+
try {
|
|
21
|
+
oauth = JSON.parse(fs.readFileSync(path.join(root, ".credentials.json"), "utf8"))?.claudeAiOauth;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
if (typeof oauth?.accessToken !== "string" || typeof oauth.expiresAt !== "number" || oauth.expiresAt - now < FRESH_MS)
|
|
27
|
+
return null;
|
|
28
|
+
let real = root;
|
|
29
|
+
try {
|
|
30
|
+
real = fs.realpathSync(root);
|
|
31
|
+
}
|
|
32
|
+
catch { }
|
|
33
|
+
const dir = path.join(ensureStateRoot(), "claude-catalog", createHash("sha256").update(real).digest("hex").slice(0, 16));
|
|
34
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
35
|
+
// The refresh token is single-use: a refresh here would sign the root out, so the copy cannot refresh.
|
|
36
|
+
const { refreshToken: _refresh, ...access } = oauth;
|
|
37
|
+
const tmp = path.join(dir, `.credentials.${randomUUID()}.tmp`);
|
|
38
|
+
fs.writeFileSync(tmp, JSON.stringify({ claudeAiOauth: access }), { mode: 0o600 });
|
|
39
|
+
fs.renameSync(tmp, path.join(dir, ".credentials.json"));
|
|
40
|
+
const digestFile = path.join(dir, "last-catalog.sha256");
|
|
41
|
+
return {
|
|
42
|
+
env: { ...env, CLAUDE_CONFIG_DIR: dir },
|
|
43
|
+
lastDigest: () => { try {
|
|
44
|
+
return fs.readFileSync(digestFile, "utf8");
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
} },
|
|
49
|
+
remember: digest => fs.writeFileSync(digestFile, digest, { mode: 0o600 }),
|
|
50
|
+
};
|
|
51
|
+
}
|
package/dist/core.js
CHANGED
|
@@ -5228,6 +5228,10 @@ export async function authenticateAgent(kind, options) {
|
|
|
5228
5228
|
* promptもturnも送らない。取得不能・形式異常はfallbackせずエラーにする。
|
|
5229
5229
|
*/
|
|
5230
5230
|
export async function listAgentModels(kind, options = {}) {
|
|
5231
|
+
if (options.configuration_root !== undefined && kind !== "claude")
|
|
5232
|
+
throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
|
|
5233
|
+
const claudeEnv = options.configuration_root === undefined ? process.env
|
|
5234
|
+
: withClaudeConfigRoot(process.env, resolveClaudeConfigurationRoot(options.configuration_root));
|
|
5231
5235
|
const cwd = options.cwd ?? process.cwd();
|
|
5232
5236
|
if (!path.isAbsolute(cwd))
|
|
5233
5237
|
throw new AitermError("cwd は絶対パスで指定してください", 2);
|
|
@@ -5237,7 +5241,7 @@ export async function listAgentModels(kind, options = {}) {
|
|
|
5237
5241
|
if (!bin)
|
|
5238
5242
|
throw catalogUnavailable(agentLabel(kind), `${agentLabel(kind)} の CLI が見つかりません`);
|
|
5239
5243
|
switch (kind) {
|
|
5240
|
-
case "claude": return claudeModelChoices(bin, cwd);
|
|
5244
|
+
case "claude": return claudeModelChoices(bin, cwd, claudeEnv);
|
|
5241
5245
|
case "codex": return codexModelChoices(bin, options.include_hidden === true);
|
|
5242
5246
|
case "grok": return grokModelChoices(bin, cwd);
|
|
5243
5247
|
case "cursor": return cursorModelChoices(bin, cwd);
|
package/dist/harnesses/claude.js
CHANGED
|
@@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url";
|
|
|
10
10
|
import { AitermError, AgentAuthenticationPreflightError } from "../errors.js";
|
|
11
11
|
import { modeBitsWorldAccessible } from "../tmux-runtime.js";
|
|
12
12
|
import { runAgentProtocolCommand, spawnAgentControlCommand } from "../agent-resolver.js";
|
|
13
|
+
import { claudeCatalogRoot } from "../claude-catalog-root.js";
|
|
13
14
|
import { catalogInvalid, catalogUnavailable, checkedCatalog, findJsonLine, processSummary } from "../model-catalog.js";
|
|
14
15
|
import { currentUid, writeJson0600, shq, subagentInstruction, AGENT_DEFAULT_PREFACE, writeScopeLaunchNote, agentEventPath, createEmpty0600, writeAgentMetadata, agentLineageFields, assertSessionName, agentsDir, LAUNCH_ID_RE, AGENT_EVENT_TAIL_BYTES, readFileRange, } from "../agent-shared.js";
|
|
15
16
|
export const OPERATION_ID_RE = /^sha256:[0-9a-f]{64}$/;
|
|
@@ -179,6 +180,27 @@ const CLAUDE_ULTRACODE_NOTE = "Claude Codeの--effortが受け付けるsession
|
|
|
179
180
|
* promptは送らず、sessionを保存せず、利用者のhookとMCP serverを起動しない。
|
|
180
181
|
*/
|
|
181
182
|
export async function claudeModelChoices(bin, cwd, env = process.env) {
|
|
183
|
+
// Run in the catalog-only root so other processes writing the shared config cannot flip the list
|
|
184
|
+
// (harness-contracts.md C1-C4). A cold root answers differently until its flag and catalog caches settle.
|
|
185
|
+
let own = claudeCatalogRoot(env);
|
|
186
|
+
if (!own) {
|
|
187
|
+
const shared = await claudeModelChoicesOnce(bin, cwd, env);
|
|
188
|
+
own = claudeCatalogRoot(env);
|
|
189
|
+
if (!own)
|
|
190
|
+
return shared;
|
|
191
|
+
}
|
|
192
|
+
let catalog;
|
|
193
|
+
for (let attempt = 0; attempt < CLAUDE_CATALOG_SETTLE_RUNS; attempt++) {
|
|
194
|
+
catalog = await claudeModelChoicesOnce(bin, cwd, own.env);
|
|
195
|
+
const digest = createHash("sha256").update(JSON.stringify(catalog)).digest("hex");
|
|
196
|
+
if (digest === own.lastDigest())
|
|
197
|
+
return catalog;
|
|
198
|
+
own.remember(digest);
|
|
199
|
+
}
|
|
200
|
+
return catalog;
|
|
201
|
+
}
|
|
202
|
+
const CLAUDE_CATALOG_SETTLE_RUNS = 4;
|
|
203
|
+
async function claudeModelChoicesOnce(bin, cwd, env) {
|
|
182
204
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "aiterm-claude-models-"));
|
|
183
205
|
try {
|
|
184
206
|
const settings = path.join(dir, "settings.json");
|
package/dist/index.js
CHANGED
|
@@ -1133,6 +1133,7 @@ export function createAitermServer(options = {}) {
|
|
|
1133
1133
|
harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).describe("候補を取得するharness"),
|
|
1134
1134
|
cwd: z.string().nullish().describe("CLIを実行する作業ディレクトリ(絶対パス・任意)。project設定で候補が変わるharness向け"),
|
|
1135
1135
|
include_hidden: z.boolean().optional().describe("Codexが一覧で隠すmodelも返す(既定false)。他のharnessには隠すmodelが無い"),
|
|
1136
|
+
configuration_root: z.string().min(1).optional().describe("claude-code harnessだけ。一覧を読むアカウントの設定root(CLAUDE_CONFIG_DIR)。受ける範囲はagent_launchと同じ(既定のroot、またはAITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下)。他はAGENT_CONFIGURATION_ROOT_REJECTED。省略は既定のroot"),
|
|
1136
1137
|
},
|
|
1137
1138
|
outputSchema: {
|
|
1138
1139
|
schema: z.literal("aiterm.agent-models.v1"),
|
|
@@ -1145,9 +1146,9 @@ export function createAitermServer(options = {}) {
|
|
|
1145
1146
|
fast_unavailable: fastModeFailureSchema.nullable().optional().describe("このアカウント・この端末では、どのmodelでもfastを使えない時の訳(harnessが先に答えられる時だけ。今はClaude Code)。使える・分からない時はnull"),
|
|
1146
1147
|
models: z.array(agentModelChoiceSchema),
|
|
1147
1148
|
},
|
|
1148
|
-
}, async ({ harness, cwd, include_hidden }) => {
|
|
1149
|
+
}, async ({ harness, cwd, include_hidden, configuration_root }) => {
|
|
1149
1150
|
try {
|
|
1150
|
-
const catalog = await core.listAgentModels(kindForHarness(harness), { cwd, include_hidden });
|
|
1151
|
+
const catalog = await core.listAgentModels(kindForHarness(harness), { cwd, include_hidden, configuration_root });
|
|
1151
1152
|
const result = agentModelsResult(harness, catalog);
|
|
1152
1153
|
return {
|
|
1153
1154
|
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// authorize-key (remote-terminal.md R14): one password-only SSH login that appends the terminal's held public key
|
|
2
|
+
// to ~/.ssh/authorized_keys. The password lives only in this process's memory and one askpass socket connection.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import * as net from "node:net";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { RemoteTerminalError, agentAlive, binding, bindingStatus, classifySshFailure, credentialPublicKeyFile, publicKey, readCredential, sshEnvironment } from "./remote-terminal.js";
|
|
9
|
+
export const ASKPASS_SOCKET_ENV = "AITERM_ASKPASS_SOCKET";
|
|
10
|
+
const PUBLIC_KEY = /^[A-Za-z0-9@.-]+ [A-Za-z0-9+/]+={0,3}$/;
|
|
11
|
+
const MAX_PASSWORD_BYTES = 1023; // ssh reads at most 1024 bytes from askpass, cut at the first CR/LF
|
|
12
|
+
/** The key this binding authenticates with afterwards: native key file, or the one credential-load holds. */
|
|
13
|
+
function heldPublicKey(b) {
|
|
14
|
+
let line;
|
|
15
|
+
if (b.key_file) {
|
|
16
|
+
const key = publicKey(b.key_file);
|
|
17
|
+
if ("reason" in key)
|
|
18
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
|
|
19
|
+
line = key.line;
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
const loaded = readCredential(b.ref);
|
|
23
|
+
if (!loaded || !agentAlive(loaded.socket))
|
|
24
|
+
throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the terminal's credential is not loaded; resolve the handle and run credential-load first");
|
|
25
|
+
try {
|
|
26
|
+
line = fs.readFileSync(credentialPublicKeyFile(b.ref), "utf8").trim().split(/\s+/).slice(0, 2).join(" ");
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the loaded credential has no public key; run credential-load again");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (!PUBLIC_KEY.test(line))
|
|
33
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the held public key is malformed");
|
|
34
|
+
return line;
|
|
35
|
+
}
|
|
36
|
+
/** Checks that need no password: done before the caller's stdin is read. */
|
|
37
|
+
export function prepareAuthorization(ref) {
|
|
38
|
+
const b = binding(ref);
|
|
39
|
+
const status = bindingStatus(ref);
|
|
40
|
+
if (!status.trust.available)
|
|
41
|
+
throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted", "confirm the new host key");
|
|
42
|
+
return { b, key: heldPublicKey(b) };
|
|
43
|
+
}
|
|
44
|
+
/** Raw stdin bytes, nothing removed. Values ssh's askpass cannot carry exactly are refused, never altered. */
|
|
45
|
+
export function checkPassword(password) {
|
|
46
|
+
let text = "";
|
|
47
|
+
try {
|
|
48
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(password);
|
|
49
|
+
}
|
|
50
|
+
catch { /* invalid below */ }
|
|
51
|
+
// eslint-disable-next-line no-control-regex
|
|
52
|
+
if (password.length === 0 || password.length > MAX_PASSWORD_BYTES || !text || /[\x00\r\n]/.test(text))
|
|
53
|
+
throw new RemoteTerminalError("PASSWORD_INVALID", "the password must be 1-1023 bytes of UTF-8 on stdin without NUL, CR or LF (no trailing newline)");
|
|
54
|
+
}
|
|
55
|
+
export function authorizedKeysScript(key) {
|
|
56
|
+
const [type, blob] = key.split(" ");
|
|
57
|
+
return [
|
|
58
|
+
"umask 077",
|
|
59
|
+
`k='${key}'; t='${type}'; b='${blob}'`,
|
|
60
|
+
'd="$HOME/.ssh"; f="$d/authorized_keys"',
|
|
61
|
+
'mkdir -p "$d" 2>/dev/null && chmod 700 "$d" 2>/dev/null || exit 21',
|
|
62
|
+
'if [ ! -e "$f" ]; then : > "$f" 2>/dev/null || exit 22; fi',
|
|
63
|
+
'chmod 600 "$f" 2>/dev/null || exit 22',
|
|
64
|
+
// Same key type and blob anywhere on a line: options and comments do not matter.
|
|
65
|
+
`if awk -v t="$t" -v b="$b" '{for(i=1;i<NF;i++) if($i==t && $(i+1)==b) f=1} END{exit f?0:1}' "$f" 2>/dev/null; then echo "AITERM_AUTHORIZE ALREADY_AUTHORIZED"; exit 0; fi`,
|
|
66
|
+
'if [ -s "$f" ] && [ -n "$(tail -c 1 "$f")" ]; then printf \'\\n\' >> "$f" || exit 22; fi',
|
|
67
|
+
'printf \'%s\\n\' "$k" >> "$f" || exit 22',
|
|
68
|
+
'echo "AITERM_AUTHORIZE AUTHORIZED"',
|
|
69
|
+
"",
|
|
70
|
+
].join("\n");
|
|
71
|
+
}
|
|
72
|
+
export function passwordSshArguments(b) {
|
|
73
|
+
return ["-F", "/dev/null", "-T", "-o", "BatchMode=no", "-o", "StrictHostKeyChecking=yes",
|
|
74
|
+
"-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
|
|
75
|
+
...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
|
|
76
|
+
"-o", "PubkeyAuthentication=no", "-o", "IdentityAgent=none", "-o", "IdentitiesOnly=yes", "-o", "IdentityFile=none",
|
|
77
|
+
"-o", "PreferredAuthentications=password", "-o", "PasswordAuthentication=yes", "-o", "KbdInteractiveAuthentication=no",
|
|
78
|
+
"-o", "GSSAPIAuthentication=no", "-o", "HostbasedAuthentication=no", "-o", "NumberOfPasswordPrompts=1",
|
|
79
|
+
"-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15",
|
|
80
|
+
"-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, "/bin/sh -s"];
|
|
81
|
+
}
|
|
82
|
+
const shq = (value) => `'${value.replace(/'/g, "'\\''")}'`;
|
|
83
|
+
export async function authorizeKey(prepared, password) {
|
|
84
|
+
const dir = fs.mkdtempSync(path.join("/tmp", "aiterm-ap-"));
|
|
85
|
+
let served = 0;
|
|
86
|
+
const server = net.createServer(connection => { served += 1; if (served === 1)
|
|
87
|
+
connection.end(password);
|
|
88
|
+
else
|
|
89
|
+
connection.end(); });
|
|
90
|
+
try {
|
|
91
|
+
checkPassword(password);
|
|
92
|
+
fs.chmodSync(dir, 0o700);
|
|
93
|
+
const socket = path.join(dir, "s");
|
|
94
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(socket, resolve); });
|
|
95
|
+
const helper = path.join(dir, "askpass");
|
|
96
|
+
const cli = fileURLToPath(new URL("./remote-terminal-cli.js", import.meta.url));
|
|
97
|
+
fs.writeFileSync(helper, `#!/bin/sh\nexec ${shq(process.execPath)} ${shq(cli)} askpass "$@"\n`, { mode: 0o700 });
|
|
98
|
+
const env = { ...sshEnvironment(), SSH_ASKPASS: helper, SSH_ASKPASS_REQUIRE: "force", DISPLAY: process.env.DISPLAY ?? "aiterm:0", [ASKPASS_SOCKET_ENV]: socket };
|
|
99
|
+
const run = await new Promise((resolve, reject) => {
|
|
100
|
+
const child = spawn("ssh", passwordSshArguments(prepared.b), { env, stdio: ["pipe", "pipe", "pipe"] });
|
|
101
|
+
let stdout = "", stderr = "";
|
|
102
|
+
const timer = setTimeout(() => child.kill(), 120_000);
|
|
103
|
+
child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
|
|
104
|
+
child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-4000); });
|
|
105
|
+
child.on("error", reject);
|
|
106
|
+
child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
|
|
107
|
+
child.stdin.on("error", () => { });
|
|
108
|
+
child.stdin.end(authorizedKeysScript(prepared.key));
|
|
109
|
+
});
|
|
110
|
+
const marker = /AITERM_AUTHORIZE (AUTHORIZED|ALREADY_AUTHORIZED)/.exec(run.stdout)?.[1];
|
|
111
|
+
if (run.code === 0 && marker)
|
|
112
|
+
return { schema: "aiterm.remote-key-authorization.v1", ref: prepared.b.ref, result: marker };
|
|
113
|
+
if (run.code === 21 || run.code === 22)
|
|
114
|
+
throw new RemoteTerminalError("AUTHORIZED_KEYS_WRITE_FAILED", "~/.ssh/authorized_keys could not be written on the terminal");
|
|
115
|
+
const denied = /Permission denied \(([^)]*)\)/.exec(run.stderr);
|
|
116
|
+
if (denied) {
|
|
117
|
+
if (served > 0)
|
|
118
|
+
throw new RemoteTerminalError("PASSWORD_REJECTED", "the terminal rejected the password");
|
|
119
|
+
if (!denied[1].split(",").includes("password"))
|
|
120
|
+
throw new RemoteTerminalError("PASSWORD_AUTH_DISABLED", "the terminal does not offer password login");
|
|
121
|
+
throw new RemoteTerminalError("AUTH_FAILED", "the password could not be offered to the terminal");
|
|
122
|
+
}
|
|
123
|
+
if (run.code === 255) {
|
|
124
|
+
const f = classifySshFailure(run.stderr);
|
|
125
|
+
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
126
|
+
}
|
|
127
|
+
throw new RemoteTerminalError("COMMAND_FAILED", "authorized_keys could not be updated on the terminal");
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
password.fill(0);
|
|
131
|
+
server.close();
|
|
132
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** The SSH_ASKPASS helper: answer a password prompt once from the parent's socket, nothing else. */
|
|
136
|
+
export function askpass(prompt, socket) {
|
|
137
|
+
if (!socket || !/password/i.test(prompt) || /passphrase|yes\/no/i.test(prompt))
|
|
138
|
+
process.exit(1);
|
|
139
|
+
const chunks = [];
|
|
140
|
+
const connection = net.createConnection(socket);
|
|
141
|
+
connection.on("data", (chunk) => chunks.push(chunk));
|
|
142
|
+
connection.on("error", () => process.exit(1));
|
|
143
|
+
connection.on("end", () => {
|
|
144
|
+
const value = Buffer.concat(chunks);
|
|
145
|
+
if (value.length === 0)
|
|
146
|
+
process.exit(1);
|
|
147
|
+
process.stdout.write(Buffer.concat([value, Buffer.from("\n")]), () => { value.fill(0); process.exit(0); });
|
|
148
|
+
});
|
|
149
|
+
}
|
package/dist/remote-contract.js
CHANGED
|
@@ -54,6 +54,6 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
|
|
|
54
54
|
"HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
|
|
55
55
|
"HOST_KEY_MISMATCH / HOST_TRUST_MISSING = the terminal's host key is not the trusted one: the Owner must confirm the new host key; do not retry. " +
|
|
56
56
|
"CREDENTIAL_REQUIRED / CREDENTIAL_NOT_LOADED = this terminal's key comes from a credential handle that the registry must load first; never paste a key anywhere. " +
|
|
57
|
-
"AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. " +
|
|
57
|
+
"AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. CONNECTION_REFUSED = the terminal refused the SSH connection (SSH may be off there); try later. " +
|
|
58
58
|
"REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
|
|
59
59
|
"SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready; launch again later. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code.";
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Terminal-side fixed path operations (remote-terminal.md R15). Runs on the terminal as the SSH user.
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { RemoteTerminalError } from "./remote-terminal.js";
|
|
5
|
+
const MISSING = { schema: "aiterm.remote-path.v1", exists: false, directory: false, writable: false };
|
|
6
|
+
const denied = (code) => code === "EACCES" || code === "EPERM";
|
|
7
|
+
const notPermitted = () => new RemoteTerminalError("FOLDER_NOT_PERMITTED", "the folder cannot be used by the terminal's SSH user (privacy consent, ACL or permissions)");
|
|
8
|
+
export function checkRemotePath(value) {
|
|
9
|
+
// eslint-disable-next-line no-control-regex
|
|
10
|
+
if (typeof value !== "string" || !path.posix.isAbsolute(value) || /[\x00-\x1f\x7f]/.test(value) || Buffer.byteLength(value) > 4096)
|
|
11
|
+
throw new RemoteTerminalError("PATH_INVALID", "path must be an absolute path without control characters");
|
|
12
|
+
}
|
|
13
|
+
function errno(error) { return error?.code; }
|
|
14
|
+
/** Can this directory be listed? A privacy-protected folder (macOS TCC) refuses it with EPERM. */
|
|
15
|
+
function listable(dir) {
|
|
16
|
+
try {
|
|
17
|
+
fs.opendirSync(dir).closeSync();
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (denied(errno(error)))
|
|
22
|
+
return false;
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** writable = a probe directory could actually be created and removed now. */
|
|
27
|
+
function writable(dir) {
|
|
28
|
+
let probe;
|
|
29
|
+
try {
|
|
30
|
+
probe = fs.mkdtempSync(path.join(dir, ".aiterm-write-probe-"));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
fs.rmdirSync(probe);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
export function inspectPath(target) {
|
|
39
|
+
checkRemotePath(target);
|
|
40
|
+
let stat;
|
|
41
|
+
try {
|
|
42
|
+
stat = fs.statSync(target);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
const code = errno(error);
|
|
46
|
+
if (denied(code))
|
|
47
|
+
throw notPermitted();
|
|
48
|
+
if (code !== "ENOENT" && code !== "ENOTDIR")
|
|
49
|
+
throw new RemoteTerminalError("PATH_UNAVAILABLE", `the path cannot be inspected (${code ?? "unknown"})`);
|
|
50
|
+
// An inaccessible parent must not read as a missing folder.
|
|
51
|
+
for (let parent = path.dirname(target);; parent = path.dirname(parent)) {
|
|
52
|
+
let parentStat = null;
|
|
53
|
+
try {
|
|
54
|
+
parentStat = fs.statSync(parent);
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
if (denied(errno(e)))
|
|
58
|
+
throw notPermitted();
|
|
59
|
+
}
|
|
60
|
+
if (parentStat) {
|
|
61
|
+
if (parentStat.isDirectory() && !listable(parent))
|
|
62
|
+
throw notPermitted();
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
if (parent === path.dirname(parent))
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
return MISSING;
|
|
69
|
+
}
|
|
70
|
+
if (!stat.isDirectory())
|
|
71
|
+
return { schema: "aiterm.remote-path.v1", exists: true, directory: false, writable: false };
|
|
72
|
+
if (!listable(target))
|
|
73
|
+
throw notPermitted();
|
|
74
|
+
return { schema: "aiterm.remote-path.v1", exists: true, directory: true, writable: writable(target) };
|
|
75
|
+
}
|
|
76
|
+
export function makeDirectory(target) {
|
|
77
|
+
checkRemotePath(target);
|
|
78
|
+
try {
|
|
79
|
+
fs.mkdirSync(target, { recursive: true });
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (denied(errno(error)))
|
|
83
|
+
throw notPermitted(); /* a file in the way shows in the inspection */
|
|
84
|
+
}
|
|
85
|
+
return inspectPath(target);
|
|
86
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS terminal,
|
|
2
|
+
// before any terminal MCP exists. Runs over the binding's trusted key SSH; the terminal fetches the release assets.
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { RemoteTerminalError, bindingStatus, classifySshFailure, sshEnvironment, trustedSshArguments } from "./remote-terminal.js";
|
|
7
|
+
import { verifySetupRuntime } from "./setup.js";
|
|
8
|
+
const pkg = createRequire(import.meta.url)("../package.json");
|
|
9
|
+
export const RUNTIME_RELEASE_BASE = "https://github.com/kitepon/aiterm-mcp/releases/download";
|
|
10
|
+
/** The terminal-side bootstrap, run as `/bin/sh -s -- VERSION BASE`. Prints one result line. */
|
|
11
|
+
export const PROVISION_SCRIPT = String.raw `set -u
|
|
12
|
+
V="$1"; BASE="$2"
|
|
13
|
+
fail() { echo "AITERM_PROVISION_ERROR $1"; exit 3; }
|
|
14
|
+
[ "$(uname -s)" = Darwin ] || fail PROVISION_PLATFORM_UNSUPPORTED
|
|
15
|
+
case "$(uname -m)" in
|
|
16
|
+
arm64) A=arm64 ;;
|
|
17
|
+
x86_64) if [ "$(sysctl -in hw.optional.arm64 2>/dev/null)" = 1 ]; then A=arm64; else A=x64; fi ;;
|
|
18
|
+
*) fail PROVISION_PLATFORM_UNSUPPORTED ;;
|
|
19
|
+
esac
|
|
20
|
+
NAME="aiterm-runtime-$V-darwin-$A"
|
|
21
|
+
ROOT="$HOME/.aiterm/runtime"
|
|
22
|
+
mkdir -p "$ROOT" 2>/dev/null && chmod 700 "$HOME/.aiterm" "$ROOT" 2>/dev/null || fail RUNTIME_DIR_UNAVAILABLE
|
|
23
|
+
smoke() { "$1/bin/aiterm-remote-terminal" runtime-smoke --expect-version "$V" >/dev/null 2>&1 </dev/null; }
|
|
24
|
+
LOCK="$ROOT/.lock"
|
|
25
|
+
if ! mkdir "$LOCK" 2>/dev/null; then
|
|
26
|
+
p=$(cat "$LOCK/pid" 2>/dev/null)
|
|
27
|
+
if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then fail PROVISION_BUSY; fi
|
|
28
|
+
rm -rf "$LOCK"; mkdir "$LOCK" 2>/dev/null || fail PROVISION_BUSY
|
|
29
|
+
fi
|
|
30
|
+
echo $$ > "$LOCK/pid"
|
|
31
|
+
STAGE="$ROOT/.stage-$$"
|
|
32
|
+
trap 'rm -rf "$STAGE" "$LOCK"' EXIT
|
|
33
|
+
if [ "$(cat "$ROOT/current/RUNTIME" 2>/dev/null)" = "$NAME" ] && smoke "$ROOT/current"; then
|
|
34
|
+
echo "AITERM_PROVISION ALREADY_CURRENT $V $A"; exit 0
|
|
35
|
+
fi
|
|
36
|
+
rm -rf "$ROOT"/.stage-*
|
|
37
|
+
mkdir -p "$STAGE/x" || fail RUNTIME_DIR_UNAVAILABLE
|
|
38
|
+
get() { curl -fsSL --retry 2 --connect-timeout 20 -o "$STAGE/$1" "$BASE/v$V/$1"; rc=$?; [ $rc = 0 ] && return 0; [ $rc = 22 ] && fail RUNTIME_ARTIFACT_UNAVAILABLE; fail RUNTIME_DOWNLOAD_FAILED; }
|
|
39
|
+
get "aiterm-runtime-$V-SHA256SUMS"
|
|
40
|
+
get "$NAME.tar.gz"
|
|
41
|
+
want=$(awk -v n="$NAME.tar.gz" '$2==n || $2=="*"n {print $1}' "$STAGE/aiterm-runtime-$V-SHA256SUMS")
|
|
42
|
+
if command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$STAGE/$NAME.tar.gz" | cut -d' ' -f1); else got=$(sha256sum "$STAGE/$NAME.tar.gz" | cut -d' ' -f1); fi
|
|
43
|
+
[ -n "$want" ] && [ "$want" = "$got" ] || fail RUNTIME_VERIFY_FAILED
|
|
44
|
+
tar -xzf "$STAGE/$NAME.tar.gz" -C "$STAGE/x" 2>/dev/null || fail RUNTIME_EXTRACT_FAILED
|
|
45
|
+
N="$STAGE/x/$NAME"
|
|
46
|
+
[ "$(cat "$N/RUNTIME" 2>/dev/null)" = "$NAME" ] || fail RUNTIME_VERIFY_FAILED
|
|
47
|
+
smoke "$N" || fail RUNTIME_SMOKE_FAILED
|
|
48
|
+
# Running seats and tmux servers are not touched; the previous runtime stays until the next provision.
|
|
49
|
+
rm -rf "$ROOT/previous"
|
|
50
|
+
if [ -d "$ROOT/current" ]; then mv "$ROOT/current" "$ROOT/previous" || fail RUNTIME_ACTIVATE_FAILED; fi
|
|
51
|
+
if ! mv "$N" "$ROOT/current"; then
|
|
52
|
+
[ -d "$ROOT/previous" ] && mv "$ROOT/previous" "$ROOT/current"
|
|
53
|
+
fail RUNTIME_ACTIVATE_FAILED
|
|
54
|
+
fi
|
|
55
|
+
echo "AITERM_PROVISION PROVISIONED $V $A"
|
|
56
|
+
`;
|
|
57
|
+
export function parseProvisionOutput(stdout) {
|
|
58
|
+
const ok = /^AITERM_PROVISION (PROVISIONED|ALREADY_CURRENT) (\S+) /m.exec(stdout);
|
|
59
|
+
if (ok)
|
|
60
|
+
return { result: ok[1], version: ok[2] };
|
|
61
|
+
const error = /^AITERM_PROVISION_ERROR ([A-Z_]+)$/m.exec(stdout);
|
|
62
|
+
return error ? { code: error[1] } : null;
|
|
63
|
+
}
|
|
64
|
+
export async function provision(ref, version = pkg.version) {
|
|
65
|
+
if (!/^\d+\.\d+\.\d+$/.test(version))
|
|
66
|
+
throw new RemoteTerminalError("VERSION_INVALID", "the runtime version must be x.y.z");
|
|
67
|
+
const status = bindingStatus(ref);
|
|
68
|
+
if (!status.trust.available)
|
|
69
|
+
throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted", "confirm the new host key");
|
|
70
|
+
if (status.credential.provider === "aiterm.native-ssh-key.v1" && !status.credential.available)
|
|
71
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
|
|
72
|
+
// Throws CREDENTIAL_NOT_LOADED for a keyless binding whose key is not loaded.
|
|
73
|
+
const args = trustedSshArguments(ref, `/bin/sh -s -- ${version} ${RUNTIME_RELEASE_BASE}`, null);
|
|
74
|
+
const run = await new Promise((resolve, reject) => {
|
|
75
|
+
const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
|
|
76
|
+
let stdout = "", stderr = "";
|
|
77
|
+
const timer = setTimeout(() => child.kill(), 1_200_000);
|
|
78
|
+
child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
|
|
79
|
+
child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-4000); });
|
|
80
|
+
child.on("error", reject);
|
|
81
|
+
child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
|
|
82
|
+
child.stdin.on("error", () => { });
|
|
83
|
+
child.stdin.end(PROVISION_SCRIPT);
|
|
84
|
+
});
|
|
85
|
+
const parsed = parseProvisionOutput(run.stdout);
|
|
86
|
+
if (parsed && "result" in parsed && run.code === 0)
|
|
87
|
+
return { schema: "aiterm.remote-provision.v1", ref, result: parsed.result, version: parsed.version };
|
|
88
|
+
if (parsed && "code" in parsed)
|
|
89
|
+
throw new RemoteTerminalError(parsed.code, `provisioning the terminal failed (${parsed.code})`);
|
|
90
|
+
if (run.code === 255) {
|
|
91
|
+
const f = classifySshFailure(run.stderr);
|
|
92
|
+
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
93
|
+
}
|
|
94
|
+
throw new RemoteTerminalError("PROVISION_FAILED", "the terminal returned no provisioning result");
|
|
95
|
+
}
|
|
96
|
+
/** runtime-smoke on the terminal: this runtime's version, its tmux, and the setup probe through its own aiterm-mcp. */
|
|
97
|
+
export async function runtimeSmoke(expectVersion) {
|
|
98
|
+
if (pkg.version !== expectVersion)
|
|
99
|
+
throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", `runtime is ${pkg.version}, expected ${expectVersion}`);
|
|
100
|
+
const tmux = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 10_000 });
|
|
101
|
+
if (tmux.status !== 0)
|
|
102
|
+
throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", "tmux does not run");
|
|
103
|
+
await verifySetupRuntime({ command: process.execPath, args: [fileURLToPath(new URL("./index.js", import.meta.url))] });
|
|
104
|
+
return { schema: "aiterm.runtime-smoke.v1", version: pkg.version, tmux: tmux.stdout.trim() };
|
|
105
|
+
}
|
|
@@ -4,15 +4,20 @@
|
|
|
4
4
|
// serve stdio MCP for one bound connection, spawned by BellTeam terminals
|
|
5
5
|
// credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key (key bytes on stdin; one JSON receipt line)
|
|
6
6
|
// transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
|
|
7
|
+
// authorize-key --ref R (login password on stdin until EOF; R14) provision --ref R (macOS runtime; R16)
|
|
8
|
+
// path-status|make-dir --path P | --path-base64 B (on the terminal; R15) runtime-smoke --expect-version V (on the terminal)
|
|
7
9
|
import { realpathSync } from "node:fs";
|
|
8
10
|
import { fileURLToPath } from "node:url";
|
|
9
11
|
import { createRequire } from "node:module";
|
|
10
12
|
import { z } from "zod";
|
|
11
13
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
12
14
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
13
|
-
import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
|
|
15
|
+
import { REMOTE_COMMAND_OPS, RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
|
|
14
16
|
import { readCompletedTranscript } from "./transcript-read.js";
|
|
15
17
|
import { credentialHandleSchema } from "./remote-contract.js";
|
|
18
|
+
import { inspectPath, makeDirectory } from "./remote-path.js";
|
|
19
|
+
import { ASKPASS_SOCKET_ENV, askpass, authorizeKey, prepareAuthorization } from "./remote-authorize.js";
|
|
20
|
+
import { provision, runtimeSmoke } from "./remote-provision.js";
|
|
16
21
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
17
22
|
function option(args, name) {
|
|
18
23
|
const at = args.indexOf(name);
|
|
@@ -26,15 +31,26 @@ function errorDto(error, schema) {
|
|
|
26
31
|
return { schema, code, message };
|
|
27
32
|
}
|
|
28
33
|
function oneShot(run, errorSchema) {
|
|
34
|
+
const fail = (error) => { process.stdout.write(`${JSON.stringify(errorDto(error, errorSchema))}\n`); process.exit(2); };
|
|
29
35
|
try {
|
|
30
|
-
process.stdout.write(`${JSON.stringify(
|
|
31
|
-
process.exit(0);
|
|
36
|
+
Promise.resolve(run()).then(value => { process.stdout.write(`${JSON.stringify(value)}\n`); process.exit(0); }, fail);
|
|
32
37
|
}
|
|
33
38
|
catch (error) {
|
|
34
|
-
|
|
35
|
-
process.exit(2);
|
|
39
|
+
fail(error);
|
|
36
40
|
}
|
|
37
41
|
}
|
|
42
|
+
function readStdin() {
|
|
43
|
+
return new Promise(resolve => {
|
|
44
|
+
const chunks = [];
|
|
45
|
+
process.stdin.on("data", (chunk) => chunks.push(chunk));
|
|
46
|
+
process.stdin.on("end", () => { const all = Buffer.concat(chunks); for (const chunk of chunks)
|
|
47
|
+
chunk.fill(0); resolve(all); });
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function pathArgument(rest) {
|
|
51
|
+
const encoded = option(rest, "--path-base64");
|
|
52
|
+
return encoded !== undefined ? Buffer.from(encoded, "base64").toString("utf8") : option(rest, "--path") ?? "";
|
|
53
|
+
}
|
|
38
54
|
function serve() {
|
|
39
55
|
const server = new McpServer({ name: "aiterm-remote-terminal", version: pkg.version });
|
|
40
56
|
let connection = null;
|
|
@@ -93,8 +109,8 @@ function serve() {
|
|
|
93
109
|
});
|
|
94
110
|
server.registerTool("remote_terminal_command", {
|
|
95
111
|
description: "Fixed Claude Code setup operation on the terminal",
|
|
96
|
-
inputSchema: { op: z.enum(
|
|
97
|
-
}, guarded(({ op }) => bound().command(op)));
|
|
112
|
+
inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional() },
|
|
113
|
+
}, guarded(({ op, path }) => bound().command(op, path)));
|
|
98
114
|
server.registerTool("remote_terminal_close", { description: "Close the bound connection and exit", inputSchema: {} }, guarded(async () => { const result = connection ? await connection.close() : { closed: true }; setTimeout(() => process.exit(0), 100); return result; }));
|
|
99
115
|
server.connect(new StdioServerTransport()).catch(error => { console.error("aiterm-remote-terminal fatal:", error); process.exit(1); });
|
|
100
116
|
}
|
|
@@ -124,6 +140,22 @@ export function main(args) {
|
|
|
124
140
|
});
|
|
125
141
|
return;
|
|
126
142
|
}
|
|
143
|
+
if (command === "authorize-key")
|
|
144
|
+
return oneShot(() => {
|
|
145
|
+
// Trust and the held key are checked before stdin is read (R14).
|
|
146
|
+
const prepared = prepareAuthorization(option(rest, "--ref") ?? "");
|
|
147
|
+
return readStdin().then(password => authorizeKey(prepared, password));
|
|
148
|
+
}, "aiterm.remote-binding-error.v1");
|
|
149
|
+
if (command === "askpass")
|
|
150
|
+
return askpass(rest.join(" "), process.env[ASKPASS_SOCKET_ENV]);
|
|
151
|
+
if (command === "provision")
|
|
152
|
+
return oneShot(() => provision(option(rest, "--ref") ?? ""), "aiterm.remote-binding-error.v1");
|
|
153
|
+
if (command === "path-status")
|
|
154
|
+
return oneShot(() => inspectPath(pathArgument(rest)), "aiterm.remote-binding-error.v1");
|
|
155
|
+
if (command === "make-dir")
|
|
156
|
+
return oneShot(() => makeDirectory(pathArgument(rest)), "aiterm.remote-binding-error.v1");
|
|
157
|
+
if (command === "runtime-smoke")
|
|
158
|
+
return oneShot(() => runtimeSmoke(option(rest, "--expect-version") ?? ""), "aiterm.remote-binding-error.v1");
|
|
127
159
|
if (command === "trust-confirm")
|
|
128
160
|
return oneShot(() => confirmHostKey(option(rest, "--ref") ?? "", option(rest, "--fingerprint") ?? ""), "aiterm.remote-binding-error.v1");
|
|
129
161
|
if (command === "transcript-read")
|
|
@@ -131,7 +163,7 @@ export function main(args) {
|
|
|
131
163
|
const id = option(rest, "--cursor-session"), offset = option(rest, "--offset"), max = option(rest, "--max-bytes");
|
|
132
164
|
return readCompletedTranscript(option(rest, "--session") ?? "", id ? { claudeSessionId: id, offset: Number(offset) } : null, max ? Number(max) : undefined);
|
|
133
165
|
}, "aiterm.transcript-read-error.v1");
|
|
134
|
-
process.stderr.write("usage: aiterm-remote-terminal serve|status|register|trust-confirm|transcript-read\n");
|
|
166
|
+
process.stderr.write("usage: aiterm-remote-terminal serve|status|register|trust-confirm|credential-load|authorize-key|provision|transcript-read|path-status|make-dir|runtime-smoke\n");
|
|
135
167
|
process.exit(64);
|
|
136
168
|
}
|
|
137
169
|
let entry = false;
|
package/dist/remote-terminal.js
CHANGED
|
@@ -12,6 +12,7 @@ import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/s
|
|
|
12
12
|
import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
|
|
13
13
|
import { posixCommand } from "./remote.js";
|
|
14
14
|
import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
|
|
15
|
+
import { checkRemotePath } from "./remote-path.js";
|
|
15
16
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
16
17
|
export class RemoteTerminalError extends Error {
|
|
17
18
|
code;
|
|
@@ -60,7 +61,7 @@ function readStore() {
|
|
|
60
61
|
throw new RemoteTerminalError("BINDING_STORE_UNREADABLE", "the binding store is not valid");
|
|
61
62
|
}
|
|
62
63
|
}
|
|
63
|
-
function binding(ref) {
|
|
64
|
+
export function binding(ref) {
|
|
64
65
|
if (!REF.test(ref))
|
|
65
66
|
throw new RemoteTerminalError("REF_INVALID", "ref must be a UUID");
|
|
66
67
|
const found = readStore().find(item => item.ref === ref);
|
|
@@ -94,7 +95,7 @@ export function registerBinding(input) {
|
|
|
94
95
|
function keyFingerprint(blob) {
|
|
95
96
|
return `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`;
|
|
96
97
|
}
|
|
97
|
-
function publicKey(keyFile) {
|
|
98
|
+
export function publicKey(keyFile) {
|
|
98
99
|
if (!fs.existsSync(keyFile))
|
|
99
100
|
return { reason: "KEY_MISSING" };
|
|
100
101
|
// Empty passphrase only: a passphrase-protected key cannot be used without a prompt.
|
|
@@ -150,8 +151,12 @@ export function confirmHostKey(ref, fingerprint) {
|
|
|
150
151
|
throw new RemoteTerminalError("FINGERPRINT_INVALID", "fingerprint must be SHA256:<base64>");
|
|
151
152
|
const b = binding(ref);
|
|
152
153
|
const scan = spawnSync("ssh-keyscan", ["-T", "10", "-p", String(b.target.port), b.target.host], { encoding: "utf8", timeout: 20_000 });
|
|
153
|
-
const
|
|
154
|
-
.
|
|
154
|
+
const keys = (scan.stdout ?? "").split("\n").filter(line => line && !line.startsWith("#")).map(line => line.trim().split(/\s+/))
|
|
155
|
+
.filter(fields => fields.length >= 3);
|
|
156
|
+
// No key at all is an asleep/offline terminal, not another machine.
|
|
157
|
+
if (keys.length === 0)
|
|
158
|
+
throw new RemoteTerminalError("UNREACHABLE", "the terminal presented no host key (asleep, offline or not accepting SSH)");
|
|
159
|
+
const matched = keys.find(fields => keyFingerprint(Buffer.from(fields[2], "base64")) === fingerprint);
|
|
155
160
|
if (!matched)
|
|
156
161
|
throw new RemoteTerminalError("HOST_KEY_FINGERPRINT_MISMATCH", "the terminal did not present the confirmed host key");
|
|
157
162
|
const name = knownHostName(b);
|
|
@@ -171,7 +176,9 @@ export function classifySshFailure(stderr) {
|
|
|
171
176
|
return { code: "AUTH_FAILED", message: "the terminal refused the key" };
|
|
172
177
|
if (/aiterm-mcp: (command )?not found|aiterm-mcp: No such file/i.test(stderr))
|
|
173
178
|
return { code: "REMOTE_AITERM_UNAVAILABLE", message: "Aiterm is not installed on the terminal" };
|
|
174
|
-
if (/Connection refused
|
|
179
|
+
if (/Connection refused/i.test(stderr))
|
|
180
|
+
return { code: "CONNECTION_REFUSED", message: "the terminal refused the SSH connection" };
|
|
181
|
+
if (/timed out|No route to host|Network is unreachable|Could not resolve|Connection closed|Connection reset/i.test(stderr))
|
|
175
182
|
return { code: "UNREACHABLE", message: "the terminal cannot be reached" };
|
|
176
183
|
return { code: "CONNECTION_FAILED", message: "the SSH connection failed" };
|
|
177
184
|
}
|
|
@@ -216,7 +223,7 @@ export function sshArguments(b, agentSocket, identityFile, remoteCommand) {
|
|
|
216
223
|
"-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4",
|
|
217
224
|
"-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, remoteCommand];
|
|
218
225
|
}
|
|
219
|
-
function sshEnvironment() {
|
|
226
|
+
export function sshEnvironment() {
|
|
220
227
|
const env = {};
|
|
221
228
|
for (const key of ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR"])
|
|
222
229
|
if (process.env[key] !== undefined)
|
|
@@ -259,6 +266,7 @@ export class SshStdioTransport {
|
|
|
259
266
|
async close() { this.child?.kill(); }
|
|
260
267
|
}
|
|
261
268
|
export const REMOTE_SEAT_TOOLS = new Set(["agent_launch", "pty_send", "pty_observe", "pty_read", "pty_key", "claude_turn", "agent_stop", "pty_close"]);
|
|
269
|
+
export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir"];
|
|
262
270
|
const COMMANDS = {
|
|
263
271
|
claude_version: "claude --version",
|
|
264
272
|
claude_install: "curl -fsSL https://claude.ai/install.sh | bash",
|
|
@@ -289,6 +297,8 @@ export function versionAtLeast(actual, required) {
|
|
|
289
297
|
}
|
|
290
298
|
// The first release with --private-env-stdin and the transcript reader on the terminal.
|
|
291
299
|
export const REMOTE_MINIMUM_VERSION = "0.65.0";
|
|
300
|
+
// The first release with the terminal's path-status / make-dir (R15).
|
|
301
|
+
export const REMOTE_PATH_OPS_VERSION = "0.69.0";
|
|
292
302
|
export class RemoteTerminalConnection extends EventEmitter {
|
|
293
303
|
b;
|
|
294
304
|
dir;
|
|
@@ -464,7 +474,11 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
464
474
|
throw new RemoteTerminalError("COMMAND_FAILED", "aiterm-wait returned no receipt");
|
|
465
475
|
}
|
|
466
476
|
}
|
|
467
|
-
async command(op) {
|
|
477
|
+
async command(op, targetPath) {
|
|
478
|
+
if (op === "path_status" || op === "make_dir")
|
|
479
|
+
return this.pathCommand(op, targetPath);
|
|
480
|
+
if (targetPath !== undefined)
|
|
481
|
+
throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no path`);
|
|
468
482
|
if (!Object.hasOwn(COMMANDS, op))
|
|
469
483
|
throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
|
|
470
484
|
const run = await this.exec(`${COMMANDS[op]} 2>&1`, op === "claude_version" ? 60_000 : 900_000);
|
|
@@ -476,6 +490,28 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
476
490
|
const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
|
|
477
491
|
return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
|
|
478
492
|
}
|
|
493
|
+
/** R15: the terminal's own fs answers; the path travels as base64 so no shell reads it. */
|
|
494
|
+
async pathCommand(op, targetPath) {
|
|
495
|
+
checkRemotePath(targetPath);
|
|
496
|
+
if (!versionAtLeast(this.remoteVersion, REMOTE_PATH_OPS_VERSION))
|
|
497
|
+
throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_PATH_OPS_VERSION} or later is required (provision the terminal)`);
|
|
498
|
+
const sub = op === "path_status" ? "path-status" : "make-dir";
|
|
499
|
+
const result = await this.exec(`exec aiterm-remote-terminal ${sub} --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`, 60_000);
|
|
500
|
+
if (result.code === 255) {
|
|
501
|
+
const f = classifySshFailure(result.stderr);
|
|
502
|
+
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
503
|
+
}
|
|
504
|
+
let parsed = null;
|
|
505
|
+
try {
|
|
506
|
+
parsed = JSON.parse(result.stdout.trim().split("\n").pop() ?? "");
|
|
507
|
+
}
|
|
508
|
+
catch { /* classified below */ }
|
|
509
|
+
if (result.code === 0 && parsed?.schema === "aiterm.remote-path.v1")
|
|
510
|
+
return { op, exists: parsed.exists === true, directory: parsed.directory === true, writable: parsed.writable === true };
|
|
511
|
+
if (parsed?.code)
|
|
512
|
+
throw new RemoteTerminalError(parsed.code, parsed.message ?? "path operation failed");
|
|
513
|
+
throw new RemoteTerminalError("COMMAND_FAILED", "the path operation failed on the terminal");
|
|
514
|
+
}
|
|
479
515
|
async close() {
|
|
480
516
|
this.closing = true;
|
|
481
517
|
await this.client.close().catch(() => { });
|
|
@@ -756,7 +792,7 @@ function agentSocketPath(ref) {
|
|
|
756
792
|
return path.join(dir, `${ref.slice(0, 8)}.sock`);
|
|
757
793
|
}
|
|
758
794
|
function agentEnv(socket) { return { ...sshEnvironment(), SSH_AUTH_SOCK: socket }; }
|
|
759
|
-
function agentAlive(socket) {
|
|
795
|
+
export function agentAlive(socket) {
|
|
760
796
|
if (!fs.existsSync(socket))
|
|
761
797
|
return false;
|
|
762
798
|
const listed = spawnSync("ssh-add", ["-l"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
|
package/dist/remote.js
CHANGED
|
@@ -135,8 +135,10 @@ export function remoteShell(target) {
|
|
|
135
135
|
// POSIX系の非ログイン実行では、~/.local/bin、Homebrew、nvmなどのPATHが入らない端末がある。
|
|
136
136
|
// 利用者のログインshellからPATHだけを受け取り、処理は/bin/shで行う。profileの出力やfish等の文法差を
|
|
137
137
|
// MCPのstdoutと処理へ持ち込まない。scriptは呼び出し側で検証済みの値だけで組み、単引用符を含めない。
|
|
138
|
+
// provisionで入れた製品のruntime(remote-terminal.md R16)があれば、利用者のPATH上の別のaiterm-mcp・tmuxより先に使う。
|
|
138
139
|
export function posixCommand(script) {
|
|
139
|
-
const importPath = 'p=$("${SHELL:-/bin/sh}" -lc env </dev/null 2>/dev/null | sed -n "s/^PATH=//p" | tail -n 1); [ -n "$p" ] && PATH=$p;
|
|
140
|
+
const importPath = 'p=$("${SHELL:-/bin/sh}" -lc env </dev/null 2>/dev/null | sed -n "s/^PATH=//p" | tail -n 1); [ -n "$p" ] && PATH=$p; ' +
|
|
141
|
+
'r="$HOME/.aiterm/runtime/current/bin"; [ -x "$r/aiterm-mcp" ] && PATH="$r:$PATH"; export PATH';
|
|
140
142
|
return `/bin/sh -c '${importPath}; ${script}'`;
|
|
141
143
|
}
|
|
142
144
|
/** 現地のaiterm-mcpを起動するコマンド。Windowsはユーザー環境からPATHが入るので、そのまま呼ぶ。 */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiterm-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.69.0",
|
|
4
4
|
"mcpName": "io.github.kitepon/aiterm-mcp",
|
|
5
5
|
"description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
|
|
6
6
|
"keywords": [
|