premanmcp 1.1.18 → 1.1.20

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.
@@ -0,0 +1,109 @@
1
+ /** Shared desktop/CLI credential store. Never persist desktop session JWTs here. */
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ export function credentialPath(homedir = os.homedir()) {
8
+ return path.join(homedir, ".preman", "credentials.json");
9
+ }
10
+
11
+ export function credentialOrigin(value) {
12
+ const url = new URL(value || "https://api.preman.live");
13
+ if (url.username || url.password || url.search || url.hash || !["http:", "https:"].includes(url.protocol)) {
14
+ throw new Error("Invalid PreMan backend URL");
15
+ }
16
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
17
+ throw new Error("PreMan credentials require HTTPS, except on localhost");
18
+ }
19
+ return url.href.replace(/\/+$/, "");
20
+ }
21
+
22
+ function readStore(homedir) {
23
+ const file = credentialPath(homedir);
24
+ try {
25
+ const stat = lstatSync(file);
26
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) return {};
27
+ return JSON.parse(readFileSync(file, "utf8"));
28
+ } catch { return {}; }
29
+ }
30
+
31
+ function profile(raw) {
32
+ if (!raw || typeof raw.api_key !== "string" || !raw.api_key.startsWith("pm_live_")) return null;
33
+ // Older clients may have saved a custom development host. Reading is compatible;
34
+ // machine clients enforce origin/security constraints before transmitting it.
35
+ const result = {};
36
+ for (const key of ["api_key", "backend_url", "frontend_url", "user_id", "user_email", "key_id", "device_name", "created_at", "expires_at", "scopes"]) {
37
+ if (raw[key] != null) result[key] = raw[key];
38
+ }
39
+ result.backend_url ||= "https://api.preman.live";
40
+ return result;
41
+ }
42
+
43
+ export function readCredentials({ homedir = os.homedir(), backend, accountId } = {}) {
44
+ const store = readStore(homedir);
45
+ const active = profile(store);
46
+ const profiles = [active, ...Object.values(store.profiles || {}).map(profile)].filter(Boolean);
47
+ return profiles.find((item) => (!backend || item.backend_url.replace(/\/+$/, "") === backend.replace(/\/+$/, ""))
48
+ && (accountId == null || String(item.user_id) === String(accountId))) || null;
49
+ }
50
+
51
+ export function writeCredentials(raw, { homedir = os.homedir() } = {}) {
52
+ const selected = profile(raw);
53
+ if (!selected) throw new Error("A valid PreMan machine API key is required");
54
+ const file = credentialPath(homedir);
55
+ const directory = path.dirname(file);
56
+ if (existsSync(directory) && lstatSync(directory).isSymbolicLink()) throw new Error("Credential directory must not be a symbolic link");
57
+ if (existsSync(file) && lstatSync(file).isSymbolicLink()) throw new Error("Credential file must not be a symbolic link");
58
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
59
+ chmodSync(directory, 0o700);
60
+ const existing = readStore(homedir);
61
+ const profiles = { ...(existing.profiles || {}) };
62
+ const idFor = (item) => createHash("sha256").update(`${item.backend_url}\n${item.user_id ?? item.user_email ?? "default"}`).digest("hex");
63
+ const old = profile(existing);
64
+ if (old) profiles[idFor(old)] = old;
65
+ const id = idFor(selected);
66
+ profiles[id] = selected;
67
+ // The active profile remains at the top level for already-installed stdio
68
+ // proxies. New callers select by backend and account from the same file.
69
+ const next = { schema_version: "1.0", active_profile: id, profiles, ...selected };
70
+ const temporary = `${file}.${randomUUID()}.tmp`;
71
+ try {
72
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
73
+ chmodSync(temporary, 0o600);
74
+ renameSync(temporary, file);
75
+ } finally { rmSync(temporary, { force: true }); }
76
+ return selected;
77
+ }
78
+
79
+ export function clearCredentials({ homedir = os.homedir(), backend, accountId } = {}) {
80
+ const file = credentialPath(homedir);
81
+ const existed = existsSync(file);
82
+ if (existed && (backend || accountId != null)) {
83
+ const store = readStore(homedir);
84
+ const profiles = { ...(store.profiles || {}) };
85
+ const matches = (item) => (!backend || item?.backend_url?.replace(/\/+$/, "") === backend.replace(/\/+$/, ""))
86
+ && (accountId == null || String(item?.user_id) === String(accountId));
87
+ for (const [id, item] of Object.entries(profiles)) if (matches(item)) delete profiles[id];
88
+ const selectedId = profiles[store.active_profile] ? store.active_profile : Object.keys(profiles)[0];
89
+ if (selectedId) {
90
+ const next = { schema_version: "1.0", active_profile: selectedId, profiles, ...profile(profiles[selectedId]) };
91
+ const temporary = `${file}.${randomUUID()}.tmp`;
92
+ try { writeFileSync(temporary, `${JSON.stringify(next)}\n`, { mode: 0o600, flag: "wx" }); renameSync(temporary, file); }
93
+ finally { rmSync(temporary, { force: true }); }
94
+ return true;
95
+ }
96
+ if (!matches(store) && profile(store)) return false;
97
+ }
98
+ rmSync(file, { force: true });
99
+ return existed;
100
+ }
101
+
102
+ export function credentialSummary(credentials) {
103
+ if (!credentials) return { authenticated: false };
104
+ return {
105
+ authenticated: true, backend_url: credentials.backend_url,
106
+ account_id: credentials.user_id ?? null, key_id: credentials.key_id ?? null,
107
+ expires_at: credentials.expires_at ?? null, scopes: credentials.scopes ?? null,
108
+ };
109
+ }
@@ -0,0 +1,54 @@
1
+ /** Same-user loopback client. Explicit execution may wake the installed background app. */
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawn } from "node:child_process";
6
+ import { boundedResponse, TaskClientError } from "./task_client.js";
7
+
8
+ export async function callDesktop(route, options = {}) {
9
+ try { return await requestDesktop(route, options); }
10
+ catch (error) {
11
+ const executable = process.env.PREMAN_DESKTOP_EXECUTABLE;
12
+ const startRequested = /\/(?:delegated-start|delegated-prepare|preview)$/.test(route);
13
+ if (error.code !== "desktop_unavailable" || !startRequested || !executable || !path.isAbsolute(executable)) throw error;
14
+ try { if (!lstatSync(executable).isFile()) throw error; } catch { throw error; }
15
+ const env = {};
16
+ for (const name of ["PATH", "HOME", "USERPROFILE", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DISPLAY", "WAYLAND_DISPLAY"]) if (process.env[name]) env[name] = process.env[name];
17
+ if (options.backend) { env.PREMAN_BACKEND = options.backend; env.PREMAN_API_URL = options.backend; }
18
+ const child = spawn(executable, ["--preman-background"], { env, detached: true, stdio: "ignore", windowsHide: true });
19
+ let launchFailed = false; child.once("error", () => { launchFailed = true; }); child.unref();
20
+ for (let i = 0; i < 40 && !launchFailed; i++) {
21
+ await new Promise((resolve) => setTimeout(resolve, 250));
22
+ try { return await requestDesktop(route, options); } catch (next) { if (next.code !== "desktop_unavailable") throw next; }
23
+ }
24
+ throw error;
25
+ }
26
+ }
27
+ async function requestDesktop(route, { body, backend, binary = false, homedir = os.homedir(), fetchImpl = fetch } = {}) {
28
+ let descriptor;
29
+ try {
30
+ const file = path.join(homedir, ".preman", "desktop-control.json");
31
+ const info = lstatSync(file);
32
+ if (!info.isFile() || info.size > 4096 || (process.platform !== "win32" && (info.mode & 0o077))) throw new Error("Invalid descriptor");
33
+ descriptor = JSON.parse(readFileSync(file, "utf8"));
34
+ } catch { throw new TaskClientError("desktop_unavailable", "Open the installed PreMan app to use its local controller and preview renderer"); }
35
+ const url = new URL(descriptor.url);
36
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || url.username || url.password || url.pathname !== "/" || url.search || url.hash || !/^[A-Za-z0-9_-]{43}$/.test(descriptor.token || "")) throw new TaskClientError("invalid_desktop_descriptor", "The desktop control descriptor is invalid");
37
+ if (backend && descriptor.backend_url?.replace(/\/+$/, "") !== backend.replace(/\/+$/, "")) throw new TaskClientError("desktop_backend_mismatch", "The desktop is connected to a different PreMan backend");
38
+ if (!/^\/v1\/(?:status|disconnect|preview|flow\/(?:status|capabilities|stop|delegated-start)|app-qa\/(?:status|capabilities|preflight|start|pause|resume|stop|delegated-prepare|delegated-start))$/.test(route)) throw new TaskClientError("invalid_argument", "Unsupported desktop operation");
39
+ let response;
40
+ try {
41
+ response = await fetchImpl(`${url.origin}${route}`, { method: body == null ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(30_000),
42
+ headers: { Authorization: `Bearer ${descriptor.token}`, ...(body == null ? {} : { "Content-Type": "application/json" }) }, body: body == null ? undefined : JSON.stringify(body) });
43
+ } catch { throw new TaskClientError("desktop_unavailable", "The PreMan desktop is not responding; open it and retry", { retryable: true }); }
44
+ const bytes = await boundedResponse(response, binary ? 32 * 1024 * 1024 : 1024 * 1024);
45
+ if (!response.ok) {
46
+ let error; try { error = JSON.parse(bytes.toString("utf8")).error; } catch {}
47
+ throw new TaskClientError(error?.code || "desktop_request_failed", error?.message || "The desktop could not complete this operation", { status: response.status });
48
+ }
49
+ if (binary) {
50
+ if (!response.headers.get("content-type")?.startsWith("image/png")) throw new TaskClientError("invalid_preview", "Desktop preview was not a PNG image");
51
+ return bytes;
52
+ }
53
+ return JSON.parse(bytes.toString("utf8"));
54
+ }
package/bin/eval.js CHANGED
@@ -48,6 +48,7 @@ import { download, progressLine } from "./desktop.js";
48
48
  import { repoEnv } from "./detect.js";
49
49
  import { adapterStats, discoverTarget, startAdapter, stepFeed } from "./eval_target.js";
50
50
  import { ensureRuntime } from "./eval_runtime.js";
51
+ import { dockerCommand, dockerReadiness } from "./task_repair_container.js";
51
52
  import { formatSurfaceLink, resolveEvalSurface } from "./link.js";
52
53
  import {
53
54
  backendUrl,
@@ -124,6 +125,31 @@ export async function cancelEvalRuns() {
124
125
  return pending.length;
125
126
  }
126
127
 
128
+ /** Only the stock sandbox resources labelled by this leased run may be removed. */
129
+ export async function cleanupEvalSandbox(job) {
130
+ if (job.target_kind !== "sandbox" || job.sandbox_kind === "endpoint") return true;
131
+ if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(String(job.id || ""))) return false;
132
+ if (!(await dockerReadiness()).ready) return false;
133
+ const filter = `label=preman.eval_run=${job.id}`;
134
+ const resources = async (kind) => {
135
+ const result = await dockerCommand(kind === "container" ? ["ps", "--all", "--quiet", "--filter", filter] : ["network", "ls", "--quiet", "--filter", filter], { timeoutMs: 10000 });
136
+ if (result.exit_code !== 0) return null;
137
+ const ids = result.output.trim().split(/\s+/).filter(Boolean);
138
+ return ids.length <= 1000 && ids.every((id) => /^[a-f0-9]{12,64}$/.test(id)) ? ids : null;
139
+ };
140
+ for (const kind of ["container", "network"]) {
141
+ const ids = await resources(kind);
142
+ if (ids === null) return false;
143
+ for (const id of ids) {
144
+ const removed = await dockerCommand(kind === "container" ? ["rm", "--force", id] : ["network", "rm", id], { timeoutMs: 10000 });
145
+ if (removed.exit_code !== 0) return false;
146
+ }
147
+ const remaining = await resources(kind);
148
+ if (remaining === null || remaining.length) return false;
149
+ }
150
+ return true;
151
+ }
152
+
127
153
  // ── Where a suite lives between runs ────────────────────────────────────
128
154
 
129
155
  /** Everything this machine keeps about evals it has run. */
@@ -1256,6 +1282,10 @@ export async function executeEvalRun(
1256
1282
  return { ok: false, reason: "no_lease" };
1257
1283
  }
1258
1284
  const route = (leaf) => `/workbench/coding-agent/local-runner/evals/${job.id}/${leaf}`;
1285
+ const acknowledgeStopped = async () => {
1286
+ if (!await cleanupEvalSandbox(job)) { log(`eval ${job.id}: sandbox cleanup could not be confirmed; no stopped acknowledgement sent`); return; }
1287
+ return report(call, route("stopped"), { lease_token: lease }, log);
1288
+ };
1259
1289
 
1260
1290
  const finish = async (ok, { summary = {}, error = "", exitCode = null } = {}) => {
1261
1291
  const result = await report(
@@ -1333,6 +1363,7 @@ export async function executeEvalRun(
1333
1363
  const handoff = await awaitAudience(job, { call, log, lease, headless, surface });
1334
1364
  if (handoff.lost) {
1335
1365
  tidy(home);
1366
+ await acknowledgeStopped();
1336
1367
  return { ok: false, reason: "lease_lost" };
1337
1368
  }
1338
1369
 
@@ -1347,18 +1378,49 @@ export async function executeEvalRun(
1347
1378
  const timeout = Math.min(RUN_TIMEOUT_MS, RUN_TIMEOUT_CAP_MS);
1348
1379
  const child = spawn(python.command, [...python.argv, HARNESS_PATH, "run", "--config", laid.configPath], {
1349
1380
  cwd: laid.cwd,
1350
- env: childEnv({ PREMAN_EVAL_RUN: `${job.suite}/${job.run}` }, { ...(job.env || {}), ...repoEnv(projectPath) }),
1381
+ env: childEnv({ PREMAN_EVAL_RUN: `${job.suite}/${job.run}`, PREMAN_EVAL_RUN_ID: String(job.id) }, { ...(job.env || {}), ...repoEnv(projectPath) }),
1351
1382
  stdio: ["ignore", "ignore", "pipe"],
1383
+ detached: process.platform !== "win32",
1352
1384
  });
1353
1385
 
1354
- const forgetChild = registerEvalTeardown(() => child.kill("SIGTERM"));
1355
-
1356
1386
  let stderr = "";
1357
1387
  child.stderr.on("data", (chunk) => {
1358
1388
  if (stderr.length < MAX_STDERR_BYTES) stderr += chunk.toString("utf8");
1359
1389
  });
1360
1390
 
1361
1391
  let lost = false;
1392
+ let forceStop;
1393
+ const signalGroup = (signal) => {
1394
+ if (!child.pid) return;
1395
+ try {
1396
+ if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000 });
1397
+ else process.kill(-child.pid, signal);
1398
+ } catch { /* A process already reaped is already stopped. */ }
1399
+ };
1400
+ const stopGroup = () => {
1401
+ signalGroup("SIGTERM");
1402
+ forceStop ||= setTimeout(() => signalGroup("SIGKILL"), 2000);
1403
+ };
1404
+ const groupStopped = async () => {
1405
+ if (!child.pid) return true;
1406
+ // A successful child exit alone cannot prove its descendants stopped.
1407
+ if (process.platform === "win32") return false;
1408
+ signalGroup("SIGKILL");
1409
+ for (let attempt = 0; attempt < 40; attempt++) {
1410
+ try { process.kill(-child.pid, 0); }
1411
+ catch (error) { return error.code === "ESRCH"; }
1412
+ await new Promise((resolve) => setTimeout(resolve, 50));
1413
+ }
1414
+ return false;
1415
+ };
1416
+ const childClosed = new Promise((resolve) => {
1417
+ child.on("error", (error) => { stderr += `\n${error.message}`; resolve(-1); });
1418
+ child.on("close", (code) => resolve(code === null ? -1 : code));
1419
+ });
1420
+ const forgetChild = registerEvalTeardown(async () => {
1421
+ lost = true; stopGroup(); await childClosed;
1422
+ if (await groupStopped()) await acknowledgeStopped();
1423
+ });
1362
1424
  let lastStage = "";
1363
1425
  let ticking = false;
1364
1426
  const sent = new Map();
@@ -1367,7 +1429,7 @@ export async function executeEvalRun(
1367
1429
  const lose = (why) => {
1368
1430
  lost = true;
1369
1431
  log(`eval ${job.id} is no longer leased to this device (${why}); stopping`);
1370
- child.kill("SIGTERM");
1432
+ stopGroup();
1371
1433
  };
1372
1434
 
1373
1435
  const heartbeat = setInterval(() => {
@@ -1422,18 +1484,13 @@ export async function executeEvalRun(
1422
1484
 
1423
1485
  const killer = setTimeout(() => {
1424
1486
  log(`eval ${job.id} exceeded ${Math.round(timeout / 60_000)} minutes; stopping it`);
1425
- child.kill("SIGKILL");
1487
+ signalGroup("SIGKILL");
1426
1488
  }, timeout);
1427
1489
 
1428
- const exitCode = await new Promise((resolve) => {
1429
- child.on("error", (error) => {
1430
- stderr += `\n${error.message}`;
1431
- resolve(-1);
1432
- });
1433
- child.on("close", (code) => resolve(code === null ? -1 : code));
1434
- });
1490
+ const exitCode = await childClosed;
1435
1491
  clearInterval(heartbeat);
1436
1492
  clearTimeout(killer);
1493
+ clearTimeout(forceStop);
1437
1494
  forgetChild();
1438
1495
 
1439
1496
  // Deliberately before the bundle is removed: the summary is read off the
@@ -1446,6 +1503,7 @@ export async function executeEvalRun(
1446
1503
  // else now, and this device reporting a result for it — or writing over its
1447
1504
  // artifacts — is the exact thing the fencing token exists to prevent.
1448
1505
  tidy(home);
1506
+ if (await groupStopped()) await acknowledgeStopped();
1449
1507
  return { ok: false, reason: "lease_lost" };
1450
1508
  }
1451
1509
 
@@ -1457,6 +1515,7 @@ export async function executeEvalRun(
1457
1515
  const final = await syncArtifacts(job, laid.cwd, sent, { call, log, lease });
1458
1516
  if (final.lost) {
1459
1517
  tidy(home);
1518
+ if (await groupStopped()) await acknowledgeStopped();
1460
1519
  return { ok: false, reason: "lease_lost" };
1461
1520
  }
1462
1521
 
@@ -792,6 +792,26 @@ if os.environ.get("PREMAN_EVAL_TRACE") == "1":
792
792
  _otel_session._spans_to_events = _spans_to_events_once
793
793
 
794
794
 
795
+ def _install_sandbox_ownership():
796
+ """Track stock per-case Docker resources so a killed harness can be cleaned."""
797
+ value = os.environ.get('PREMAN_EVAL_RUN_ID')
798
+ if not value:
799
+ return
800
+ from uuid import UUID
801
+ owner = str(UUID(value))
802
+ from assert_ai.integrations.sandbox import runtime
803
+ original = runtime._docker
804
+ def owned_docker(*args, **kwargs):
805
+ label = 'preman.eval_run=' + owner
806
+ if args and args[0] == 'run':
807
+ args = ('run', '--label', label, *args[1:])
808
+ elif args[:2] == ('network', 'create'):
809
+ args = ('network', 'create', '--label', label, *args[2:])
810
+ return original(*args, **kwargs)
811
+ runtime._docker = owned_docker
812
+
813
+
795
814
  if __name__ == "__main__":
815
+ _install_sandbox_ownership()
796
816
  _cli = next(e for e in entry_points(group="console_scripts") if e.name == "assert-ai")
797
817
  sys.exit(_cli.load()())
package/bin/harness.js ADDED
@@ -0,0 +1,48 @@
1
+ /** Deterministic installed-harness lifecycle; no model, login UI or credential output. */
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { registerInstalledAgents, installedAgentStatus, removeInstalledAgents } from './installed_registration.js';
5
+ import { readCredentials, clearCredentials, credentialOrigin } from './credentials.js';
6
+ import { makeArgs } from './shared.js';
7
+ import { callDesktop } from './desktop_client.js';
8
+ import { TaskClientError } from './task_client.js';
9
+
10
+ export const HARNESS_HELP = `
11
+ Installed coding-agent integrations (JSON output):
12
+ harness status Inspect managed MCP registration
13
+ harness install [--launcher <path>] Register installed Codex, Claude Code and Cursor
14
+ harness remove Remove unchanged managed MCP config and instructions
15
+ harness remove --disconnect --remove-launcher
16
+ Stop local executors, revoke this machine key, and remove integration
17
+ A fresh coding-agent session loads the new MCP configuration. Existing sessions may need restart.
18
+ `;
19
+ export async function harnessCommand(argv) {
20
+ const args = makeArgs(argv); const operation = argv[0] || 'status';
21
+ let result;
22
+ if (operation === 'status') result = installedAgentStatus();
23
+ else if (operation === 'install') {
24
+ const stored = readCredentials() || {};
25
+ const launcher = args.value('--launcher', process.env.PREMAN_CLI_EXECUTABLE || path.join(os.homedir(), '.local', 'bin', process.platform === 'win32' ? 'preman.cmd' : 'preman'));
26
+ result = { schema_version: '1.0', ...registerInstalledAgents({ launcherPath: path.resolve(launcher), backendUrl: credentialOrigin(args.value('--backend', stored.backend_url || process.env.PREMAN_BACKEND || 'https://api.preman.live')),
27
+ frontendUrl: stored.frontend_url || 'https://app.preman.live', accountId: stored.user_id }) };
28
+ } else if (operation === 'remove') {
29
+ let disconnected;
30
+ if (args.has('--disconnect')) {
31
+ try { disconnected = await callDesktop('/v1/disconnect', { body: {} }); }
32
+ catch (error) {
33
+ if (error.code !== 'desktop_unavailable') throw error;
34
+ const stored = readCredentials();
35
+ if (stored?.key_id) {
36
+ const response = await fetch(`${credentialOrigin(stored.backend_url)}/api-keys/${encodeURIComponent(stored.key_id)}`, { method: 'DELETE', redirect: 'error', signal: AbortSignal.timeout(15000), headers: { Authorization: `Bearer ${stored.api_key}` } });
37
+ if (!response.ok && response.status !== 404 && response.status !== 401) throw new TaskClientError('revocation_required', 'The backend did not confirm machine-key revocation; retry removal when reachable');
38
+ } else if (stored?.api_key) throw new TaskClientError('revocation_required', 'This legacy key has no revocation ID. Revoke it in PreMan before removing the connection');
39
+ clearCredentials({ backend: stored?.backend_url, accountId: stored?.user_id });
40
+ disconnected = { cleared: true, revoked: true, local_stopped: true };
41
+ }
42
+ if (!disconnected.revoked || disconnected.local_stopped === false) throw new TaskClientError('disconnect_incomplete', 'Machine-key revocation or executor shutdown could not be confirmed');
43
+ }
44
+ result = { ...removeInstalledAgents({ removeLauncher: args.has('--remove-launcher') }), ...(disconnected ? { disconnected } : {}) };
45
+ } else throw new TaskClientError('invalid_argument', 'Use harness status|install|remove');
46
+ process.stdout.write(`${JSON.stringify(result)}\n`);
47
+ return result.agents?.some((item) => ['conflict', 'configuration_failed', 'modified_preserved'].includes(item.state) || item.cli_approval === 'approval_required') ? 2 : 0;
48
+ }
package/bin/hook.js CHANGED
@@ -100,6 +100,7 @@ export function invocationAnswers(invocation) {
100
100
  try {
101
101
  const probe = spawnSync(`${invocation} help`, {
102
102
  shell: true,
103
+ env: { ...process.env, PREMAN_NO_HOOK_REPAIR: "1" },
103
104
  encoding: "utf8",
104
105
  timeout: Number(process.env.PREMAN_HOOK_PROBE_MS) || PROBE_TIMEOUT_MS,
105
106
  stdio: ["ignore", "pipe", "pipe"],
@@ -195,7 +196,11 @@ function shellSingleQuote(value) {
195
196
  return `'${String(value).replace(/'/g, `'\\''`)}'`;
196
197
  }
197
198
 
198
- function hookBody(invocation) {
199
+ function hookIsReadOnly(text) {
200
+ return /^\s*PREMAN_HOOK=1 .+ verify --pre-push\b[^\n]*\s--read-only(?:\s|$)/m.test(text);
201
+ }
202
+
203
+ function hookBody(invocation, { readOnly = false } = {}) {
199
204
  // `exec` is deliberately absent: we want the wrapper to survive the CLI exiting
200
205
  // non-zero and still exit 0 itself.
201
206
  //
@@ -217,10 +222,10 @@ ${MARKER}
217
222
  # makes the second attempt the one that works.
218
223
  if [ -z "\${PREMAN_SKIP_HOOK}" ]; then
219
224
  PREMAN_HOOK_BIN=${shellSingleQuote(path.dirname(process.execPath))}
220
- PREMAN_HOOK=1 ${invocation} verify --pre-push --timeout ${HOOK_TIMEOUT_SECONDS}
225
+ PREMAN_HOOK=1 ${invocation} verify --pre-push${readOnly ? " --read-only" : ""} --timeout ${HOOK_TIMEOUT_SECONDS}
221
226
  preman_status=$?
222
227
  if [ "$preman_status" -eq 127 ] && [ -d "$PREMAN_HOOK_BIN" ]; then
223
- PATH="$PREMAN_HOOK_BIN:$PATH" PREMAN_HOOK=1 ${invocation} verify --pre-push --timeout ${HOOK_TIMEOUT_SECONDS}
228
+ PATH="$PREMAN_HOOK_BIN:$PATH" PREMAN_HOOK=1 ${invocation} verify --pre-push${readOnly ? " --read-only" : ""} --timeout ${HOOK_TIMEOUT_SECONDS}
224
229
  preman_status=$?
225
230
  fi
226
231
  if [ "$preman_status" -eq ${BLOCK_EXIT_CODE} ]; then
@@ -264,11 +269,11 @@ export function installHook(args, { invocation } = {}) {
264
269
  };
265
270
  }
266
271
 
267
- const body = hookBody(resolved);
272
+ const existing = existsSync(target) ? readFileSync(target, "utf8") : "";
273
+ const body = hookBody(resolved, { readOnly: isOurHook(existing) && hookIsReadOnly(existing) });
268
274
  mkdirSync(path.dirname(target), { recursive: true });
269
275
 
270
276
  if (existsSync(target)) {
271
- const existing = readFileSync(target, "utf8");
272
277
  if (isOurHook(existing)) {
273
278
  writeFileSync(target, body, { mode: 0o755 });
274
279
  chmodSync(target, 0o755);
@@ -351,7 +356,7 @@ export function hookStatus({ probe = false } = {}) {
351
356
  path: target,
352
357
  state: "installed",
353
358
  invocation,
354
- current: Boolean(wanted) && existing === hookBody(wanted),
359
+ current: Boolean(wanted) && existing === hookBody(wanted, { readOnly: hookIsReadOnly(existing) }),
355
360
  works: probe ? Boolean(invocation) && invocationAnswers(invocation) : null,
356
361
  };
357
362
  }
@@ -439,6 +444,8 @@ export function scheduleHookRepair({ cwd = process.cwd(), now = Date.now() } = {
439
444
  try {
440
445
  const child = spawn(process.execPath, [path.join(__dirname, "cli.js"), "hook", "repair"], {
441
446
  cwd,
447
+ // The child's probes may launch this CLI again; none may schedule repair.
448
+ env: { ...process.env, PREMAN_NO_HOOK_REPAIR: "1" },
442
449
  detached: true,
443
450
  stdio: "ignore",
444
451
  });
@@ -0,0 +1,135 @@
1
+ /** Register the installed executable without copying credentials into harness files. */
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import { detectAgents } from "./connect/agents.js";
7
+ import { renderCodexToml, upsertCodexToml, shellQuote } from "./connect/configs.js";
8
+ import { installAgentInstructions, managedInstructionFiles } from "./connect/instructions.js";
9
+ import { makeArgs } from "./shared.js";
10
+ import { createHash } from "node:crypto";
11
+ import { spawnSync } from "node:child_process";
12
+
13
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
14
+ const instructionBlock = (text) => text.match(/<!-- preman:qa-instructions:start -->[\s\S]*?<!-- preman:qa-instructions:end -->/)?.[0];
15
+ const codexBlock = (text) => text.match(/^\[mcp_servers\.preman\][\s\S]*?(?=^\[(?!mcp_servers\.preman\.)|(?![\s\S]))/m)?.[0]?.trim();
16
+ function ledgerPath(homedir) { return path.join(homedir, ".preman", "agent-integrations.json"); }
17
+ function readLedger(homedir) {
18
+ try { const file = ledgerPath(homedir); if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 1024 * 1024) throw new Error(); return JSON.parse(fs.readFileSync(file, "utf8")); }
19
+ catch { return { schema_version: "1.0", agents: [] }; }
20
+ }
21
+ function cursorApproval(action, homedir) {
22
+ const local = path.join(homedir, ".local", "bin", process.platform === "win32" ? "cursor-agent.cmd" : "cursor-agent");
23
+ const located = fs.existsSync(local) ? local : spawnSync(process.platform === "win32" ? "where" : "which", ["cursor-agent"], { encoding: "utf8" }).stdout?.trim().split("\n")[0];
24
+ if (!located) return "desktop_only";
25
+ const result = spawnSync(located, ["mcp", action, "preman"], { env: { ...process.env, HOME: homedir, USERPROFILE: homedir }, cwd: homedir, encoding: "utf8", timeout: 15000, windowsHide: true, shell: process.platform === "win32" });
26
+ return result.status === 0 ? action === "enable" ? "enabled" : "disabled" : "approval_required";
27
+ }
28
+
29
+ function atomic(file, text) {
30
+ fs.mkdirSync(path.dirname(file), { recursive: true });
31
+ const destination = fs.existsSync(file) ? fs.realpathSync(file) : file;
32
+ const temporary = `${destination}.${randomUUID()}.tmp`;
33
+ try { fs.writeFileSync(temporary, text, { mode: 0o600, flag: "wx" }); fs.renameSync(temporary, destination); }
34
+ finally { fs.rmSync(temporary, { force: true }); }
35
+ }
36
+
37
+ export function registerInstalledAgents({ launcherPath, backendUrl, frontendUrl = "", accountId, homedir = os.homedir() }) {
38
+ if (!path.isAbsolute(launcherPath) || !fs.existsSync(launcherPath)) throw new Error("An installed PreMan executable is required");
39
+ const env = { PREMAN_BACKEND: backendUrl, ...(frontendUrl ? { PREMAN_FRONTEND: frontendUrl } : {}), ...(accountId != null ? { PREMAN_ACCOUNT_ID: String(accountId) } : {}) };
40
+ const config = process.platform === "win32" ? { command: "cmd", args: ["/c", launcherPath, "start"], env } : { command: launcherPath, args: ["start"], env };
41
+ const detected = homedir === os.homedir() ? detectAgents() : {};
42
+ detected.codex ||= fs.existsSync(process.env.CODEX_HOME || path.join(homedir, ".codex"));
43
+ detected.claude_code ||= fs.existsSync(process.env.CLAUDE_CONFIG_DIR || path.join(homedir, ".claude"));
44
+ detected.cursor ||= fs.existsSync(path.join(homedir, ".cursor"));
45
+ const rows = [];
46
+ const managed = readLedger(homedir);
47
+ for (const name of ["codex", "claude_code", "cursor"]) {
48
+ if (!detected[name]) continue;
49
+ const file = name === "codex" ? path.join(process.env.CODEX_HOME || path.join(homedir, ".codex"), "config.toml")
50
+ : name === "cursor" ? path.join(homedir, ".cursor", "mcp.json")
51
+ : path.join(process.env.CLAUDE_CONFIG_DIR || homedir, ".claude.json");
52
+ try {
53
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
54
+ if (name === "codex") {
55
+ const block = existing.match(/^\[mcp_servers\.preman\][\s\S]*?(?=^\[(?!mcp_servers\.preman\.)|(?![\s\S]))/m)?.[0];
56
+ if (block && !/premanmcp|[\\/]preman(?:\.cmd)?["']|command\s*=\s*["']preman["']/.test(block)) { rows.push({ agent: name, state: "conflict", path: file }); continue; }
57
+ atomic(file, upsertCodexToml(existing, "preman", renderCodexToml("preman", config)));
58
+ } else {
59
+ const value = existing.trim() ? JSON.parse(existing) : {};
60
+ const old = value.mcpServers?.preman;
61
+ if (old && !JSON.stringify(old).includes("premanmcp") && old.command !== launcherPath && !/[/\\]preman(?:\.cmd)?$/.test(old.command || "")) { rows.push({ agent: name, state: "conflict", path: file }); continue; }
62
+ value.mcpServers = { ...value.mcpServers, preman: config };
63
+ atomic(file, `${JSON.stringify(value, null, 2)}\n`);
64
+ }
65
+ const instructionPaths = managedInstructionFiles(name, homedir);
66
+ const existed = new Set(instructionPaths.filter((item) => fs.existsSync(item)));
67
+ const instructions = installAgentInstructions(makeArgs(["--agent", name]), { quiet: true, invocation: shellQuote(launcherPath), homedir });
68
+ const previous = managed.agents.find((item) => item.agent === name);
69
+ const record = { agent: name, path: file, config, ...(name === "codex" ? { block: codexBlock(fs.readFileSync(file, "utf8")) } : {}),
70
+ instructions: instructionPaths.filter((item) => fs.existsSync(item)).map((item) => { const text = fs.readFileSync(item, "utf8"); return { path: item,
71
+ block_sha256: digest(instructionBlock(text) || ""), file_sha256: digest(text), created: previous?.instructions?.find((entry) => entry.path === item)?.created ?? !existed.has(item) }; }) };
72
+ managed.agents = [...managed.agents.filter((item) => item.agent !== name), record];
73
+ rows.push({ agent: name, state: "configured", path: file, instructions: instructions.state, restart_required: true,
74
+ ...(name === "cursor" ? { cli_approval: cursorApproval("enable", homedir) } : {}) });
75
+ } catch { rows.push({ agent: name, state: "configuration_failed", path: file }); }
76
+ }
77
+ managed.launcher_path = launcherPath; managed.backend_url = backendUrl;
78
+ const ledger = ledgerPath(homedir);
79
+ if (fs.existsSync(ledger) && fs.lstatSync(ledger).isSymbolicLink()) throw new Error("Integration ownership file must not be a symlink");
80
+ atomic(ledger, `${JSON.stringify(managed, null, 2)}\n`);
81
+ return { agents: rows, generic_mcp: config };
82
+ }
83
+
84
+ export function installedAgentStatus({ homedir = os.homedir() } = {}) {
85
+ const ledger = readLedger(homedir);
86
+ return { schema_version: "1.0", launcher_path: ledger.launcher_path || null, agents: ledger.agents.map((entry) => {
87
+ let state = "missing";
88
+ try { const text = fs.readFileSync(entry.path, "utf8");
89
+ state = entry.agent === "codex" ? codexBlock(text) === entry.block ? "configured" : "modified"
90
+ : JSON.stringify(JSON.parse(text).mcpServers?.preman) === JSON.stringify(entry.config) ? "configured" : "modified";
91
+ } catch {}
92
+ return { agent: entry.agent, state, path: entry.path, restart_required: state === "configured" };
93
+ }) };
94
+ }
95
+
96
+ export function removeInstalledAgents({ homedir = os.homedir(), removeLauncher = false } = {}) {
97
+ const ledger = readLedger(homedir); const rows = []; const remaining = [];
98
+ for (const entry of ledger.agents) {
99
+ let conflict = false;
100
+ try {
101
+ if (fs.existsSync(entry.path)) {
102
+ const text = fs.readFileSync(entry.path, "utf8");
103
+ if (entry.agent === "codex") {
104
+ if (codexBlock(text) && codexBlock(text) !== entry.block) conflict = true;
105
+ else if (codexBlock(text)) atomic(entry.path, upsertCodexToml(text, "preman", ""));
106
+ } else {
107
+ const value = JSON.parse(text);
108
+ if (value.mcpServers?.preman && JSON.stringify(value.mcpServers.preman) !== JSON.stringify(entry.config)) conflict = true;
109
+ else if (value.mcpServers?.preman) { if (entry.agent === "cursor") cursorApproval("disable", homedir); delete value.mcpServers.preman; atomic(entry.path, `${JSON.stringify(value, null, 2)}\n`); }
110
+ }
111
+ }
112
+ if (!conflict) for (const instruction of entry.instructions || []) {
113
+ if (!fs.existsSync(instruction.path)) continue;
114
+ const text = fs.readFileSync(instruction.path, "utf8"); const block = instructionBlock(text);
115
+ if (!block) continue;
116
+ if (digest(block) !== instruction.block_sha256) { conflict = true; continue; }
117
+ if (instruction.created && digest(text) === instruction.file_sha256 && !fs.lstatSync(instruction.path).isSymbolicLink()) fs.unlinkSync(instruction.path);
118
+ else atomic(instruction.path, text.replace(block, "").replace(/\n{3,}/g, "\n\n"));
119
+ }
120
+ } catch { conflict = true; }
121
+ if (conflict) remaining.push(entry);
122
+ rows.push({ agent: entry.agent, state: conflict ? "modified_preserved" : "removed", path: entry.path });
123
+ }
124
+ let launcher = "retained";
125
+ if (removeLauncher && !remaining.length && ledger.launcher_path) {
126
+ try { const info = fs.lstatSync(ledger.launcher_path); const text = fs.readFileSync(ledger.launcher_path, "utf8");
127
+ if (!info.isSymbolicLink() && text.includes("preman-cli-launcher-v1")) { fs.unlinkSync(ledger.launcher_path); launcher = "removed"; }
128
+ else launcher = "modified_preserved";
129
+ } catch (error) { launcher = error.code === "ENOENT" ? "missing" : "modified_preserved"; }
130
+ }
131
+ const file = ledgerPath(homedir);
132
+ if (remaining.length || (ledger.launcher_path && launcher === "retained")) atomic(file, `${JSON.stringify({ ...ledger, agents: remaining }, null, 2)}\n`);
133
+ else fs.rmSync(file, { force: true });
134
+ return { schema_version: "1.0", agents: rows, launcher, credential_action: "Use preman logout or desktop sign-out to revoke the account connection before removing the app" };
135
+ }
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { describeCheckout, explainNoCheckout, resolveCheckout } from "./repo.js";
18
18
  import { desktopAppInstalled, writeDesktopSession } from "./desktop.js";
19
+ import { installAgentInstructions, validateInstructionAgent } from "./connect/instructions.js";
19
20
  import {
20
21
  DEFAULT_BACKEND,
21
22
  askWhileWaiting,
@@ -680,6 +681,7 @@ export async function onboardCommand(
680
681
  ) {
681
682
  const args = makeArgs(commandArgs);
682
683
  const assumeYes = args.has("--yes");
684
+ validateInstructionAgent(args);
683
685
 
684
686
  // Imported at call time, not at the top: guide.js imports this module for MARK
685
687
  // and the three integration commands, so a static edge back would close the
@@ -749,6 +751,10 @@ export async function onboardCommand(
749
751
  };
750
752
 
751
753
  const steps = [
754
+ {
755
+ name: "Coding-agent QA instructions",
756
+ run: () => installAgentInstructions(args),
757
+ },
752
758
  {
753
759
  // No question. Everything below is a decision about code PreMan has not
754
760
  // read yet, and asking permission to look was how people ended up with an
@@ -1055,12 +1061,16 @@ export const INTEGRATIONS_HELP = `
1055
1061
  Setup options:
1056
1062
  preman onboard Sign in, map this repo's endpoints, connect it for
1057
1063
  pull requests, and check the endpoints you touch on
1058
- every git push. Installs the desktop app at the end
1064
+ every git push. Adds personal QA instructions for
1065
+ detected coding agents and installs the desktop app
1059
1066
  preman aws Connect an AWS account and stream a log group
1060
1067
  preman github Install the PreMan GitHub App
1061
1068
  preman slack Add PreMan to a Slack workspace
1062
1069
 
1063
1070
  --yes Take each step's default without prompting (onboard)
1071
+ --agent <name> Install QA instructions only for cursor, claude-code,
1072
+ or codex; also selects the agent for discovery
1073
+ --no-agent-instructions Skip personal QA instructions (onboard)
1064
1074
  --desktop Install the desktop app even where there is no macOS
1065
1075
  build, to print the download link (onboard)
1066
1076
  --no-desktop Skip the desktop app, which otherwise installs