premanmcp 0.4.0 → 0.7.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/README.md +72 -22
- package/bin/api_tools.js +215 -0
- package/bin/cli.js +63 -324
- package/bin/connect.js +715 -0
- package/bin/integrations.js +367 -0
- package/bin/shared.js +351 -0
- package/dist/server.js +121 -1
- package/package.json +3 -2
package/bin/connect.js
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `preman connect` — pick a coding agent and get connected, in one command.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the hand-edited MCP config: the user picks Cursor / Claude Code /
|
|
5
|
+
* Codex from a list, PreMan logs them in if needed, writes that agent's config
|
|
6
|
+
* itself, and binds the connection to their account with a pair code.
|
|
7
|
+
*
|
|
8
|
+
* Optionally captures a cloud-dispatch credential in the same pass so PreMan can
|
|
9
|
+
* start agent runs for them later (SCRUM-124). That step is always skippable and
|
|
10
|
+
* never fails the connect.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
14
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
|
|
18
|
+
import { callTool as callPremanTool, printTestSummary } from "./api_tools.js";
|
|
19
|
+
import {
|
|
20
|
+
assertOk,
|
|
21
|
+
authenticateTerminal,
|
|
22
|
+
backendUrl,
|
|
23
|
+
buildServerConfig,
|
|
24
|
+
callBackendJson,
|
|
25
|
+
frontendUrl,
|
|
26
|
+
hasKeyAvailable,
|
|
27
|
+
makeArgs,
|
|
28
|
+
promptSecret,
|
|
29
|
+
promptText,
|
|
30
|
+
readJsonFile,
|
|
31
|
+
resolveApiKey,
|
|
32
|
+
writeJsonFile,
|
|
33
|
+
} from "./shared.js";
|
|
34
|
+
|
|
35
|
+
const EXIT_USAGE = 2;
|
|
36
|
+
|
|
37
|
+
class ConnectError extends Error {
|
|
38
|
+
constructor(message, exitCode = 1) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.exitCode = exitCode;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Supported agents. `id` matches the backend's normalize_agent() vocabulary so
|
|
46
|
+
* the link record and this CLI cannot disagree about who is connected.
|
|
47
|
+
*/
|
|
48
|
+
const AGENTS = [
|
|
49
|
+
{
|
|
50
|
+
id: "cursor",
|
|
51
|
+
label: "Cursor",
|
|
52
|
+
aliases: ["cursor"],
|
|
53
|
+
dispatch: { credential: "Cursor API key", needsRoutine: false },
|
|
54
|
+
snippetHint: "merge into ~/.cursor/mcp.json",
|
|
55
|
+
restartHint: 'Fully quit and reopen Cursor, then Settings → MCP → toggle "preman" off and on.',
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: "claude_code",
|
|
59
|
+
label: "Claude Code",
|
|
60
|
+
aliases: ["claude", "claude-code", "claude_code", "claudecode"],
|
|
61
|
+
dispatch: { credential: "Claude Code routine token", needsRoutine: true },
|
|
62
|
+
snippetHint: "run:",
|
|
63
|
+
restartHint: 'Start a new Claude Code session and run `claude mcp list` — "preman" should be listed.',
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
id: "codex",
|
|
67
|
+
label: "Codex",
|
|
68
|
+
aliases: ["codex", "openai-codex", "openai_codex"],
|
|
69
|
+
dispatch: null, // No public fire API; stays on the copy-paste path.
|
|
70
|
+
snippetHint: "append to ~/.codex/config.toml",
|
|
71
|
+
restartHint: "Restart Codex so it re-reads its config.toml.",
|
|
72
|
+
},
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
function findAgent(value) {
|
|
76
|
+
const raw = String(value || "").trim().toLowerCase().replace(/\s+/g, "-");
|
|
77
|
+
return AGENTS.find((a) => a.id === raw || a.aliases.includes(raw)) || null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function onPath(binary) {
|
|
81
|
+
const probe = spawnSync(process.platform === "win32" ? "where" : "which", [binary], {
|
|
82
|
+
stdio: "ignore",
|
|
83
|
+
});
|
|
84
|
+
return probe.status === 0;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Best guess at which agent this machine actually uses, for the default pick. */
|
|
88
|
+
function detectAgents() {
|
|
89
|
+
const home = os.homedir();
|
|
90
|
+
return {
|
|
91
|
+
cursor: existsSync(path.join(home, ".cursor")) || Boolean(process.env.CURSOR_TRACE_ID),
|
|
92
|
+
claude_code: onPath("claude") || existsSync(path.join(home, ".claude.json")),
|
|
93
|
+
codex: onPath("codex") || existsSync(process.env.CODEX_HOME || path.join(home, ".codex")),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function promptAgentChoice(detected) {
|
|
98
|
+
process.stdout.write("Which coding agent?\n");
|
|
99
|
+
AGENTS.forEach((agent, index) => {
|
|
100
|
+
const mark = detected[agent.id] ? " (detected)" : "";
|
|
101
|
+
process.stdout.write(` ${index + 1}. ${agent.label}${mark}\n`);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
const defaultIndex = Math.max(
|
|
105
|
+
0,
|
|
106
|
+
AGENTS.findIndex((a) => detected[a.id])
|
|
107
|
+
);
|
|
108
|
+
const answer = await promptText(`Pick [${defaultIndex + 1}]: `);
|
|
109
|
+
if (!answer) return AGENTS[defaultIndex];
|
|
110
|
+
|
|
111
|
+
const byNumber = Number.parseInt(answer, 10);
|
|
112
|
+
if (Number.isInteger(byNumber) && byNumber >= 1 && byNumber <= AGENTS.length) {
|
|
113
|
+
return AGENTS[byNumber - 1];
|
|
114
|
+
}
|
|
115
|
+
const byName = findAgent(answer);
|
|
116
|
+
if (byName) return byName;
|
|
117
|
+
throw new ConnectError(`Not a valid choice: ${answer}`, EXIT_USAGE);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ── Config writers ──────────────────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
function cursorConfigPath(projectInstall) {
|
|
123
|
+
return projectInstall
|
|
124
|
+
? path.join(process.cwd(), ".cursor", "mcp.json")
|
|
125
|
+
: path.join(os.homedir(), ".cursor", "mcp.json");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function writeCursorConfig({ serverName, serverConfig, projectInstall }) {
|
|
129
|
+
const configPath = cursorConfigPath(projectInstall);
|
|
130
|
+
const config = { ...readJsonFile(configPath) };
|
|
131
|
+
config.mcpServers = { ...(config.mcpServers || {}), [serverName]: serverConfig };
|
|
132
|
+
writeJsonFile(configPath, config);
|
|
133
|
+
return { path: configPath, how: "wrote" };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The `claude mcp add` invocation, shared by the writer and the printed fallback. */
|
|
137
|
+
export function claudeMcpAddArgs(serverName, serverConfig, projectInstall) {
|
|
138
|
+
const envArgs = Object.entries(serverConfig.env).flatMap(([k, v]) => ["--env", `${k}=${v}`]);
|
|
139
|
+
return [
|
|
140
|
+
"mcp",
|
|
141
|
+
"add",
|
|
142
|
+
serverName,
|
|
143
|
+
"--scope",
|
|
144
|
+
projectInstall ? "project" : "user",
|
|
145
|
+
...envArgs,
|
|
146
|
+
"--",
|
|
147
|
+
serverConfig.command,
|
|
148
|
+
...serverConfig.args,
|
|
149
|
+
];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Claude Code owns ~/.claude.json, so prefer its own CLI. Fall back to writing
|
|
154
|
+
* the config directly when `claude` is not installed — a user can connect before
|
|
155
|
+
* installing the agent.
|
|
156
|
+
*/
|
|
157
|
+
export function writeClaudeConfig({ serverName, serverConfig, projectInstall }) {
|
|
158
|
+
if (onPath("claude")) {
|
|
159
|
+
const args = claudeMcpAddArgs(serverName, serverConfig, projectInstall);
|
|
160
|
+
try {
|
|
161
|
+
execFileSync("claude", args, { stdio: "pipe" });
|
|
162
|
+
return { path: projectInstall ? ".mcp.json" : "Claude Code user config", how: "registered via claude mcp add" };
|
|
163
|
+
} catch (error) {
|
|
164
|
+
const detail = error?.stderr?.toString().trim() || error.message;
|
|
165
|
+
process.stdout.write(`Note: claude mcp add failed (${detail}); writing the config directly.\n`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (projectInstall) {
|
|
170
|
+
const configPath = path.join(process.cwd(), ".mcp.json");
|
|
171
|
+
const config = { ...readJsonFile(configPath) };
|
|
172
|
+
config.mcpServers = { ...(config.mcpServers || {}), [serverName]: serverConfig };
|
|
173
|
+
writeJsonFile(configPath, config);
|
|
174
|
+
return { path: configPath, how: "wrote" };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Merge only mcpServers: the user config holds a lot of unrelated state.
|
|
178
|
+
// CLAUDE_CONFIG_DIR relocates that file, and writing to ~ when it is set
|
|
179
|
+
// produces a config Claude Code never reads.
|
|
180
|
+
const configPath = path.join(process.env.CLAUDE_CONFIG_DIR || os.homedir(), ".claude.json");
|
|
181
|
+
const config = { ...readJsonFile(configPath) };
|
|
182
|
+
config.mcpServers = { ...(config.mcpServers || {}), [serverName]: serverConfig };
|
|
183
|
+
writeJsonFile(configPath, config);
|
|
184
|
+
return { path: configPath, how: "wrote" };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Render the `[mcp_servers.<name>]` block for Codex's TOML config. Only strings
|
|
189
|
+
* and string arrays appear here, so a hand-rolled writer is enough — no TOML
|
|
190
|
+
* dependency for one fixed shape.
|
|
191
|
+
*/
|
|
192
|
+
export function renderCodexToml(serverName, serverConfig) {
|
|
193
|
+
const str = (value) => JSON.stringify(String(value));
|
|
194
|
+
const lines = [
|
|
195
|
+
`[mcp_servers.${serverName}]`,
|
|
196
|
+
`command = ${str(serverConfig.command)}`,
|
|
197
|
+
`args = [${serverConfig.args.map(str).join(", ")}]`,
|
|
198
|
+
];
|
|
199
|
+
const env = Object.entries(serverConfig.env);
|
|
200
|
+
if (env.length) {
|
|
201
|
+
lines.push("", `[mcp_servers.${serverName}.env]`);
|
|
202
|
+
for (const [key, value] of env) lines.push(`${key} = ${str(value)}`);
|
|
203
|
+
}
|
|
204
|
+
return `${lines.join("\n")}\n`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Replace an existing preman block, or append a new one, leaving the rest alone. */
|
|
208
|
+
export function upsertCodexToml(existing, serverName, block) {
|
|
209
|
+
const header = new RegExp(`^\\[mcp_servers\\.${serverName}(\\.|\\])`, "m");
|
|
210
|
+
if (!header.test(existing)) {
|
|
211
|
+
const separator = existing.trim() ? "\n" : "";
|
|
212
|
+
return `${existing.trimEnd()}${separator}\n${block}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const lines = existing.split("\n");
|
|
216
|
+
const out = [];
|
|
217
|
+
let skipping = false;
|
|
218
|
+
for (const line of lines) {
|
|
219
|
+
const isOurHeader = new RegExp(`^\\[mcp_servers\\.${serverName}(\\.|\\])`).test(line);
|
|
220
|
+
if (isOurHeader) {
|
|
221
|
+
skipping = true;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (skipping && /^\[/.test(line) && !isOurHeader) skipping = false;
|
|
225
|
+
if (!skipping) out.push(line);
|
|
226
|
+
}
|
|
227
|
+
return `${out.join("\n").trimEnd()}\n\n${block}`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function writeCodexConfig({ serverName, serverConfig }) {
|
|
231
|
+
const configPath = path.join(
|
|
232
|
+
process.env.CODEX_HOME || path.join(os.homedir(), ".codex"),
|
|
233
|
+
"config.toml"
|
|
234
|
+
);
|
|
235
|
+
const existing = existsSync(configPath) ? readFileSync(configPath, "utf8") : "";
|
|
236
|
+
const next = upsertCodexToml(existing, serverName, renderCodexToml(serverName, serverConfig));
|
|
237
|
+
mkdirSync(path.dirname(configPath), { recursive: true });
|
|
238
|
+
writeFileSync(configPath, next, { mode: 0o600 });
|
|
239
|
+
chmodSync(configPath, 0o600); // mode above is ignored for an existing file
|
|
240
|
+
return { path: configPath, how: "wrote" };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const WRITERS = {
|
|
244
|
+
cursor: writeCursorConfig,
|
|
245
|
+
claude_code: writeClaudeConfig,
|
|
246
|
+
codex: writeCodexConfig,
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// ── Copy-paste fallbacks ────────────────────────────────────────────────
|
|
250
|
+
|
|
251
|
+
/** Quote only what a shell would otherwise mangle, so the line stays readable. */
|
|
252
|
+
function shellQuote(value) {
|
|
253
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${String(value).replace(/'/g, `'\\''`)}'`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** What a user would paste by hand to get exactly what the writer would have written. */
|
|
257
|
+
export function renderAgentSnippet(agentId, serverName, serverConfig, { projectInstall = false } = {}) {
|
|
258
|
+
if (agentId === "codex") return renderCodexToml(serverName, serverConfig);
|
|
259
|
+
if (agentId === "claude_code") {
|
|
260
|
+
const args = claudeMcpAddArgs(serverName, serverConfig, projectInstall);
|
|
261
|
+
return `claude ${args.map(shellQuote).join(" ")}\n`;
|
|
262
|
+
}
|
|
263
|
+
return `${JSON.stringify({ mcpServers: { [serverName]: serverConfig } }, null, 2)}\n`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Every agent's snippet, for when we could not pick one for the user. */
|
|
267
|
+
export function renderAllAgentSnippets(args, serverName, { projectInstall = false } = {}) {
|
|
268
|
+
// Build config WITHOUT resolved API key to avoid leaking secrets in CI logs.
|
|
269
|
+
// Users must supply --api-key or set PREMAN_API_KEY separately.
|
|
270
|
+
const env = {
|
|
271
|
+
PREMAN_BACKEND: backendUrl(args),
|
|
272
|
+
PREMAN_FRONTEND: frontendUrl(args),
|
|
273
|
+
};
|
|
274
|
+
const serverConfig = { command: "npx", args: ["-y", "premanmcp@latest"], env };
|
|
275
|
+
|
|
276
|
+
return AGENTS.map((agent) => {
|
|
277
|
+
// Adjust hint based on projectInstall, matching verifyWrittenConfig logic
|
|
278
|
+
let hint = agent.snippetHint;
|
|
279
|
+
if (agent.id === "cursor" && projectInstall) {
|
|
280
|
+
hint = "merge into .cursor/mcp.json";
|
|
281
|
+
} else if (agent.id === "claude_code") {
|
|
282
|
+
hint = projectInstall ? "run (with --scope project):" : "run:";
|
|
283
|
+
}
|
|
284
|
+
return `# ${agent.label} — ${hint}\n` + renderAgentSnippet(agent.id, serverName, serverConfig, { projectInstall });
|
|
285
|
+
}).join("\n");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ── Post-write validation ───────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
/** The lines belonging to our `[mcp_servers.<name>]` block, or null if absent. */
|
|
291
|
+
function codexBlockLines(text, serverName) {
|
|
292
|
+
const lines = text.split("\n");
|
|
293
|
+
const start = lines.findIndex((line) => line.trim() === `[mcp_servers.${serverName}]`);
|
|
294
|
+
if (start === -1) return null;
|
|
295
|
+
const block = [];
|
|
296
|
+
for (let i = start + 1; i < lines.length; i += 1) {
|
|
297
|
+
const line = lines[i];
|
|
298
|
+
if (/^\[/.test(line) && !line.startsWith(`[mcp_servers.${serverName}.`)) break;
|
|
299
|
+
block.push(line);
|
|
300
|
+
}
|
|
301
|
+
return block;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Read back what we just wrote, so a silently-failed write is not reported as a
|
|
306
|
+
* success. Proves the entry is on disk (or that Claude Code knows about it) —
|
|
307
|
+
* whether the agent has actually loaded it is only ever proven by a check-in.
|
|
308
|
+
*
|
|
309
|
+
* Never throws: a verification that cannot run must not fail the connect. An
|
|
310
|
+
* unreadable state reports "unknown" and stays quiet, because a wrong warning
|
|
311
|
+
* costs more trust than a missing one.
|
|
312
|
+
*/
|
|
313
|
+
export function verifyWrittenConfig(agent, { serverName, written }) {
|
|
314
|
+
try {
|
|
315
|
+
if (agent.id === "codex") {
|
|
316
|
+
const text = written.path && existsSync(written.path) ? readFileSync(written.path, "utf8") : "";
|
|
317
|
+
const block = codexBlockLines(text, serverName);
|
|
318
|
+
if (!block) {
|
|
319
|
+
return { status: "mismatch", detail: `no [mcp_servers.${serverName}] block in ${written.path}` };
|
|
320
|
+
}
|
|
321
|
+
if (!block.some((line) => line.trim() === 'command = "npx"')) {
|
|
322
|
+
return { status: "mismatch", detail: `${written.path} does not launch npx` };
|
|
323
|
+
}
|
|
324
|
+
return { status: "verified" };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Claude Code registered the server itself — ask its CLI what it ended up with.
|
|
328
|
+
if (agent.id === "claude_code" && written.how !== "wrote") {
|
|
329
|
+
const probe = spawnSync("claude", ["mcp", "get", serverName], { stdio: "ignore" });
|
|
330
|
+
if (probe.error) return { status: "unknown", detail: "could not run claude" };
|
|
331
|
+
return probe.status === 0
|
|
332
|
+
? { status: "verified" }
|
|
333
|
+
: { status: "mismatch", detail: `claude mcp get ${serverName} did not find the server` };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const entry = readJsonFile(written.path).mcpServers?.[serverName];
|
|
337
|
+
if (!entry) return { status: "mismatch", detail: `${serverName} is missing from ${written.path}` };
|
|
338
|
+
if (entry.command !== "npx") {
|
|
339
|
+
return { status: "mismatch", detail: `${written.path} does not launch npx` };
|
|
340
|
+
}
|
|
341
|
+
return { status: "verified" };
|
|
342
|
+
} catch (error) {
|
|
343
|
+
return { status: "unknown", detail: error.message };
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ── Pairing ─────────────────────────────────────────────────────────────
|
|
348
|
+
|
|
349
|
+
async function startPairing(args, agent, apiKey) {
|
|
350
|
+
const result = await callBackendJson(args, "PUT", "/workbench/coding-agent", {
|
|
351
|
+
token: apiKey,
|
|
352
|
+
json: { agent: agent.id, project_path: process.cwd(), start_pairing: true },
|
|
353
|
+
});
|
|
354
|
+
if (!result.ok) {
|
|
355
|
+
process.stdout.write(
|
|
356
|
+
`Note: could not start pairing (${result.status_code}); the config still works, ` +
|
|
357
|
+
"your agent will link on its first PreMan call.\n"
|
|
358
|
+
);
|
|
359
|
+
return "";
|
|
360
|
+
}
|
|
361
|
+
return String(result.pair_code || "");
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export async function waitForConnection(
|
|
365
|
+
args,
|
|
366
|
+
apiKey,
|
|
367
|
+
{
|
|
368
|
+
intervalMs = Number(process.env.PREMAN_CONNECT_POLL_MS) || 3000,
|
|
369
|
+
timeoutMs = Number(process.env.PREMAN_CONNECT_WAIT_MS) || 300000,
|
|
370
|
+
} = {}
|
|
371
|
+
) {
|
|
372
|
+
const deadline = Date.now() + timeoutMs;
|
|
373
|
+
let interrupted = false;
|
|
374
|
+
const onInterrupt = () => {
|
|
375
|
+
interrupted = true;
|
|
376
|
+
};
|
|
377
|
+
process.on("SIGINT", onInterrupt);
|
|
378
|
+
|
|
379
|
+
try {
|
|
380
|
+
while (Date.now() < deadline && !interrupted) {
|
|
381
|
+
const status = await callBackendJson(args, "GET", "/workbench/coding-agent", {
|
|
382
|
+
token: apiKey,
|
|
383
|
+
});
|
|
384
|
+
if (status.ok && status.connected) return true;
|
|
385
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
386
|
+
}
|
|
387
|
+
} finally {
|
|
388
|
+
process.off("SIGINT", onInterrupt);
|
|
389
|
+
}
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ── Dispatch credential (SCRUM-124) ─────────────────────────────────────
|
|
394
|
+
|
|
395
|
+
async function captureDispatchCredential(args, agent, apiKey) {
|
|
396
|
+
if (!agent.dispatch) return;
|
|
397
|
+
if (args.has("--skip-dispatch-credential")) return;
|
|
398
|
+
|
|
399
|
+
let secret = args.value("--dispatch-credential", "");
|
|
400
|
+
let routineId = args.value("--routine-id", "");
|
|
401
|
+
|
|
402
|
+
if (!secret) {
|
|
403
|
+
if (!process.stdin.isTTY) return;
|
|
404
|
+
process.stdout.write(
|
|
405
|
+
`\nOptional: paste a ${agent.dispatch.credential} so PreMan can start ${agent.label} runs for you.\n`
|
|
406
|
+
);
|
|
407
|
+
secret = await promptSecret("(Enter to skip): ");
|
|
408
|
+
if (!secret) return;
|
|
409
|
+
if (agent.dispatch.needsRoutine && !routineId) {
|
|
410
|
+
routineId = await promptText("Routine id or URL: ");
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (agent.dispatch.needsRoutine && !routineId) {
|
|
415
|
+
process.stdout.write("Skipped: a routine id is required alongside the token.\n");
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const body = agent.dispatch.needsRoutine
|
|
420
|
+
? { provider: agent.id, secret, routine_id: extractRoutineId(routineId) }
|
|
421
|
+
: { provider: agent.id, secret };
|
|
422
|
+
|
|
423
|
+
const result = await callBackendJson(args, "PUT", "/workbench/coding-agent/dispatch", {
|
|
424
|
+
token: apiKey,
|
|
425
|
+
json: body,
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
if (result.ok) {
|
|
429
|
+
process.stdout.write("Cloud dispatch enabled — PreMan can now start runs for you.\n");
|
|
430
|
+
} else if (result.status_code === 404 || result.status_code === 405) {
|
|
431
|
+
process.stdout.write("Note: this PreMan backend does not support cloud dispatch yet; skipped.\n");
|
|
432
|
+
} else {
|
|
433
|
+
process.stdout.write(`Note: could not save the credential (${result.status_code}); skipped.\n`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Accept either a bare trig_… id or the routine URL it appears in. */
|
|
438
|
+
export function extractRoutineId(value) {
|
|
439
|
+
const raw = String(value || "").trim();
|
|
440
|
+
const match = raw.match(/trig_[A-Za-z0-9]+/);
|
|
441
|
+
return match ? match[0] : raw;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ── Guided first run ────────────────────────────────────────────────────
|
|
445
|
+
|
|
446
|
+
const MANUAL_STEPS =
|
|
447
|
+
" preman endpoints discover # brief for your agent → endpoints.json\n" +
|
|
448
|
+
" preman endpoints setup --file endpoints.json # register runnable requests\n" +
|
|
449
|
+
" preman test <request-id> # generate + run your first scenarios\n";
|
|
450
|
+
|
|
451
|
+
function nextStepsBlock(agent) {
|
|
452
|
+
return (
|
|
453
|
+
"\nNext steps:\n" +
|
|
454
|
+
` 1. Restart ${agent.label}, then ask it: "run preman_status" to finish linking.\n` +
|
|
455
|
+
" 2. preman endpoints discover # brief for your agent → endpoints.json\n" +
|
|
456
|
+
" 3. preman endpoints setup --file endpoints.json # register runnable requests\n" +
|
|
457
|
+
" 4. preman test <request-id> # generate + run your first scenarios\n"
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function confirm(question) {
|
|
462
|
+
const answer = (await promptText(`${question} [Y/n]: `)).toLowerCase();
|
|
463
|
+
return answer === "" || answer.startsWith("y");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Carry a freshly linked agent to its first passing test.
|
|
468
|
+
*
|
|
469
|
+
* Discovery itself belongs to the coding agent — the backend hands back a brief
|
|
470
|
+
* for it to execute — so this either runs a test against what the account
|
|
471
|
+
* already has, or prints that brief and the two commands that follow it.
|
|
472
|
+
*
|
|
473
|
+
* Never throws: onboarding help must not turn a successful connect into a failure.
|
|
474
|
+
*/
|
|
475
|
+
async function guidedFirstRun(args, agent) {
|
|
476
|
+
try {
|
|
477
|
+
const inventory = await callPremanTool(args, "get_endpoints", {
|
|
478
|
+
include_workbench: true,
|
|
479
|
+
limit: 50,
|
|
480
|
+
});
|
|
481
|
+
const runnable = (inventory.workbench_requests || [])[0];
|
|
482
|
+
const registered = (inventory.endpoints || []).length;
|
|
483
|
+
|
|
484
|
+
if (runnable) {
|
|
485
|
+
const label = `${runnable.method || "GET"} ${runnable.url || ""}`.trim();
|
|
486
|
+
if (!(await confirm(`\nRun a first test against ${label}?`))) {
|
|
487
|
+
process.stdout.write(`Whenever you are ready: preman test ${runnable.id}\n`);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
process.stdout.write("Generating scenarios…\n");
|
|
491
|
+
const result = await callPremanTool(args, "generate_endpoint_tests", {
|
|
492
|
+
target: runnable.id,
|
|
493
|
+
run: true,
|
|
494
|
+
allow_writes: false,
|
|
495
|
+
max_cases: 10,
|
|
496
|
+
});
|
|
497
|
+
printTestSummary(result);
|
|
498
|
+
process.stdout.write(`\nAdd your own: preman test ${runnable.id} --scenario "..."\n`);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (registered) {
|
|
503
|
+
process.stdout.write(
|
|
504
|
+
`\nYou have ${registered} registered endpoint(s), but none are runnable yet:\n` +
|
|
505
|
+
" preman endpoints setup --ids <id1,id2> # make them runnable\n" +
|
|
506
|
+
" preman test <request-id> # generate + run your first scenarios\n"
|
|
507
|
+
);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
if (!(await confirm("\nNo endpoints in PreMan yet. Print the discovery brief for your agent?"))) {
|
|
512
|
+
process.stdout.write(`\nWhen you are ready:\n${MANUAL_STEPS}`);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const brief = await callPremanTool(args, "discover_endpoints_from_codebase", { base_path: "." });
|
|
517
|
+
for (const line of brief.instructions || []) process.stdout.write(`${line}\n`);
|
|
518
|
+
process.stdout.write(
|
|
519
|
+
`\nHand this brief to ${agent.label}, then run:\n` +
|
|
520
|
+
" preman endpoints setup --file endpoints.json\n" +
|
|
521
|
+
" preman test <request-id>\n"
|
|
522
|
+
);
|
|
523
|
+
} catch (error) {
|
|
524
|
+
process.stdout.write(
|
|
525
|
+
`Note: ${error.message}. Run \`preman endpoints list\` when you are ready.\n`
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ── Preflight ───────────────────────────────────────────────────────────
|
|
531
|
+
|
|
532
|
+
const MIN_NODE_MAJOR = 18;
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Verify the machine can actually run the config we are about to write.
|
|
536
|
+
* Hard-fails only on a Node that cannot run the server; everything else is a
|
|
537
|
+
* warning — connect must keep working offline and behind odd shells.
|
|
538
|
+
*/
|
|
539
|
+
export async function preflight(args) {
|
|
540
|
+
const problems = [];
|
|
541
|
+
const notes = [];
|
|
542
|
+
|
|
543
|
+
const major = Number(process.versions.node.split(".")[0]);
|
|
544
|
+
if (Number.isFinite(major) && major < MIN_NODE_MAJOR) {
|
|
545
|
+
problems.push(
|
|
546
|
+
`Node ${process.versions.node} is too old — the PreMan MCP server needs Node ${MIN_NODE_MAJOR}+.`
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (!onPath("npx")) {
|
|
551
|
+
notes.push(
|
|
552
|
+
"npx was not found on PATH; the written config launches PreMan via npx, so make sure your agent's environment has it."
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
try {
|
|
557
|
+
const resp = await fetch(new URL("health", `${backendUrl(args)}/`), {
|
|
558
|
+
signal: AbortSignal.timeout(4000),
|
|
559
|
+
});
|
|
560
|
+
if (!resp.ok) {
|
|
561
|
+
notes.push(`PreMan backend ${backendUrl(args)} answered ${resp.status}; connect will continue but calls may fail.`);
|
|
562
|
+
}
|
|
563
|
+
} catch {
|
|
564
|
+
notes.push(`Could not reach ${backendUrl(args)}; connect will continue but pairing and logins need it.`);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
for (const note of notes) process.stdout.write(`Note: ${note}\n`);
|
|
568
|
+
if (problems.length) {
|
|
569
|
+
throw new ConnectError(problems.join("\n"), EXIT_USAGE);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// ── Command ─────────────────────────────────────────────────────────────
|
|
574
|
+
|
|
575
|
+
export const CONNECT_HELP = `
|
|
576
|
+
Connect options:
|
|
577
|
+
--agent <name> cursor | claude-code | codex (skips the picker)
|
|
578
|
+
--project Write project-local config instead of the user config
|
|
579
|
+
--api-key <key> PreMan API key. If omitted, stored credentials are used
|
|
580
|
+
--email <email> Pre-fill the email prompt when logging in
|
|
581
|
+
--backend <url> PreMan backend URL
|
|
582
|
+
--frontend <url> PreMan frontend URL
|
|
583
|
+
--name <name> MCP server name. Defaults to preman
|
|
584
|
+
--dispatch-credential <t> Cloud-dispatch token (non-interactive)
|
|
585
|
+
--routine-id <id> Claude Code routine id, with --dispatch-credential
|
|
586
|
+
--skip-dispatch-credential Do not ask for a cloud-dispatch credential
|
|
587
|
+
--skip-login Write config without interactive terminal auth
|
|
588
|
+
--no-pair Do not mint a pair code
|
|
589
|
+
--no-wait Do not wait for the agent to check in
|
|
590
|
+
--no-guide Skip the guided first run after connecting
|
|
591
|
+
--print Print the config instead of writing it
|
|
592
|
+
`;
|
|
593
|
+
|
|
594
|
+
export async function connectCommand(commandArgs) {
|
|
595
|
+
const args = makeArgs(commandArgs);
|
|
596
|
+
const serverName = args.value("--name", "preman");
|
|
597
|
+
const projectInstall = args.has("--project");
|
|
598
|
+
const printOnly = args.has("--print");
|
|
599
|
+
const interactive = Boolean(process.stdin.isTTY);
|
|
600
|
+
|
|
601
|
+
let agent = findAgent(args.value("--agent", ""));
|
|
602
|
+
if (!agent && args.value("--agent", "")) {
|
|
603
|
+
throw new ConnectError(
|
|
604
|
+
`Unknown agent: ${args.value("--agent", "")}. Use cursor, claude-code, or codex.`,
|
|
605
|
+
EXIT_USAGE
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
if (!agent) {
|
|
610
|
+
if (!interactive) {
|
|
611
|
+
// Nothing to prompt on, so leave behind everything a CI log needs to
|
|
612
|
+
// finish the setup by hand rather than just the reason it stopped.
|
|
613
|
+
process.stdout.write(
|
|
614
|
+
`preman connect needs a terminal to pick an agent. Copy-paste setup instead:\n\n${renderAllAgentSnippets(args, serverName, { projectInstall })}\n` +
|
|
615
|
+
'Then restart your agent and ask it: "run preman_status".\n' +
|
|
616
|
+
"Or rerun: preman connect --agent <cursor|claude-code|codex> --api-key pm_live_…\n"
|
|
617
|
+
);
|
|
618
|
+
throw new ConnectError(
|
|
619
|
+
"preman connect needs a terminal. In CI pass --agent <cursor|claude-code|codex> " +
|
|
620
|
+
"and --api-key pm_live_… (or --print), or use one of the snippets above.",
|
|
621
|
+
EXIT_USAGE
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
agent = await promptAgentChoice(detectAgents());
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
if (!printOnly) {
|
|
628
|
+
// Verify the machine can run what we are about to write — before any
|
|
629
|
+
// config edits or logins, so failures leave nothing half-done.
|
|
630
|
+
await preflight(args);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (printOnly) {
|
|
634
|
+
const serverConfig = buildServerConfig(args);
|
|
635
|
+
if (agent.id === "codex") {
|
|
636
|
+
process.stdout.write(renderCodexToml(serverName, serverConfig));
|
|
637
|
+
} else {
|
|
638
|
+
process.stdout.write(`${JSON.stringify({ mcpServers: { [serverName]: serverConfig } }, null, 2)}\n`);
|
|
639
|
+
}
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
if (!args.has("--skip-login") && !hasKeyAvailable(args)) {
|
|
644
|
+
if (!interactive) {
|
|
645
|
+
throw new ConnectError(
|
|
646
|
+
"No PreMan credentials. Pass --api-key pm_live_… or set PREMAN_API_KEY.",
|
|
647
|
+
EXIT_USAGE
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
process.stdout.write("First, let's connect your PreMan account.\n");
|
|
651
|
+
await authenticateTerminal(args);
|
|
652
|
+
process.stdout.write("\n");
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const apiKey = resolveApiKey(args);
|
|
656
|
+
|
|
657
|
+
let pairCode = "";
|
|
658
|
+
if (apiKey && !args.has("--no-pair")) {
|
|
659
|
+
pairCode = await startPairing(args, agent, apiKey);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const serverConfig = buildServerConfig(args, { pairCode });
|
|
663
|
+
const written = WRITERS[agent.id]({ serverName, serverConfig, projectInstall });
|
|
664
|
+
|
|
665
|
+
process.stdout.write(
|
|
666
|
+
`\n${agent.label} connected: ${written.how} ${written.path}\n` +
|
|
667
|
+
`Server name: ${serverName}\n` +
|
|
668
|
+
`Backend: ${serverConfig.env.PREMAN_BACKEND}\n`
|
|
669
|
+
);
|
|
670
|
+
|
|
671
|
+
const verification = verifyWrittenConfig(agent, { serverName, written });
|
|
672
|
+
if (verification.status === "mismatch") {
|
|
673
|
+
// Generate hint that matches the actual install location
|
|
674
|
+
let hint = agent.snippetHint;
|
|
675
|
+
if (agent.id === "cursor" && projectInstall) {
|
|
676
|
+
hint = "merge into .cursor/mcp.json";
|
|
677
|
+
} else if (agent.id === "claude_code") {
|
|
678
|
+
hint = projectInstall ? "run (with --scope project):" : "run:";
|
|
679
|
+
}
|
|
680
|
+
process.stdout.write(
|
|
681
|
+
`\nWarning: could not confirm the ${agent.label} config (${verification.detail}).\n` +
|
|
682
|
+
`Apply it by hand — ${hint}\n\n` +
|
|
683
|
+
renderAgentSnippet(agent.id, serverName, serverConfig, { projectInstall })
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// Not gated on TTY: --dispatch-credential is the non-interactive path, and the
|
|
688
|
+
// prompt inside only runs when there is a terminal to prompt on.
|
|
689
|
+
await captureDispatchCredential(args, agent, apiKey);
|
|
690
|
+
|
|
691
|
+
if (!pairCode || args.has("--no-wait") || !interactive) {
|
|
692
|
+
process.stdout.write(nextStepsBlock(agent));
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
process.stdout.write(
|
|
697
|
+
`\nRestart ${agent.label} and ask it: "run preman_status"\n` +
|
|
698
|
+
"Waiting for your agent to check in… (Ctrl+C to stop waiting)\n"
|
|
699
|
+
);
|
|
700
|
+
|
|
701
|
+
if (!(await waitForConnection(args, apiKey))) {
|
|
702
|
+
process.stdout.write(
|
|
703
|
+
"No check-in yet. Troubleshooting:\n" +
|
|
704
|
+
` - ${agent.restartHint}\n` +
|
|
705
|
+
` - Config written to: ${written.path}\n` +
|
|
706
|
+
` - Then ask ${agent.label} to "run preman_status" — it links on its first PreMan call.\n`
|
|
707
|
+
);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
process.stdout.write(`Connected as ${agent.label}.\n`);
|
|
712
|
+
if (!args.has("--no-guide")) {
|
|
713
|
+
await guidedFirstRun(args, agent);
|
|
714
|
+
}
|
|
715
|
+
}
|