paseo-office 0.2.0 → 0.2.1
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/OVERVIEW.md +27 -0
- package/README.md +65 -134
- package/client/action-button.tsx +4 -1
- package/client/activity-panel.tsx +6 -4
- package/client/agent-appearance.tsx +257 -0
- package/client/agent-card.tsx +2 -1
- package/client/agent-picker-text.ts +23 -4
- package/client/agent-picker.tsx +5 -8
- package/client/board-sheet.tsx +48 -16
- package/client/board-text.ts +12 -2
- package/client/brand.ts +1 -0
- package/client/chat-chrome.tsx +318 -0
- package/client/chat-compose-tools.tsx +314 -0
- package/client/chat-dictation.tsx +133 -0
- package/client/chat-more.tsx +119 -0
- package/client/chat-panel.tsx +401 -146
- package/client/chat-quick.tsx +198 -0
- package/client/chat-text.ts +25 -6
- package/client/column-sheet.tsx +93 -23
- package/client/conversation-model.ts +19 -5
- package/client/duty-sheet.tsx +321 -0
- package/client/duty-text.ts +20 -0
- package/client/fullscreen-header.tsx +28 -13
- package/client/fullscreen-theme.ts +38 -0
- package/client/host-details.tsx +269 -0
- package/client/host-styles.ts +129 -0
- package/client/host-switches.tsx +197 -73
- package/client/incidents-card.tsx +2 -1
- package/client/janitor-card.tsx +1 -1
- package/client/library-card.tsx +2 -1
- package/client/list-text.ts +8 -6
- package/client/lobby-board.tsx +73 -53
- package/client/machine-card.tsx +225 -85
- package/client/messenger-styles.ts +216 -0
- package/client/new-agent-form.tsx +153 -61
- package/client/new-agent-model.ts +2 -0
- package/client/notes-card.tsx +111 -83
- package/client/notes-days.tsx +1 -1
- package/client/office-brand-context.ts +44 -0
- package/client/office-column.tsx +2 -1
- package/client/office-keyboard.ts +79 -0
- package/client/office-link.ts +7 -1
- package/client/office-mark.tsx +29 -0
- package/client/office-modal.tsx +440 -0
- package/client/office-settings.tsx +75 -30
- package/client/office-state.ts +12 -2
- package/client/office-surface.tsx +591 -81
- package/client/pixel/actors.ts +2 -1
- package/client/pixel/art.ts +33 -19
- package/client/pixel/pixel-office.tsx +2 -2
- package/client/prompt-coach.tsx +152 -0
- package/client/qa-card.tsx +2 -1
- package/client/review-card.tsx +2 -1
- package/client/room-board.tsx +26 -2
- package/client/scene-picker.tsx +158 -0
- package/client/scene-previews.ts +10 -0
- package/client/session-pane.tsx +25 -5
- package/client/session-panel-detail.tsx +238 -0
- package/client/session-panel.tsx +222 -137
- package/client/session-styles.ts +224 -1
- package/client/session-transcript.tsx +243 -0
- package/client/sessions-panel.tsx +181 -22
- package/client/sessions-text.ts +18 -0
- package/client/settings-sections.tsx +126 -0
- package/client/sidebar-launcher.ts +29 -0
- package/client/ssh-hosts.tsx +331 -0
- package/client/ssh-metrics.ts +76 -0
- package/client/standup-card.tsx +2 -1
- package/client/structure-view.tsx +20 -3
- package/client/styles.ts +170 -62
- package/client/team-chat-preview.tsx +96 -0
- package/client/transcript-styles.ts +90 -0
- package/client/use-device-switch.ts +21 -12
- package/client/use-duty-actions.ts +43 -0
- package/client/use-group-photo.ts +48 -0
- package/client/use-new-agent.ts +4 -0
- package/client/use-street.ts +8 -0
- package/client/workspace-office-tools.tsx +102 -0
- package/client/workspace-overlay-route.web.ts +47 -0
- package/client/workspace-overlay.tsx +195 -0
- package/client/world/adapter.ts +37 -2
- package/client/world/escape.ts +58 -0
- package/client/world/use-world-feed.ts +6 -2
- package/client/world/workspace-dock.ts +6 -0
- package/client/world/world-api.ts +45 -4
- package/client/world/world-bridge-page.ts +14 -3
- package/client/world/world-bridge.ts +50 -5
- package/client/world/world-frame.web.ts +8 -0
- package/client/world/world-view-native.tsx +31 -10
- package/client/world/world-view-shared.ts +36 -7
- package/client/world/world-view.tsx +93 -21
- package/docs/office.md +148 -58
- package/index.client.tsx +13 -6
- package/index.server.ts +125 -9
- package/package.json +2 -1
- package/server/activity.ts +42 -19
- package/server/agent-tools.ts +11 -5
- package/server/board-service.ts +381 -10
- package/server/brand-logo.ts +34 -0
- package/server/chat-group.ts +83 -0
- package/server/chat-service.ts +406 -62
- package/server/chat-store.ts +1 -4
- package/server/directory.ts +22 -7
- package/server/duty-service.ts +230 -0
- package/server/group-photo.ts +39 -0
- package/server/home-departure.ts +47 -0
- package/server/hub.ts +43 -1
- package/server/live-ports.ts +114 -18
- package/server/lobby-pickup.ts +170 -0
- package/server/machine/details.ts +91 -0
- package/server/mention-queue.ts +14 -0
- package/server/office.ts +110 -6
- package/server/paths.ts +9 -0
- package/server/ssh/LICENSE.paseo +211 -0
- package/server/ssh/client.ts +401 -0
- package/server/ssh/discovery.ts +230 -0
- package/server/ssh/installed.ts +104 -0
- package/server/ssh/monitor.ts +104 -0
- package/server/ssh/pid-files.ts +194 -0
- package/server/ssh/read.ts +136 -0
- package/server/subagent-names.ts +4 -0
- package/server/words.generated.ts +1 -1
- package/server/world.generated.ts +1 -1
- package/shared/appearance.ts +43 -0
- package/shared/branding.ts +53 -0
- package/shared/chat-words.ts +2 -2
- package/shared/contracts.ts +135 -4
- package/shared/duties.ts +100 -0
- package/shared/host-details.ts +25 -0
- package/shared/lobby-assignment.ts +34 -0
- package/shared/model.ts +9 -1
- package/shared/names.ts +2 -0
- package/shared/settings.ts +14 -3
- package/shared/ssh.ts +34 -0
- package/shared/upstream/README.md +1 -3
- package/shared/upstream/chat-engine.d.ts +4 -0
- package/shared/upstream/prompt-coach.d.ts +6 -0
- package/shared/upstream/prompt-coach.js +178 -0
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
// Adapted from Paseo Resource Manager. See LICENSE.paseo.
|
|
2
|
+
import { nodeTimers } from "../timers.js";
|
|
3
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
4
|
+
import { mkdirSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
import type { Readable } from "node:stream";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { killGroup, removePidFile, writePidFile } from "./pid-files.js";
|
|
10
|
+
|
|
11
|
+
// A minimal MCP client over a child's stdio: initialize, tools/list, tools/call. It runs inside
|
|
12
|
+
// the daemon, so every child, stream and timer event is handled and every timer is unref'd. The
|
|
13
|
+
// child is a detached group leader with a pid file, so a daemon that dies leaves a file the next
|
|
14
|
+
// start reclaims (decision 16).
|
|
15
|
+
|
|
16
|
+
export const MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
17
|
+
const CLIENT_INFO = { name: "paseo-office", version: "1.0.0" };
|
|
18
|
+
const MAX_TOOL_PAGES = 20;
|
|
19
|
+
// As in shared-mcp's STRIPPED_ENV_PREFIX and STRIPPED_ENV_KEYS (process-runner.ts): Paseo's own
|
|
20
|
+
// variables and the keys Paseo removes from every process it launches never reach ssh-mcp.
|
|
21
|
+
const STRIPPED_ENV_PREFIX = "PASEO_";
|
|
22
|
+
const STRIPPED_ENV_KEYS = new Set([
|
|
23
|
+
"ELECTRON_RUN_AS_NODE",
|
|
24
|
+
"ELECTRON_NO_ATTACH_CONSOLE",
|
|
25
|
+
"ESBUILD_BINARY_PATH",
|
|
26
|
+
"CLAUDECODE",
|
|
27
|
+
"CLAUDE_CODE_ENTRYPOINT",
|
|
28
|
+
"CLAUDE_CODE_SSE_PORT",
|
|
29
|
+
"CLAUDE_AGENT_SDK_VERSION",
|
|
30
|
+
]);
|
|
31
|
+
|
|
32
|
+
export interface McpServerCommand {
|
|
33
|
+
command: string;
|
|
34
|
+
args: readonly string[];
|
|
35
|
+
/** The entry's own env, laid over the base env. */
|
|
36
|
+
env: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface McpStdioOptions {
|
|
40
|
+
runDir: string;
|
|
41
|
+
/** Pid files are <runDir>/<name>-<pid>.pid. Pass the server id, never the entry's name. */
|
|
42
|
+
name: string;
|
|
43
|
+
procRoot: string;
|
|
44
|
+
/** The daemon's env. PASEO_* and the parent-session keys are removed from it. */
|
|
45
|
+
baseEnv: NodeJS.ProcessEnv;
|
|
46
|
+
startTimeoutMs: number;
|
|
47
|
+
requestTimeoutMs: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ToolCallResult {
|
|
51
|
+
isError: boolean;
|
|
52
|
+
/** The result's text parts, joined by newlines. */
|
|
53
|
+
text: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class McpSessionError extends Error {
|
|
57
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
58
|
+
super(message, options);
|
|
59
|
+
this.name = "McpSessionError";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class JsonRpcError extends Error {
|
|
64
|
+
readonly code: number;
|
|
65
|
+
|
|
66
|
+
constructor(code: number, message: string) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = "JsonRpcError";
|
|
69
|
+
this.code = code;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const IdSchema = z.union([z.number(), z.string()]);
|
|
74
|
+
type JsonRpcId = z.output<typeof IdSchema>;
|
|
75
|
+
|
|
76
|
+
const IncomingSchema = z.object({
|
|
77
|
+
id: IdSchema.nullish(),
|
|
78
|
+
method: z.string().optional(),
|
|
79
|
+
result: z.unknown().optional(),
|
|
80
|
+
error: z.object({ code: z.number(), message: z.string() }).optional(),
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const InitializeResultSchema = z.object({ protocolVersion: z.string() });
|
|
84
|
+
|
|
85
|
+
const ToolsListResultSchema = z.object({
|
|
86
|
+
tools: z.array(z.object({ name: z.string() })),
|
|
87
|
+
nextCursor: z.string().optional(),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const CallToolResultSchema = z.object({
|
|
91
|
+
content: z.array(z.object({ type: z.string(), text: z.string().optional() })).optional(),
|
|
92
|
+
isError: z.boolean().optional(),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
interface Pending {
|
|
96
|
+
resolve(result: unknown): void;
|
|
97
|
+
reject(error: Error): void;
|
|
98
|
+
cancelTimeout(): void;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function errorMessage(error: unknown): string {
|
|
102
|
+
return error instanceof Error ? error.message : String(error);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function serverEnv(
|
|
106
|
+
overrides: Record<string, string>,
|
|
107
|
+
base: NodeJS.ProcessEnv,
|
|
108
|
+
): NodeJS.ProcessEnv {
|
|
109
|
+
const env: NodeJS.ProcessEnv = {};
|
|
110
|
+
for (const [key, value] of Object.entries({ ...base, ...overrides })) {
|
|
111
|
+
if (key.startsWith(STRIPPED_ENV_PREFIX) || STRIPPED_ENV_KEYS.has(key)) continue;
|
|
112
|
+
env[key] = value;
|
|
113
|
+
}
|
|
114
|
+
return env;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// A stream error means the child went away; the exit handler reports that. readline re-emits an
|
|
118
|
+
// input stream's error on its interface, which needs its own listener (as forwardLines in
|
|
119
|
+
// shared-mcp's process-runner.ts has). A throwing handler must not escape a readline event either,
|
|
120
|
+
// or it would take the daemon down.
|
|
121
|
+
export function readLines(stream: Readable | null, onLine: (line: string) => void): void {
|
|
122
|
+
if (stream === null) return;
|
|
123
|
+
stream.on("error", () => {
|
|
124
|
+
// Reported by the exit handler.
|
|
125
|
+
});
|
|
126
|
+
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
127
|
+
lines.on("error", () => {
|
|
128
|
+
// The same stream error, re-emitted by readline.
|
|
129
|
+
});
|
|
130
|
+
lines.on("line", (line) => {
|
|
131
|
+
try {
|
|
132
|
+
onLine(line);
|
|
133
|
+
} catch {
|
|
134
|
+
console.error("[office] an ssh-mcp line handler failed");
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export class McpStdioClient {
|
|
140
|
+
readonly pid: number | null;
|
|
141
|
+
private readonly child: ChildProcess;
|
|
142
|
+
private readonly pidFile: string | null;
|
|
143
|
+
private readonly requestTimeoutMs: number;
|
|
144
|
+
private readonly pending = new Map<number, Pending>();
|
|
145
|
+
private nextId = 1;
|
|
146
|
+
private exited = false;
|
|
147
|
+
private failure: McpSessionError | null = null;
|
|
148
|
+
private closing: Promise<void> | null = null;
|
|
149
|
+
// One stop per group, started by the leader's exit or by close(), whichever comes first.
|
|
150
|
+
private stopping: Promise<void> | null = null;
|
|
151
|
+
|
|
152
|
+
constructor(child: ChildProcess, pidFile: string | null, requestTimeoutMs: number) {
|
|
153
|
+
this.child = child;
|
|
154
|
+
this.pid = child.pid ?? null;
|
|
155
|
+
this.pidFile = pidFile;
|
|
156
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
157
|
+
// An unlistened "error" on the child or a stream would crash the daemon.
|
|
158
|
+
// No cause: Node's spawn error lists every argument in spawnargs, and one can be a password.
|
|
159
|
+
child.on("error", (error) => {
|
|
160
|
+
this.fail(new McpSessionError(`Could not start ssh-mcp: ${error.message}`));
|
|
161
|
+
});
|
|
162
|
+
child.once("exit", (code, signal) => this.onExit(code, signal));
|
|
163
|
+
child.stdin?.on("error", () => {
|
|
164
|
+
// A write after ssh-mcp closed its stdin fails with EPIPE; the exit handler reports why.
|
|
165
|
+
});
|
|
166
|
+
readLines(child.stdout, (line) => this.handleLine(line));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
get closed(): boolean {
|
|
170
|
+
return this.exited || this.failure !== null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async initialize(timeoutMs: number): Promise<void> {
|
|
174
|
+
const raw = await this.call(
|
|
175
|
+
"initialize",
|
|
176
|
+
{ protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO },
|
|
177
|
+
timeoutMs,
|
|
178
|
+
);
|
|
179
|
+
if (!InitializeResultSchema.safeParse(raw).success) {
|
|
180
|
+
throw new McpSessionError("ssh-mcp answered initialize with an unexpected result");
|
|
181
|
+
}
|
|
182
|
+
this.send({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async listTools(): Promise<string[]> {
|
|
186
|
+
const names: string[] = [];
|
|
187
|
+
let cursor: string | undefined;
|
|
188
|
+
for (let page = 0; page < MAX_TOOL_PAGES; page += 1) {
|
|
189
|
+
const raw = await this.call(
|
|
190
|
+
"tools/list",
|
|
191
|
+
cursor === undefined ? {} : { cursor },
|
|
192
|
+
this.requestTimeoutMs,
|
|
193
|
+
);
|
|
194
|
+
const result = ToolsListResultSchema.safeParse(raw);
|
|
195
|
+
if (!result.success) {
|
|
196
|
+
throw new McpSessionError("ssh-mcp answered tools/list with an unexpected result");
|
|
197
|
+
}
|
|
198
|
+
for (const tool of result.data.tools) names.push(tool.name);
|
|
199
|
+
cursor = result.data.nextCursor;
|
|
200
|
+
if (cursor === undefined) break;
|
|
201
|
+
}
|
|
202
|
+
return names;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async callTool(name: string, args: Record<string, unknown>): Promise<ToolCallResult> {
|
|
206
|
+
let raw: unknown;
|
|
207
|
+
try {
|
|
208
|
+
raw = await this.request("tools/call", { name, arguments: args }, this.requestTimeoutMs);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
// Older MCP SDKs turn an exception in a tool into a JSON-RPC error.
|
|
211
|
+
if (error instanceof JsonRpcError) return { isError: true, text: error.message };
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
const result = CallToolResultSchema.safeParse(raw);
|
|
215
|
+
if (!result.success) {
|
|
216
|
+
throw new McpSessionError(`ssh-mcp answered ${name} with an unexpected result`);
|
|
217
|
+
}
|
|
218
|
+
const text = (result.data.content ?? [])
|
|
219
|
+
.flatMap((part) => (part.type === "text" && part.text !== undefined ? [part.text] : []))
|
|
220
|
+
.join("\n");
|
|
221
|
+
return { isError: result.data.isError === true, text };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
close(): Promise<void> {
|
|
225
|
+
this.closing ??= this.shutdown();
|
|
226
|
+
return this.closing;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
private async shutdown(): Promise<void> {
|
|
230
|
+
this.fail(new McpSessionError("The ssh-mcp session was closed"));
|
|
231
|
+
try {
|
|
232
|
+
this.child.stdin?.end();
|
|
233
|
+
} catch {
|
|
234
|
+
// close() must never reject: startMcpStdioClient's abort handler calls it with `void`.
|
|
235
|
+
console.error("[office] could not stop an ssh-mcp session");
|
|
236
|
+
}
|
|
237
|
+
await this.stopGroup();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Members the leader started can outlive it, so the group stops as soon as the leader exits,
|
|
241
|
+
// while its id still names them. An empty group's id can be reused: it is never signalled again,
|
|
242
|
+
// as in shared-mcp's watchChild.
|
|
243
|
+
private stopGroup(): Promise<void> {
|
|
244
|
+
this.stopping ??= this.killAndForgetGroup();
|
|
245
|
+
return this.stopping;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private async killAndForgetGroup(): Promise<void> {
|
|
249
|
+
try {
|
|
250
|
+
if (this.pid !== null) {
|
|
251
|
+
if (process.platform === "win32") {
|
|
252
|
+
if (!this.exited) this.child.kill();
|
|
253
|
+
} else await killGroup(this.pid);
|
|
254
|
+
}
|
|
255
|
+
if (this.pidFile !== null) removePidFile(this.pidFile);
|
|
256
|
+
} catch {
|
|
257
|
+
console.error("[office] could not stop an ssh-mcp session");
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private onExit(code: number | null, signal: NodeJS.Signals | null): void {
|
|
262
|
+
this.exited = true;
|
|
263
|
+
void this.stopGroup();
|
|
264
|
+
this.fail(new McpSessionError(`ssh-mcp exited (${code ?? signal})`));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private fail(error: McpSessionError): void {
|
|
268
|
+
this.failure ??= error;
|
|
269
|
+
for (const pending of this.pending.values()) {
|
|
270
|
+
pending.cancelTimeout();
|
|
271
|
+
pending.reject(this.failure);
|
|
272
|
+
}
|
|
273
|
+
this.pending.clear();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private send(message: Record<string, unknown>): void {
|
|
277
|
+
const stdin = this.child.stdin;
|
|
278
|
+
if (this.pid === null || this.exited || this.failure !== null) return;
|
|
279
|
+
if (stdin === null || !stdin.writable) return;
|
|
280
|
+
stdin.write(`${JSON.stringify(message)}\n`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private request(
|
|
284
|
+
method: string,
|
|
285
|
+
params: Record<string, unknown>,
|
|
286
|
+
timeoutMs: number,
|
|
287
|
+
): Promise<unknown> {
|
|
288
|
+
if (this.failure !== null) return Promise.reject(this.failure);
|
|
289
|
+
const id = this.nextId;
|
|
290
|
+
this.nextId += 1;
|
|
291
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
292
|
+
const cancelTimeout = nodeTimers.setTimeout(() => {
|
|
293
|
+
this.pending.delete(id);
|
|
294
|
+
reject(
|
|
295
|
+
new McpSessionError(`ssh-mcp did not answer ${method} within ${timeoutMs / 1000} s`),
|
|
296
|
+
);
|
|
297
|
+
}, timeoutMs);
|
|
298
|
+
this.pending.set(id, { resolve, reject, cancelTimeout });
|
|
299
|
+
this.send({ jsonrpc: "2.0", id, method, params });
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// A JSON-RPC error on a protocol method means the session cannot be used.
|
|
304
|
+
private async call(
|
|
305
|
+
method: string,
|
|
306
|
+
params: Record<string, unknown>,
|
|
307
|
+
timeoutMs: number,
|
|
308
|
+
): Promise<unknown> {
|
|
309
|
+
try {
|
|
310
|
+
return await this.request(method, params, timeoutMs);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (error instanceof JsonRpcError) {
|
|
313
|
+
throw new McpSessionError(`ssh-mcp refused ${method}: ${error.message}`, { cause: error });
|
|
314
|
+
}
|
|
315
|
+
throw error;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private handleLine(line: string): void {
|
|
320
|
+
let json: unknown;
|
|
321
|
+
try {
|
|
322
|
+
json = JSON.parse(line);
|
|
323
|
+
} catch {
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const message = IncomingSchema.safeParse(json);
|
|
327
|
+
if (!message.success) return;
|
|
328
|
+
const { id, method, error } = message.data;
|
|
329
|
+
if (method !== undefined) {
|
|
330
|
+
if (id !== undefined && id !== null) this.answerServerRequest(id, method);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (typeof id !== "number") return;
|
|
334
|
+
const pending = this.pending.get(id);
|
|
335
|
+
if (pending === undefined) return;
|
|
336
|
+
this.pending.delete(id);
|
|
337
|
+
pending.cancelTimeout();
|
|
338
|
+
if (error !== undefined) pending.reject(new JsonRpcError(error.code, error.message));
|
|
339
|
+
else pending.resolve(message.data.result);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private answerServerRequest(id: JsonRpcId, method: string): void {
|
|
343
|
+
if (method === "ping") this.send({ jsonrpc: "2.0", id, result: {} });
|
|
344
|
+
else this.send({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found" } });
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Node refuses a NUL byte and quotes the whole value in its error, and the value can be a password.
|
|
349
|
+
function holdsNul(command: McpServerCommand): boolean {
|
|
350
|
+
const entries = Object.entries(command.env).flat();
|
|
351
|
+
return [command.command, ...command.args, ...entries].some((value) => value.includes("\0"));
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function spawnServer(command: McpServerCommand, options: McpStdioOptions): ChildProcess {
|
|
355
|
+
if (holdsNul(command)) {
|
|
356
|
+
throw new McpSessionError(
|
|
357
|
+
"Could not start ssh-mcp: the command, an argument or an env entry holds a NUL byte",
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
mkdirSync(options.runDir, { recursive: true, mode: 0o700 });
|
|
362
|
+
return spawn(command.command, [...command.args], {
|
|
363
|
+
env: serverEnv(command.env, options.baseEnv),
|
|
364
|
+
detached: true,
|
|
365
|
+
// Without it, a detached child on Windows opens a console window of its own.
|
|
366
|
+
windowsHide: true,
|
|
367
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
368
|
+
});
|
|
369
|
+
} catch (error) {
|
|
370
|
+
throw new McpSessionError(`Could not start ssh-mcp: ${errorMessage(error)}`, { cause: error });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export async function startMcpStdioClient(
|
|
375
|
+
command: McpServerCommand,
|
|
376
|
+
options: McpStdioOptions,
|
|
377
|
+
signal?: AbortSignal,
|
|
378
|
+
): Promise<McpStdioClient> {
|
|
379
|
+
if (signal?.aborted) throw new McpSessionError("The ssh-mcp start was cancelled");
|
|
380
|
+
const child = spawnServer(command, options);
|
|
381
|
+
const pidFile =
|
|
382
|
+
child.pid === undefined ? null : join(options.runDir, `${options.name}-${child.pid}.pid`);
|
|
383
|
+
const client = new McpStdioClient(child, pidFile, options.requestTimeoutMs);
|
|
384
|
+
const abort = (): void => {
|
|
385
|
+
void client.close();
|
|
386
|
+
};
|
|
387
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
388
|
+
try {
|
|
389
|
+
if (pidFile !== null && client.pid !== null) {
|
|
390
|
+
writePidFile(pidFile, client.pid, options.procRoot);
|
|
391
|
+
}
|
|
392
|
+
await client.initialize(options.startTimeoutMs);
|
|
393
|
+
return client;
|
|
394
|
+
} catch (error) {
|
|
395
|
+
await client.close();
|
|
396
|
+
if (error instanceof McpSessionError) throw error;
|
|
397
|
+
throw new McpSessionError(`Could not start ssh-mcp: ${errorMessage(error)}`, { cause: error });
|
|
398
|
+
} finally {
|
|
399
|
+
signal?.removeEventListener("abort", abort);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Adapted from Paseo Resource Manager. See LICENSE.paseo.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { installedLaunch } from "./installed.js";
|
|
7
|
+
|
|
8
|
+
// Finds every ssh-mcp entry in the Claude configs the daemon can read, taking a .mcp.json only
|
|
9
|
+
// where Claude Code trusts its folder. A config holds passwords and keys in its args and env, so
|
|
10
|
+
// nothing here logs or returns a config's text: a file that does not parse is reported by path
|
|
11
|
+
// only. The RPC publishes just the entry name and an opaque ID.
|
|
12
|
+
|
|
13
|
+
export interface SshServer {
|
|
14
|
+
/** sha256(source key NUL entry name), first 16 hex characters: stable and free of secrets. */
|
|
15
|
+
id: string;
|
|
16
|
+
name: string;
|
|
17
|
+
/** "User config", "Local config for <dir>" or "<dir>/.mcp.json". */
|
|
18
|
+
source: string;
|
|
19
|
+
command: string;
|
|
20
|
+
args: string[];
|
|
21
|
+
env: Record<string, string>;
|
|
22
|
+
/** Variables the entry names that the daemon's env does not set, with no default. */
|
|
23
|
+
missingVariables: string[];
|
|
24
|
+
/** sha256 of the expanded command, args and env. A change replaces the running session. */
|
|
25
|
+
fingerprint: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Discovery {
|
|
29
|
+
servers: SshServer[];
|
|
30
|
+
problems: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DiscoveryInput {
|
|
34
|
+
claudeConfigFile: string;
|
|
35
|
+
/** Each workspace's directory: its worktree, else its project root. */
|
|
36
|
+
workspaceDirectories: readonly string[];
|
|
37
|
+
env: NodeJS.ProcessEnv;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface ConfigSource {
|
|
41
|
+
key: string;
|
|
42
|
+
label: string;
|
|
43
|
+
servers: Record<string, unknown>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Entries are parsed one by one, so an HTTP entry or an odd one never hides the rest.
|
|
47
|
+
const ServerMapSchema = z.record(z.string(), z.unknown());
|
|
48
|
+
|
|
49
|
+
const StdioEntrySchema = z.object({
|
|
50
|
+
type: z.literal("stdio").optional(),
|
|
51
|
+
command: z.string().min(1),
|
|
52
|
+
args: z.array(z.string()).optional(),
|
|
53
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// projects is read per workspace for the same reason.
|
|
57
|
+
const ClaudeConfigSchema = z.object({
|
|
58
|
+
mcpServers: ServerMapSchema.optional(),
|
|
59
|
+
projects: z.record(z.string(), z.unknown()).optional(),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const ProjectSchema = z.object({ mcpServers: ServerMapSchema.optional() });
|
|
63
|
+
|
|
64
|
+
const McpJsonSchema = z.object({ mcpServers: ServerMapSchema.optional() });
|
|
65
|
+
|
|
66
|
+
const TrustSchema = z.object({ hasTrustDialogAccepted: z.literal(true) });
|
|
67
|
+
|
|
68
|
+
// Claude Code's syntax: ${VAR} and ${VAR:-default}.
|
|
69
|
+
const VARIABLE = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
|
|
70
|
+
|
|
71
|
+
function isMissing(error: unknown): boolean {
|
|
72
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// undefined when the file is missing (silently) or unusable (reported). JSON is never undefined.
|
|
76
|
+
async function readJson(file: string, problems: string[]): Promise<unknown> {
|
|
77
|
+
let text: string;
|
|
78
|
+
try {
|
|
79
|
+
text = await readFile(file, "utf8");
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (!isMissing(error)) problems.push(`${file}: unreadable`);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(text);
|
|
86
|
+
} catch {
|
|
87
|
+
// The parser's message quotes the text, which may hold a password.
|
|
88
|
+
problems.push(`${file}: not valid JSON`);
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function expandVariables(
|
|
94
|
+
value: string,
|
|
95
|
+
env: NodeJS.ProcessEnv,
|
|
96
|
+
missing: Set<string>,
|
|
97
|
+
): string {
|
|
98
|
+
return value.replace(VARIABLE, (_match: string, name: string, fallback: string | undefined) => {
|
|
99
|
+
// Object.prototype's members (constructor, __proto__) are never strings, so a variable named
|
|
100
|
+
// after one counts as unset.
|
|
101
|
+
const set = env[name];
|
|
102
|
+
if (typeof set === "string") return set;
|
|
103
|
+
if (fallback !== undefined) return fallback;
|
|
104
|
+
missing.add(name);
|
|
105
|
+
return "";
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function sha256(text: string): string {
|
|
110
|
+
return createHash("sha256").update(text).digest("hex");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function serverId(sourceKey: string, name: string): string {
|
|
114
|
+
return sha256(`${sourceKey}\0${name}`).slice(0, 16);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function fingerprintOf(command: string, args: readonly string[], env: Record<string, string>) {
|
|
118
|
+
const entries = Object.entries(env).sort(([a], [b]) => (a < b ? -1 : 1));
|
|
119
|
+
return sha256(JSON.stringify([command, args, entries]));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function toServer(
|
|
123
|
+
source: ConfigSource,
|
|
124
|
+
name: string,
|
|
125
|
+
raw: unknown,
|
|
126
|
+
env: NodeJS.ProcessEnv,
|
|
127
|
+
): Promise<SshServer | null> {
|
|
128
|
+
const entry = StdioEntrySchema.safeParse(raw);
|
|
129
|
+
if (!entry.success) return null;
|
|
130
|
+
const missing = new Set<string>();
|
|
131
|
+
const command = expandVariables(entry.data.command, env, missing);
|
|
132
|
+
const args = (entry.data.args ?? []).map((arg) => expandVariables(arg, env, missing));
|
|
133
|
+
const serverEnv: Record<string, string> = {};
|
|
134
|
+
for (const [key, value] of Object.entries(entry.data.env ?? {})) {
|
|
135
|
+
serverEnv[key] = expandVariables(value, env, missing);
|
|
136
|
+
}
|
|
137
|
+
const launch = await installedLaunch(command, args, { ...env, ...serverEnv });
|
|
138
|
+
if (!launch) return null;
|
|
139
|
+
return {
|
|
140
|
+
id: serverId(source.key, name),
|
|
141
|
+
name,
|
|
142
|
+
source: source.label,
|
|
143
|
+
...launch,
|
|
144
|
+
env: serverEnv,
|
|
145
|
+
missingVariables: [...missing].sort(),
|
|
146
|
+
fingerprint: fingerprintOf(launch.command, launch.args, serverEnv),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// A .mcp.json comes with the repository, so its commands are the repository's code. As in Claude
|
|
151
|
+
// Code, they run only for a folder trusted there: hasTrustDialogAccepted on the folder or a parent
|
|
152
|
+
// in ~/.claude.json, which Claude Code sets when its trust dialog is accepted.
|
|
153
|
+
function isTrusted(projects: Record<string, unknown> | undefined, dir: string): boolean {
|
|
154
|
+
for (let path = resolve(dir); ; path = dirname(path)) {
|
|
155
|
+
if (TrustSchema.safeParse(projects?.[path]).success) return true;
|
|
156
|
+
if (dirname(path) === path) return false;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// null when the folder has no usable .mcp.json, or Claude Code does not trust the folder.
|
|
161
|
+
async function readMcpJsonSource(
|
|
162
|
+
dir: string,
|
|
163
|
+
projects: Record<string, unknown> | undefined,
|
|
164
|
+
problems: string[],
|
|
165
|
+
): Promise<ConfigSource | null> {
|
|
166
|
+
const file = join(dir, ".mcp.json");
|
|
167
|
+
const json = await readJson(file, problems);
|
|
168
|
+
if (json === undefined) return null;
|
|
169
|
+
const parsed = McpJsonSchema.safeParse(json);
|
|
170
|
+
if (!parsed.success) {
|
|
171
|
+
problems.push(`${file}: not an MCP config`);
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
if (parsed.data.mcpServers === undefined) return null;
|
|
175
|
+
const source: ConfigSource = {
|
|
176
|
+
key: `project:${file}`,
|
|
177
|
+
label: file,
|
|
178
|
+
servers: parsed.data.mcpServers,
|
|
179
|
+
};
|
|
180
|
+
if (isTrusted(projects, dir)) return source;
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function collectSources(input: DiscoveryInput, problems: string[]): Promise<ConfigSource[]> {
|
|
185
|
+
const sources: ConfigSource[] = [];
|
|
186
|
+
const json = await readJson(input.claudeConfigFile, problems);
|
|
187
|
+
let claude: z.output<typeof ClaudeConfigSchema> | null = null;
|
|
188
|
+
if (json !== undefined) {
|
|
189
|
+
const parsed = ClaudeConfigSchema.safeParse(json);
|
|
190
|
+
if (parsed.success) claude = parsed.data;
|
|
191
|
+
else problems.push(`${input.claudeConfigFile}: not a Claude config`);
|
|
192
|
+
}
|
|
193
|
+
if (claude?.mcpServers !== undefined) {
|
|
194
|
+
sources.push({ key: "user", label: "User config", servers: claude.mcpServers });
|
|
195
|
+
}
|
|
196
|
+
for (const dir of input.workspaceDirectories) {
|
|
197
|
+
const project = ProjectSchema.safeParse(claude?.projects?.[dir]);
|
|
198
|
+
if (project.success && project.data.mcpServers !== undefined) {
|
|
199
|
+
sources.push({
|
|
200
|
+
key: `local:${dir}`,
|
|
201
|
+
label: `Local config for ${dir}`,
|
|
202
|
+
servers: project.data.mcpServers,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
const mcpJson = await readMcpJsonSource(dir, claude?.projects, problems);
|
|
206
|
+
if (mcpJson !== null) sources.push(mcpJson);
|
|
207
|
+
}
|
|
208
|
+
return sources;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// User scope first, then each workspace's local and project scope in the order Paseo lists them.
|
|
212
|
+
// Entries with the same expanded command, args and env are one server, under its first source.
|
|
213
|
+
// Unset variables expand to "", so they are part of the key: entries that differ only in which
|
|
214
|
+
// variables are unset stay apart.
|
|
215
|
+
export async function discoverSshServers(input: DiscoveryInput): Promise<Discovery> {
|
|
216
|
+
const problems: string[] = [];
|
|
217
|
+
const servers: SshServer[] = [];
|
|
218
|
+
const seen = new Set<string>();
|
|
219
|
+
for (const source of await collectSources(input, problems)) {
|
|
220
|
+
for (const [name, raw] of Object.entries(source.servers)) {
|
|
221
|
+
const server = await toServer(source, name, raw, input.env);
|
|
222
|
+
if (server === null) continue;
|
|
223
|
+
const key = `${server.fingerprint}\0${server.missingVariables.join(",")}`;
|
|
224
|
+
if (seen.has(key)) continue;
|
|
225
|
+
seen.add(key);
|
|
226
|
+
servers.push(server);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return { servers, problems };
|
|
230
|
+
}
|