passcontrol 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +92 -0
- package/README.md +281 -0
- package/bin/passcontrol.mjs +1209 -0
- package/cli/config.mjs +237 -0
- package/cli/sidecar.mjs +111 -0
- package/package.json +88 -0
|
@@ -0,0 +1,1209 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { createInterface } from "node:readline/promises";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { ed25519 } from "@noble/curves/ed25519";
|
|
10
|
+
import {
|
|
11
|
+
CONFIG_FILE,
|
|
12
|
+
OPENAI_SHAPE_PROVIDERS,
|
|
13
|
+
PROVIDERS,
|
|
14
|
+
config,
|
|
15
|
+
configPathLabel,
|
|
16
|
+
defaultModelForProvider,
|
|
17
|
+
fail,
|
|
18
|
+
formatChallengeError,
|
|
19
|
+
formatProxyError,
|
|
20
|
+
globalConfigPath,
|
|
21
|
+
ok,
|
|
22
|
+
redact,
|
|
23
|
+
requireControlApiKey,
|
|
24
|
+
requirePassport,
|
|
25
|
+
step,
|
|
26
|
+
writeConfigFile,
|
|
27
|
+
} from "../cli/config.mjs";
|
|
28
|
+
import { startSidecar } from "../cli/sidecar.mjs";
|
|
29
|
+
|
|
30
|
+
const b64url = (bytes) =>
|
|
31
|
+
Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
32
|
+
const fromB64url = (s) => new Uint8Array(Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
|
|
33
|
+
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
34
|
+
const DASHBOARD_STATE_FILE = "local-dashboard.json";
|
|
35
|
+
const APP_STATE_FILE = "app.json";
|
|
36
|
+
const PUBLIC_REPO_URL = "https://github.com/Vertias3u/PassControl.git";
|
|
37
|
+
const LOCAL_DASHBOARD_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
38
|
+
const LOCAL_STACK_PORTS = [54321, 54322, 54324, 54327, 8079];
|
|
39
|
+
// The local stack (Supabase + Redis + dashboard) lives in a PassControl repo
|
|
40
|
+
// checkout — NOT in the installed CLI package (which ships only bin/ + cli/).
|
|
41
|
+
// `appRoot` is that checkout: the surrounding repo when run via `npm run cli --`,
|
|
42
|
+
// or a cloned/configured checkout when the CLI is installed globally. Resolved
|
|
43
|
+
// lazily by ensureAppRoot() before any stack command runs.
|
|
44
|
+
let appRoot = null;
|
|
45
|
+
|
|
46
|
+
function parseArgv(argv) {
|
|
47
|
+
const opts = {};
|
|
48
|
+
const rest = [];
|
|
49
|
+
const optKey = (key) => key.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
|
|
50
|
+
for (let i = 0; i < argv.length; i++) {
|
|
51
|
+
const arg = argv[i];
|
|
52
|
+
if (!arg.startsWith("--") || arg === "--") {
|
|
53
|
+
rest.push(arg);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const eq = arg.indexOf("=");
|
|
58
|
+
if (eq !== -1) {
|
|
59
|
+
opts[optKey(arg.slice(2, eq))] = arg.slice(eq + 1);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const key = optKey(arg.slice(2));
|
|
64
|
+
const next = argv[i + 1];
|
|
65
|
+
if (next && !next.startsWith("--")) {
|
|
66
|
+
opts[key] = next;
|
|
67
|
+
i++;
|
|
68
|
+
} else {
|
|
69
|
+
opts[key] = true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { opts, rest };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function cliPrefix() {
|
|
76
|
+
return process.env.npm_lifecycle_event === "cli" ? "npm run cli --" : "passcontrol";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function cliCommand(args = "") {
|
|
80
|
+
return args ? `${cliPrefix()} ${args}` : cliPrefix();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function usage() {
|
|
84
|
+
const cmd = cliPrefix();
|
|
85
|
+
return `PassControl
|
|
86
|
+
|
|
87
|
+
Usage:
|
|
88
|
+
${cmd} show cockpit status
|
|
89
|
+
${cmd} init [--global] create a config profile
|
|
90
|
+
${cmd} status [--no-network] show active config
|
|
91
|
+
${cmd} start start the configured local dashboard
|
|
92
|
+
${cmd} stop stop the CLI-managed local dashboard
|
|
93
|
+
${cmd} restart restart the CLI-managed local dashboard
|
|
94
|
+
${cmd} local-logs [--follow] show local dashboard logs
|
|
95
|
+
${cmd} doctor [--deep] [--fix] check local setup and repair a stopped dashboard
|
|
96
|
+
${cmd} reset --local --confirm RESET
|
|
97
|
+
destroy and recreate the local stack
|
|
98
|
+
${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
|
|
99
|
+
clone the app (if needed), start local services, open the dashboard
|
|
100
|
+
${cmd} call "hi" mint a visa and call a model
|
|
101
|
+
${cmd} sidecar [--port 8788] start the local agent bridge
|
|
102
|
+
${cmd} env [openhands] print sidecar settings for agents
|
|
103
|
+
${cmd} configure <integration> [--write]
|
|
104
|
+
preview or create a supported integration config
|
|
105
|
+
${cmd} agent list list agents
|
|
106
|
+
${cmd} agent create <name> create an agent passport
|
|
107
|
+
${cmd} agent suspend <id> suspend an agent
|
|
108
|
+
${cmd} agent resume <id> resume an agent
|
|
109
|
+
${cmd} agent revoke <id> revoke an agent
|
|
110
|
+
${cmd} spend show fleet + per-agent spend
|
|
111
|
+
${cmd} audit [--limit 20] show admin audit trail
|
|
112
|
+
${cmd} logs [--limit 20] show gateway call logs
|
|
113
|
+
${cmd} kill on|off toggle tenant kill switch
|
|
114
|
+
${cmd} open start (if needed) and open the dashboard
|
|
115
|
+
|
|
116
|
+
Config:
|
|
117
|
+
Env vars win, then nearest .passcontrol, then ~/.config/passcontrol/config.
|
|
118
|
+
Installed globally, the local-stack commands (setup/start/reset) use a cloned
|
|
119
|
+
app checkout; override its location with PASSCONTROL_APP_ROOT.
|
|
120
|
+
`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function assertProvider(provider) {
|
|
124
|
+
if (!PROVIDERS.includes(provider)) {
|
|
125
|
+
throw new Error(`Unknown provider "${provider}". Use one of: ${PROVIDERS.join(", ")}.`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function activeModel(provider, opts = {}) {
|
|
130
|
+
if (opts.model) return opts.model;
|
|
131
|
+
if (process.env.MODEL) return process.env.MODEL;
|
|
132
|
+
if (provider === config.provider) return config.model;
|
|
133
|
+
return defaultModelForProvider(provider);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function fetchWithTimeout(url, init = {}, timeoutMs = 1200) {
|
|
137
|
+
const controller = new AbortController();
|
|
138
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
139
|
+
try {
|
|
140
|
+
return await fetch(url, { ...init, signal: controller.signal });
|
|
141
|
+
} finally {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function gatewayStatus(noNetwork = false) {
|
|
147
|
+
if (noNetwork) return { label: "not checked", ok: null };
|
|
148
|
+
try {
|
|
149
|
+
const res = await fetchWithTimeout(config.gateway, { method: "GET" });
|
|
150
|
+
return { label: res.ok ? `online (${res.status})` : `unhealthy (${res.status})`, ok: res.ok };
|
|
151
|
+
} catch {
|
|
152
|
+
return { label: "offline or unreachable", ok: false };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function printCockpit({ noNetwork = false } = {}) {
|
|
157
|
+
const gateway = await gatewayStatus(noNetwork);
|
|
158
|
+
const passportConfigured = Boolean(config.passportId && config.passportSecret);
|
|
159
|
+
const adminConfigured = Boolean(config.apiKey);
|
|
160
|
+
|
|
161
|
+
console.log("PassControl\n");
|
|
162
|
+
console.log(`Gateway: ${gateway.label} ${config.gateway}`);
|
|
163
|
+
console.log(`Dashboard: ${dashboardStatusLabel(gateway, noNetwork)}`);
|
|
164
|
+
console.log(`App: ${appRootLabel()}`);
|
|
165
|
+
console.log(`Config: ${configPathLabel(config.sources)}`);
|
|
166
|
+
console.log(`Provider: ${config.provider}`);
|
|
167
|
+
console.log(`Model: ${config.model}`);
|
|
168
|
+
console.log(`Passport: ${passportConfigured ? redact(config.passportId) : "missing"}`);
|
|
169
|
+
console.log(`Admin key: ${adminConfigured ? redact(config.apiKey, 6) : "missing"}`);
|
|
170
|
+
console.log(`Sidecar: foreground command (\`${cliCommand("sidecar")}\`)\n`);
|
|
171
|
+
console.log("Next commands:");
|
|
172
|
+
console.log(` ${cliCommand("start")} start the local dashboard`);
|
|
173
|
+
console.log(` ${cliCommand("stop")} stop the local dashboard`);
|
|
174
|
+
console.log(` ${cliCommand("restart")} restart the local dashboard`);
|
|
175
|
+
console.log(` ${cliCommand("local-logs --follow")} follow local dashboard logs`);
|
|
176
|
+
console.log(` ${cliCommand("init")} configure this project`);
|
|
177
|
+
console.log(` ${cliCommand('call "hi"')} test a governed model call`);
|
|
178
|
+
console.log(` ${cliCommand("sidecar")} start the local agent bridge`);
|
|
179
|
+
console.log(` ${cliCommand("agent list")} list agents`);
|
|
180
|
+
console.log(` ${cliCommand("spend")} show fleet spend`);
|
|
181
|
+
console.log(` ${cliCommand("env openhands")} print agent settings`);
|
|
182
|
+
console.log(` ${cliCommand("doctor")} check setup`);
|
|
183
|
+
console.log(` ${cliCommand("open")} open dashboard`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function appConfigDir(env = process.env) {
|
|
187
|
+
const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
188
|
+
return path.join(base, "passcontrol");
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function dashboardStatePath(env = process.env) {
|
|
192
|
+
return path.join(appConfigDir(env), DASHBOARD_STATE_FILE);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function dashboardLogPath(env = process.env) {
|
|
196
|
+
return path.join(appConfigDir(env), "local-dashboard.log");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function appRootStatePath(env = process.env) {
|
|
200
|
+
return path.join(appConfigDir(env), APP_STATE_FILE);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// A directory is a usable stack checkout if it has the bootstrap script, the
|
|
204
|
+
// Redis compose file, and a package.json (with the dev:stack/dev:docker scripts).
|
|
205
|
+
function isRepoCheckout(dir) {
|
|
206
|
+
return Boolean(
|
|
207
|
+
dir &&
|
|
208
|
+
fs.existsSync(path.join(dir, "scripts", "dev-stack.sh")) &&
|
|
209
|
+
fs.existsSync(path.join(dir, "docker", "compose.yml")) &&
|
|
210
|
+
fs.existsSync(path.join(dir, "package.json"))
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function readSavedAppRoot() {
|
|
215
|
+
try {
|
|
216
|
+
const saved = JSON.parse(fs.readFileSync(appRootStatePath(), "utf8")).path;
|
|
217
|
+
return typeof saved === "string" ? saved : null;
|
|
218
|
+
} catch {
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function saveAppRoot(dir) {
|
|
224
|
+
const statePath = appRootStatePath();
|
|
225
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true, mode: 0o700 });
|
|
226
|
+
fs.writeFileSync(statePath, `${JSON.stringify({ path: dir, savedAt: new Date().toISOString() })}\n`, { mode: 0o600 });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Precedence: explicit env override → the surrounding checkout (npm run cli --) →
|
|
230
|
+
// a previously cloned/saved checkout. Returns null when the CLI is installed
|
|
231
|
+
// globally and no stack has been set up yet.
|
|
232
|
+
function resolveAppRoot() {
|
|
233
|
+
const envRoot = process.env.PASSCONTROL_APP_ROOT?.trim();
|
|
234
|
+
if (envRoot) {
|
|
235
|
+
const abs = path.resolve(envRoot);
|
|
236
|
+
if (!isRepoCheckout(abs)) {
|
|
237
|
+
throw new Error(`PASSCONTROL_APP_ROOT=${envRoot} is not a PassControl checkout (missing scripts/dev-stack.sh).`);
|
|
238
|
+
}
|
|
239
|
+
return abs;
|
|
240
|
+
}
|
|
241
|
+
if (process.env.PASSCONTROL_FORCE_INSTALLED !== "1" && isRepoCheckout(PACKAGE_ROOT)) return PACKAGE_ROOT;
|
|
242
|
+
const saved = readSavedAppRoot();
|
|
243
|
+
if (saved && isRepoCheckout(saved)) return path.resolve(saved);
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function defaultAppDir() {
|
|
248
|
+
return path.join(os.homedir(), "passcontrol");
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function appRootLabel() {
|
|
252
|
+
try {
|
|
253
|
+
return resolveAppRoot() ?? `not set up (run \`${cliCommand("setup")}\`)`;
|
|
254
|
+
} catch (error) {
|
|
255
|
+
return error.message;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function commandExists(command) {
|
|
260
|
+
try {
|
|
261
|
+
execFileSync(process.platform === "win32" ? "where" : "which", [command], { stdio: "ignore" });
|
|
262
|
+
return true;
|
|
263
|
+
} catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function promptLine(question, fallback) {
|
|
269
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
270
|
+
try {
|
|
271
|
+
const answer = (await rl.question(question)).trim();
|
|
272
|
+
return answer || fallback;
|
|
273
|
+
} finally {
|
|
274
|
+
rl.close();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function confirmYes(question) {
|
|
279
|
+
const answer = (await promptLine(question, "")).toLowerCase();
|
|
280
|
+
return answer === "" || answer === "y" || answer === "yes";
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Resolve the stack checkout, cloning the public repo on demand when the CLI is
|
|
284
|
+
// installed globally. `clone: false` never clones — it errors with a pointer to
|
|
285
|
+
// `passcontrol setup` (used by reset/doctor, where there's nothing yet to act on).
|
|
286
|
+
async function ensureAppRoot({ clone = false, appDir, yes = false } = {}) {
|
|
287
|
+
if (appRoot) return appRoot;
|
|
288
|
+
const resolved = resolveAppRoot();
|
|
289
|
+
if (resolved) {
|
|
290
|
+
appRoot = resolved;
|
|
291
|
+
return appRoot;
|
|
292
|
+
}
|
|
293
|
+
if (!clone) {
|
|
294
|
+
throw new Error(
|
|
295
|
+
`No PassControl app checkout found. Run \`${cliCommand("setup")}\` to clone and start it, or set PASSCONTROL_APP_ROOT to an existing checkout.`
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
300
|
+
if (!interactive && !yes) {
|
|
301
|
+
throw new Error(
|
|
302
|
+
`No PassControl app checkout found. Re-run \`${cliCommand("setup")}\` in an interactive terminal, or pass --yes (with optional --app-dir <path>) to clone ${PUBLIC_REPO_URL} non-interactively.`
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const target = path.resolve(appDir || (interactive ? await promptLine(`Where should the PassControl app be cloned? [${defaultAppDir()}] `, defaultAppDir()) : defaultAppDir()));
|
|
307
|
+
if (fs.existsSync(target) && fs.readdirSync(target).length) {
|
|
308
|
+
if (isRepoCheckout(target)) {
|
|
309
|
+
saveAppRoot(target);
|
|
310
|
+
appRoot = target;
|
|
311
|
+
ok(`Using existing PassControl checkout at ${target}`);
|
|
312
|
+
return appRoot;
|
|
313
|
+
}
|
|
314
|
+
throw new Error(`${target} already exists and is not empty. Choose an empty path with --app-dir.`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (!commandExists("git")) {
|
|
318
|
+
throw new Error("git is required to fetch the PassControl app. Install it from https://git-scm.com/downloads, then retry.");
|
|
319
|
+
}
|
|
320
|
+
if (interactive && !yes) {
|
|
321
|
+
const proceed = await confirmYes(`Clone ${PUBLIC_REPO_URL} into ${target} and install dependencies? [Y/n] `);
|
|
322
|
+
if (!proceed) throw new Error("Aborted — nothing was cloned.");
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
step(`Cloning ${PUBLIC_REPO_URL} → ${target}…`);
|
|
326
|
+
await runCommand("git", ["clone", "--depth", "1", PUBLIC_REPO_URL, target], { cwd: process.cwd() });
|
|
327
|
+
step("Installing dependencies (npm install)…");
|
|
328
|
+
await runCommand(process.platform === "win32" ? "npm.cmd" : "npm", ["install"], { cwd: target });
|
|
329
|
+
saveAppRoot(target);
|
|
330
|
+
appRoot = target;
|
|
331
|
+
ok(`PassControl app ready at ${target}`);
|
|
332
|
+
return appRoot;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function localComposeProjectName() {
|
|
336
|
+
const configPath = path.join(appRoot, "supabase", "config.toml");
|
|
337
|
+
const configText = fs.existsSync(configPath) ? fs.readFileSync(configPath, "utf8") : "";
|
|
338
|
+
const projectId = configText.match(/^project_id\s*=\s*"([^"]+)"\s*$/m)?.[1] ?? path.basename(appRoot);
|
|
339
|
+
return `passcontrol_${projectId.replace(/[^A-Za-z0-9]/g, "_").toLowerCase()}`;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function localDashboard() {
|
|
343
|
+
let url;
|
|
344
|
+
try {
|
|
345
|
+
url = new URL(config.gateway);
|
|
346
|
+
} catch {
|
|
347
|
+
throw new Error(`Invalid PASSCONTROL_GATEWAY URL: ${config.gateway}`);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (url.protocol !== "http:" || !LOCAL_DASHBOARD_HOSTS.has(url.hostname)) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
`passcontrol only manages local gateways (http://localhost or 127.0.0.1); configured gateway is ${config.gateway}.`
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const port = Number(url.port || 80);
|
|
357
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
358
|
+
throw new Error(`Invalid local dashboard port in PASSCONTROL_GATEWAY: ${config.gateway}`);
|
|
359
|
+
}
|
|
360
|
+
return { url: url.toString().replace(/\/$/, ""), port };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function readDashboardState() {
|
|
364
|
+
const statePath = dashboardStatePath();
|
|
365
|
+
try {
|
|
366
|
+
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
367
|
+
if (!Number.isInteger(state.pid) || state.pid < 1) throw new Error("bad pid");
|
|
368
|
+
return state;
|
|
369
|
+
} catch {
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function removeDashboardState() {
|
|
375
|
+
fs.rmSync(dashboardStatePath(), { force: true });
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function runningManagedDashboard() {
|
|
379
|
+
const state = readDashboardState();
|
|
380
|
+
if (!state) return null;
|
|
381
|
+
try {
|
|
382
|
+
process.kill(state.pid, 0);
|
|
383
|
+
return state;
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (error.code === "ESRCH") removeDashboardState();
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function dashboardStatusLabel(gateway, noNetwork) {
|
|
391
|
+
try {
|
|
392
|
+
localDashboard();
|
|
393
|
+
} catch {
|
|
394
|
+
return "remote gateway (not managed locally)";
|
|
395
|
+
}
|
|
396
|
+
if (noNetwork) return "local server not checked";
|
|
397
|
+
const managed = runningManagedDashboard();
|
|
398
|
+
if (managed) return gateway.ok ? `CLI-managed (PID ${managed.pid})` : `CLI-managed, unhealthy (PID ${managed.pid})`;
|
|
399
|
+
return gateway.ok ? "online (not managed by CLI)" : "stopped";
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
403
|
+
|
|
404
|
+
function portIsListening(port) {
|
|
405
|
+
return new Promise((resolve) => {
|
|
406
|
+
const socket = net.connect({ host: "127.0.0.1", port });
|
|
407
|
+
const done = (listening) => {
|
|
408
|
+
socket.removeAllListeners();
|
|
409
|
+
socket.destroy();
|
|
410
|
+
resolve(listening);
|
|
411
|
+
};
|
|
412
|
+
socket.once("connect", () => done(true));
|
|
413
|
+
socket.once("error", () => done(false));
|
|
414
|
+
socket.setTimeout(500, () => done(false));
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function waitForPortRelease(port, timeoutMs = 5000) {
|
|
419
|
+
const deadline = Date.now() + timeoutMs;
|
|
420
|
+
while (Date.now() < deadline) {
|
|
421
|
+
if (!await portIsListening(port)) return true;
|
|
422
|
+
await pause(100);
|
|
423
|
+
}
|
|
424
|
+
return !await portIsListening(port);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async function waitForGateway(timeoutMs = 30000) {
|
|
428
|
+
const deadline = Date.now() + timeoutMs;
|
|
429
|
+
while (Date.now() < deadline) {
|
|
430
|
+
const gateway = await gatewayStatus(false);
|
|
431
|
+
if (gateway.ok) return true;
|
|
432
|
+
await pause(250);
|
|
433
|
+
}
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function ownSupabaseDatabaseIsRunning(offset = 0) {
|
|
438
|
+
const project = `${path.basename(appRoot)}${offset ? `-${offset}` : ""}`;
|
|
439
|
+
try {
|
|
440
|
+
return Boolean(
|
|
441
|
+
execFileSync("docker", ["ps", "-q", "--filter", `name=^/supabase_db_${project}$`], { encoding: "utf8" }).trim()
|
|
442
|
+
);
|
|
443
|
+
} catch {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function assertLocalStackPortsAvailable(offset = 0) {
|
|
449
|
+
if (ownSupabaseDatabaseIsRunning(offset)) return;
|
|
450
|
+
const busy = [];
|
|
451
|
+
for (const port of LOCAL_STACK_PORTS.map((port) => port + offset)) {
|
|
452
|
+
if (await portIsListening(port)) busy.push(port);
|
|
453
|
+
}
|
|
454
|
+
if (busy.length) {
|
|
455
|
+
throw new Error(
|
|
456
|
+
`Local stack ports ${busy.join(", ")} are in use by another project. Stop that project first (for example, \`supabase stop --project-id <project>\`), then rerun \`passcontrol setup\`.`
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function startDashboard(opts = {}) {
|
|
462
|
+
await ensureAppRoot({ clone: true, appDir: opts.appDir, yes: opts.yes });
|
|
463
|
+
const dashboard = localDashboard();
|
|
464
|
+
if ((await gatewayStatus(false)).ok) {
|
|
465
|
+
ok(`dashboard already online at ${dashboard.url}`);
|
|
466
|
+
return dashboard;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const running = runningManagedDashboard();
|
|
470
|
+
if (running) {
|
|
471
|
+
step(`dashboard is still starting (PID ${running.pid}); waiting for ${dashboard.url}…`);
|
|
472
|
+
if (await waitForGateway()) {
|
|
473
|
+
ok(`dashboard online at ${dashboard.url}`);
|
|
474
|
+
return dashboard;
|
|
475
|
+
}
|
|
476
|
+
throw new Error(`CLI-managed dashboard (PID ${running.pid}) did not become ready. See ${running.logPath}.`);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const envFile = path.join(appRoot, ".env.docker");
|
|
480
|
+
if (!fs.existsSync(envFile)) {
|
|
481
|
+
throw new Error(`Local stack is not configured. Run \`${cliCommand("setup")}\` in ${appRoot} first.`);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const statePath = dashboardStatePath();
|
|
485
|
+
const logPath = dashboardLogPath();
|
|
486
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true, mode: 0o700 });
|
|
487
|
+
const logFd = fs.openSync(logPath, "a", 0o600);
|
|
488
|
+
const child = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ["run", "dev:docker"], {
|
|
489
|
+
cwd: appRoot,
|
|
490
|
+
detached: process.platform !== "win32",
|
|
491
|
+
env: { ...process.env, PORT: String(dashboard.port) },
|
|
492
|
+
stdio: ["ignore", logFd, logFd],
|
|
493
|
+
});
|
|
494
|
+
fs.closeSync(logFd);
|
|
495
|
+
child.unref();
|
|
496
|
+
fs.writeFileSync(
|
|
497
|
+
statePath,
|
|
498
|
+
`${JSON.stringify({ pid: child.pid, gateway: dashboard.url, port: dashboard.port, logPath, startedAt: new Date().toISOString() })}\n`,
|
|
499
|
+
{ mode: 0o600 }
|
|
500
|
+
);
|
|
501
|
+
|
|
502
|
+
step(`starting local dashboard at ${dashboard.url}…`);
|
|
503
|
+
if (!await waitForGateway()) {
|
|
504
|
+
throw new Error(`Dashboard did not become ready. See ${logPath}.`);
|
|
505
|
+
}
|
|
506
|
+
ok(`dashboard online at ${dashboard.url}`);
|
|
507
|
+
return dashboard;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function stopDashboard() {
|
|
511
|
+
const state = runningManagedDashboard();
|
|
512
|
+
if (!state) {
|
|
513
|
+
ok("No CLI-managed local dashboard is running.");
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
try {
|
|
518
|
+
if (process.platform === "win32") process.kill(state.pid, "SIGTERM");
|
|
519
|
+
else process.kill(-state.pid, "SIGTERM");
|
|
520
|
+
} catch (error) {
|
|
521
|
+
if (error.code === "ESRCH") {
|
|
522
|
+
removeDashboardState();
|
|
523
|
+
ok("No CLI-managed local dashboard is running.");
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
throw error;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (!await waitForPortRelease(state.port)) {
|
|
530
|
+
if (process.platform === "win32") process.kill(state.pid, "SIGKILL");
|
|
531
|
+
else process.kill(-state.pid, "SIGKILL");
|
|
532
|
+
if (!await waitForPortRelease(state.port)) {
|
|
533
|
+
throw new Error(`Dashboard process group ${state.pid} did not release port ${state.port}.`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
removeDashboardState();
|
|
537
|
+
ok(`stopped CLI-managed dashboard (PID ${state.pid})`);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
async function restartDashboard(opts = {}) {
|
|
541
|
+
localDashboard();
|
|
542
|
+
const managed = runningManagedDashboard();
|
|
543
|
+
if (!managed) {
|
|
544
|
+
if ((await gatewayStatus(false)).ok) {
|
|
545
|
+
throw new Error("Dashboard is online but was not started by passcontrol; stop it manually before restarting.");
|
|
546
|
+
}
|
|
547
|
+
return startDashboard(opts);
|
|
548
|
+
}
|
|
549
|
+
await stopDashboard();
|
|
550
|
+
return startDashboard(opts);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
async function localLogsCommand(opts = {}) {
|
|
554
|
+
const logPath = dashboardLogPath();
|
|
555
|
+
if (!fs.existsSync(logPath)) {
|
|
556
|
+
throw new Error(`No local dashboard log found at ${logPath}. Run \`passcontrol start\` first.`);
|
|
557
|
+
}
|
|
558
|
+
if (!opts.follow) {
|
|
559
|
+
process.stdout.write(fs.readFileSync(logPath, "utf8"));
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
if (process.platform === "win32") {
|
|
563
|
+
throw new Error(`Live log following is not available on Windows. Open ${logPath} directly.`);
|
|
564
|
+
}
|
|
565
|
+
await new Promise((resolve, reject) => {
|
|
566
|
+
const child = spawn("tail", ["-n", "100", "-f", logPath], { stdio: "inherit" });
|
|
567
|
+
child.once("error", reject);
|
|
568
|
+
child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`tail exited with code ${code}.`)));
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
async function runCommand(command, args, { cwd = appRoot, env = process.env } = {}) {
|
|
573
|
+
await new Promise((resolve, reject) => {
|
|
574
|
+
const child = spawn(command, args, { cwd, env, stdio: "inherit" });
|
|
575
|
+
child.once("error", reject);
|
|
576
|
+
child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`${command} exited with code ${code}.`)));
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async function runLocalCommand(command, args, env = process.env) {
|
|
581
|
+
await runCommand(command, args, { cwd: appRoot, env });
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
async function resetLocalStack(opts = {}) {
|
|
585
|
+
if (opts.local !== true) {
|
|
586
|
+
throw new Error("Usage: passcontrol reset --local --confirm RESET");
|
|
587
|
+
}
|
|
588
|
+
localDashboard();
|
|
589
|
+
if (opts.confirm !== "RESET") {
|
|
590
|
+
throw new Error("reset refuses to delete local data without `--confirm RESET`.");
|
|
591
|
+
}
|
|
592
|
+
await ensureAppRoot({ clone: false });
|
|
593
|
+
|
|
594
|
+
step("Resetting local PassControl data, Supabase, and Redis…");
|
|
595
|
+
await stopDashboard();
|
|
596
|
+
await runLocalCommand("supabase", ["stop", "--no-backup"]);
|
|
597
|
+
await runLocalCommand("docker", ["compose", "-f", "docker/compose.yml", "down", "-v"], {
|
|
598
|
+
...process.env,
|
|
599
|
+
COMPOSE_PROJECT_NAME: localComposeProjectName(),
|
|
600
|
+
});
|
|
601
|
+
fs.rmSync(path.join(appRoot, ".env.docker"), { force: true });
|
|
602
|
+
await runLocalCommand(process.platform === "win32" ? "npm.cmd" : "npm", ["run", "dev:stack"]);
|
|
603
|
+
ok("Local stack recreated. Run `passcontrol start` to launch the dashboard.");
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
async function setupLocal(opts = {}) {
|
|
607
|
+
const dashboard = localDashboard();
|
|
608
|
+
const offset = opts.portOffset === undefined ? 0 : Number(opts.portOffset);
|
|
609
|
+
if (!Number.isInteger(offset) || offset < 0 || offset > 10000) {
|
|
610
|
+
throw new Error("--port-offset must be an integer from 0 to 10000.");
|
|
611
|
+
}
|
|
612
|
+
await ensureAppRoot({ clone: true, appDir: opts.appDir, yes: opts.yes });
|
|
613
|
+
await assertLocalStackPortsAvailable(offset);
|
|
614
|
+
step("Preparing the local Supabase, Redis, migrations, and dev user…");
|
|
615
|
+
await runLocalCommand(process.platform === "win32" ? "npm.cmd" : "npm", ["run", "dev:stack"], {
|
|
616
|
+
...process.env,
|
|
617
|
+
PASSCONTROL_PORT_OFFSET: String(offset),
|
|
618
|
+
});
|
|
619
|
+
await startDashboard(opts);
|
|
620
|
+
if (!opts.noOpen) await openDashboard(opts);
|
|
621
|
+
console.log(`\nLocal dashboard: ${dashboard.url}`);
|
|
622
|
+
console.log("Local-only login: dev@passcontrol.local / passcontrol-dev");
|
|
623
|
+
step("Add a non-critical provider key, issue a passport, then run `passcontrol doctor --deep`.");
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function initCommand(opts) {
|
|
627
|
+
if (!process.stdin.isTTY) {
|
|
628
|
+
throw new Error("`passcontrol init` needs an interactive terminal. Or copy .passcontrol.example to .passcontrol and edit it.");
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const target = opts.global ? globalConfigPath() : path.join(process.cwd(), CONFIG_FILE);
|
|
632
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
633
|
+
try {
|
|
634
|
+
if (fs.existsSync(target)) {
|
|
635
|
+
const overwrite = await rl.question(`${target} already exists. Overwrite? [y/N]: `);
|
|
636
|
+
if (!/^y(es)?$/i.test(overwrite.trim())) {
|
|
637
|
+
ok("left existing config unchanged");
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
console.log("PassControl init");
|
|
643
|
+
if (opts.global) {
|
|
644
|
+
console.log("Saving a global profile. Only do this on a machine you trust.\n");
|
|
645
|
+
} else {
|
|
646
|
+
console.log("Saving a project-local .passcontrol file.\n");
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const ask = async (label, fallback = "") => {
|
|
650
|
+
const suffix = fallback ? ` [${fallback}]` : "";
|
|
651
|
+
const answer = await rl.question(`${label}${suffix}: `);
|
|
652
|
+
return answer.trim() || fallback;
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
const provider = await ask("Provider", config.provider || "anthropic");
|
|
656
|
+
assertProvider(provider);
|
|
657
|
+
const modelFallback = provider === config.provider ? config.model : defaultModelForProvider(provider);
|
|
658
|
+
const values = {
|
|
659
|
+
PASSCONTROL_GATEWAY: await ask("Gateway URL", config.gateway),
|
|
660
|
+
PASSPORT_ID: await ask("Passport ID", config.passportId),
|
|
661
|
+
PASSPORT_SECRET: await ask("Passport Secret (input is visible)", config.passportSecret),
|
|
662
|
+
PASSCONTROL_API_KEY: await ask("Control API key (optional, input is visible)", config.apiKey),
|
|
663
|
+
PROVIDER: provider,
|
|
664
|
+
MODEL: await ask("Model", modelFallback),
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
writeConfigFile(target, values);
|
|
668
|
+
ok(`saved ${target}`);
|
|
669
|
+
} finally {
|
|
670
|
+
rl.close();
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
async function mintVisa(current = config) {
|
|
675
|
+
const { passportId, passportSecret } = requirePassport(current);
|
|
676
|
+
const payloadObj = { passport_id: passportId, ts: Date.now(), nonce: crypto.randomUUID() };
|
|
677
|
+
const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObj)));
|
|
678
|
+
const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
|
|
679
|
+
const res = await fetch(`${current.gateway}/api/auth/challenge`, {
|
|
680
|
+
method: "POST",
|
|
681
|
+
headers: { "content-type": "application/json" },
|
|
682
|
+
body: JSON.stringify({ payload, signature }),
|
|
683
|
+
});
|
|
684
|
+
if (!res.ok) throw new Error(formatChallengeError(res.status, await res.text()));
|
|
685
|
+
const data = await res.json();
|
|
686
|
+
if (!data.visa) throw new Error("Challenge returned no visa.");
|
|
687
|
+
return data;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function requestFor(provider, model, prompt) {
|
|
691
|
+
if (provider === "anthropic") {
|
|
692
|
+
return {
|
|
693
|
+
path: "v1/messages",
|
|
694
|
+
body: { model, max_tokens: 128, stream: true, messages: [{ role: "user", content: prompt }] },
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
if (OPENAI_SHAPE_PROVIDERS.has(provider)) {
|
|
698
|
+
return {
|
|
699
|
+
path: "chat/completions",
|
|
700
|
+
body: { model, stream: true, messages: [{ role: "user", content: prompt }] },
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
throw new Error(`Provider ${provider} is not supported by the CLI call command yet.`);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function extractDelta(json) {
|
|
707
|
+
return json?.delta?.text ?? json?.choices?.[0]?.delta?.content ?? "";
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
async function streamResponse(res) {
|
|
711
|
+
if (!res.body) {
|
|
712
|
+
console.log(await res.text());
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
process.stdout.write("\nresponse: ");
|
|
717
|
+
const reader = res.body.getReader();
|
|
718
|
+
const dec = new TextDecoder();
|
|
719
|
+
let buf = "";
|
|
720
|
+
for (;;) {
|
|
721
|
+
const { value, done } = await reader.read();
|
|
722
|
+
if (done) break;
|
|
723
|
+
buf += dec.decode(value, { stream: true });
|
|
724
|
+
const lines = buf.split("\n");
|
|
725
|
+
buf = lines.pop() ?? "";
|
|
726
|
+
for (const line of lines) {
|
|
727
|
+
const m = line.match(/^data:\s*(.*)$/);
|
|
728
|
+
if (!m || m[1] === "[DONE]") continue;
|
|
729
|
+
try {
|
|
730
|
+
process.stdout.write(extractDelta(JSON.parse(m[1])));
|
|
731
|
+
} catch {
|
|
732
|
+
// Keep-alives and provider-specific comments can safely be ignored.
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
console.log("");
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
async function callCommand(rest, opts) {
|
|
740
|
+
const provider = String(opts.provider || config.provider);
|
|
741
|
+
assertProvider(provider);
|
|
742
|
+
const model = activeModel(provider, opts);
|
|
743
|
+
const prompt = rest.join(" ") || process.env.PROMPT || "Say hello in exactly 3 words.";
|
|
744
|
+
requirePassport(config);
|
|
745
|
+
step(`${provider}/${model} via ${config.gateway}`);
|
|
746
|
+
step(`prompt: ${prompt}\n`);
|
|
747
|
+
|
|
748
|
+
const { visa, expires_in } = await mintVisa(config);
|
|
749
|
+
ok(`minted visa (expires in ${expires_in ?? 300}s)`);
|
|
750
|
+
|
|
751
|
+
const { path: proxyPath, body } = requestFor(provider, model, prompt);
|
|
752
|
+
const res = await fetch(`${config.gateway}/api/v1/${provider}/${proxyPath}`, {
|
|
753
|
+
method: "POST",
|
|
754
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${visa}` },
|
|
755
|
+
body: JSON.stringify(body),
|
|
756
|
+
});
|
|
757
|
+
if (!res.ok) throw new Error(formatProxyError(res.status, await res.text()));
|
|
758
|
+
await streamResponse(res);
|
|
759
|
+
ok("done - check the dashboard audit log + spend for this call.");
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
async function api(method, pathPart, body) {
|
|
763
|
+
const apiKey = requireControlApiKey(config);
|
|
764
|
+
const res = await fetch(`${config.gateway}/api/control/v1${pathPart}`, {
|
|
765
|
+
method,
|
|
766
|
+
headers: {
|
|
767
|
+
authorization: `Bearer ${apiKey}`,
|
|
768
|
+
...(body ? { "content-type": "application/json" } : {}),
|
|
769
|
+
...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
|
|
770
|
+
},
|
|
771
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
772
|
+
});
|
|
773
|
+
const text = await res.text();
|
|
774
|
+
let json = {};
|
|
775
|
+
try {
|
|
776
|
+
json = text ? JSON.parse(text) : {};
|
|
777
|
+
} catch {
|
|
778
|
+
json = { error: { message: text || "non-JSON response" } };
|
|
779
|
+
}
|
|
780
|
+
if (!res.ok) {
|
|
781
|
+
const e = json.error ?? {};
|
|
782
|
+
throw new Error(`${res.status} ${e.code ?? ""} ${e.message ?? ""} (req ${e.request_id ?? "?"})`);
|
|
783
|
+
}
|
|
784
|
+
return json.data;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function controlPath(pathPart, params = {}) {
|
|
788
|
+
const qs = new URLSearchParams();
|
|
789
|
+
for (const [key, value] of Object.entries(params)) {
|
|
790
|
+
if (value !== undefined && value !== null && value !== "") qs.set(key, String(value));
|
|
791
|
+
}
|
|
792
|
+
const suffix = qs.toString();
|
|
793
|
+
return suffix ? `${pathPart}?${suffix}` : pathPart;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function usd(microcents) {
|
|
797
|
+
return `$${(Number(microcents ?? 0) / 100_000_000).toFixed(6)}`;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function safeLimit(raw, fallback = 20) {
|
|
801
|
+
const n = Number(raw ?? fallback);
|
|
802
|
+
if (!Number.isFinite(n)) return fallback;
|
|
803
|
+
return Math.max(1, Math.min(100, Math.floor(n)));
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
async function agentCommand(rest, opts) {
|
|
807
|
+
const [sub, ...args] = rest;
|
|
808
|
+
switch (sub) {
|
|
809
|
+
case "list": {
|
|
810
|
+
const agents = await api("GET", "/agents");
|
|
811
|
+
console.table(
|
|
812
|
+
agents.map((a) => ({
|
|
813
|
+
id: a.id,
|
|
814
|
+
name: a.name,
|
|
815
|
+
status: a.status,
|
|
816
|
+
tokens: a.spent_tokens,
|
|
817
|
+
usd: a.spent_microcents === undefined ? undefined : usd(a.spent_microcents),
|
|
818
|
+
}))
|
|
819
|
+
);
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
case "create": {
|
|
823
|
+
const name = args[0];
|
|
824
|
+
if (!name) throw new Error("Usage: passcontrol agent create <name>");
|
|
825
|
+
const provider = String(opts.provider || config.provider);
|
|
826
|
+
assertProvider(provider);
|
|
827
|
+
const scopeModel = String(opts.scope || (provider === "anthropic" ? "claude-*" : activeModel(provider, opts)));
|
|
828
|
+
const priv = ed25519.utils.randomPrivateKey();
|
|
829
|
+
const pub = ed25519.getPublicKey(priv);
|
|
830
|
+
const passportId = b64url(pub);
|
|
831
|
+
const created = await api("POST", "/agents", {
|
|
832
|
+
name,
|
|
833
|
+
passportPubkey: passportId,
|
|
834
|
+
scopes: [{ provider, models: [scopeModel] }],
|
|
835
|
+
});
|
|
836
|
+
ok(`created agent ${created.id} (${created.name})`);
|
|
837
|
+
step("Store these - the secret is shown once and is the agent's passport:");
|
|
838
|
+
console.log(` PASSPORT_ID=${passportId}`);
|
|
839
|
+
console.log(` PASSPORT_SECRET=${b64url(priv)}`);
|
|
840
|
+
step("Paste them into .passcontrol, then run `passcontrol call \"hi\"`.");
|
|
841
|
+
break;
|
|
842
|
+
}
|
|
843
|
+
case "suspend":
|
|
844
|
+
if (!args[0]) throw new Error("Usage: passcontrol agent suspend <id>");
|
|
845
|
+
console.log(await api("POST", `/agents/${encodeURIComponent(args[0])}/suspend`));
|
|
846
|
+
break;
|
|
847
|
+
case "resume":
|
|
848
|
+
if (!args[0]) throw new Error("Usage: passcontrol agent resume <id>");
|
|
849
|
+
console.log(await api("POST", `/agents/${encodeURIComponent(args[0])}/resume`));
|
|
850
|
+
break;
|
|
851
|
+
case "revoke":
|
|
852
|
+
if (!args[0]) throw new Error("Usage: passcontrol agent revoke <id>");
|
|
853
|
+
console.log(await api("DELETE", `/agents/${encodeURIComponent(args[0])}`));
|
|
854
|
+
break;
|
|
855
|
+
default:
|
|
856
|
+
throw new Error("Usage: passcontrol agent list|create <name>|suspend <id>|resume <id>|revoke <id>");
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
async function spendCommand() {
|
|
861
|
+
const data = await api("GET", "/spend");
|
|
862
|
+
console.log(`fleet: ${data.fleet.spent_tokens} tokens · ${usd(data.fleet.spent_microcents)}`);
|
|
863
|
+
console.table(
|
|
864
|
+
data.agents.map((agent) => ({
|
|
865
|
+
id: agent.id,
|
|
866
|
+
name: agent.name,
|
|
867
|
+
tokens: agent.spent_tokens,
|
|
868
|
+
usd: usd(agent.spent_microcents),
|
|
869
|
+
}))
|
|
870
|
+
);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
async function auditCommand(opts) {
|
|
874
|
+
const events = await api("GET", controlPath("/audit", { limit: safeLimit(opts.limit) }));
|
|
875
|
+
console.table(
|
|
876
|
+
events.map((event) => ({
|
|
877
|
+
at: event.created_at,
|
|
878
|
+
action: event.action,
|
|
879
|
+
target: event.target_id,
|
|
880
|
+
request: event.request_id,
|
|
881
|
+
}))
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
async function logsCommand(opts) {
|
|
886
|
+
const rows = await api(
|
|
887
|
+
"GET",
|
|
888
|
+
controlPath("/logs", {
|
|
889
|
+
limit: safeLimit(opts.limit),
|
|
890
|
+
agent_id: opts.agentId,
|
|
891
|
+
status: opts.status,
|
|
892
|
+
})
|
|
893
|
+
);
|
|
894
|
+
console.table(
|
|
895
|
+
rows.map((row) => ({
|
|
896
|
+
at: row.created_at,
|
|
897
|
+
agent: row.agent_id,
|
|
898
|
+
provider: row.provider,
|
|
899
|
+
model: row.model,
|
|
900
|
+
status: row.status,
|
|
901
|
+
in: row.input_tokens,
|
|
902
|
+
out: row.output_tokens,
|
|
903
|
+
total: row.total_tokens,
|
|
904
|
+
usd: usd(row.cost_microcents),
|
|
905
|
+
}))
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function killCommand(rest) {
|
|
910
|
+
const mode = rest[0];
|
|
911
|
+
if (mode !== "on" && mode !== "off") throw new Error("Usage: passcontrol kill on|off");
|
|
912
|
+
const data = await api("PUT", "/kill-switch", { armed: mode === "on" });
|
|
913
|
+
ok(`kill switch ${data.armed ? "armed" : "disarmed"} (${data.affected ?? 0} affected)`);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
async function sidecarCommand(rest, opts) {
|
|
917
|
+
if (rest[0] === "status") {
|
|
918
|
+
step("The sidecar runs as a foreground process.");
|
|
919
|
+
step("If it is running, your agent should point at http://127.0.0.1:8788/api/v1/anthropic or /api/v1/openai.");
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
const { passportId, passportSecret } = requirePassport(config);
|
|
924
|
+
startSidecar({
|
|
925
|
+
gateway: config.gateway,
|
|
926
|
+
passportId,
|
|
927
|
+
passportSecret,
|
|
928
|
+
port: Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788),
|
|
929
|
+
host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
|
|
930
|
+
refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
|
|
931
|
+
});
|
|
932
|
+
|
|
933
|
+
if (opts.for) {
|
|
934
|
+
console.log("");
|
|
935
|
+
printAgentPreset(String(opts.for), opts);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
function sidecarBaseUrl(opts = {}) {
|
|
940
|
+
const provider = String(opts.provider || config.provider);
|
|
941
|
+
assertProvider(provider);
|
|
942
|
+
const host = String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1");
|
|
943
|
+
const port = Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788);
|
|
944
|
+
return {
|
|
945
|
+
provider,
|
|
946
|
+
model: activeModel(provider, opts),
|
|
947
|
+
apiKey: "passcontrol",
|
|
948
|
+
baseUrl: `http://${host}:${port}/api/v1/${provider}`,
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function shellQuote(value) {
|
|
953
|
+
return `'${String(value).replace(/'/g, "'\\''")}'`;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function printExports(values) {
|
|
957
|
+
for (const [key, value] of values) {
|
|
958
|
+
console.log(`export ${key}=${shellQuote(value)}`);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
function printAgentPreset(name = "generic", opts = {}) {
|
|
963
|
+
const preset = name.toLowerCase();
|
|
964
|
+
const { provider, model, apiKey, baseUrl } = sidecarBaseUrl(opts);
|
|
965
|
+
const modelWithProvider = `${provider}/${model}`;
|
|
966
|
+
const sidecarStart = opts.port ? cliCommand(`sidecar --port ${opts.port}`) : cliCommand("sidecar");
|
|
967
|
+
|
|
968
|
+
console.log(`# Start the bridge first: ${sidecarStart}`);
|
|
969
|
+
switch (preset) {
|
|
970
|
+
case "openhands":
|
|
971
|
+
console.log("# OpenHands / LiteLLM-compatible starting point:");
|
|
972
|
+
printExports([
|
|
973
|
+
["LLM_BASE_URL", baseUrl],
|
|
974
|
+
["LLM_API_KEY", apiKey],
|
|
975
|
+
["LLM_MODEL", modelWithProvider],
|
|
976
|
+
]);
|
|
977
|
+
break;
|
|
978
|
+
case "litellm":
|
|
979
|
+
console.log("# LiteLLM-compatible starting point:");
|
|
980
|
+
printExports([
|
|
981
|
+
["LITELLM_BASE_URL", baseUrl],
|
|
982
|
+
["LITELLM_API_KEY", apiKey],
|
|
983
|
+
["LITELLM_MODEL", modelWithProvider],
|
|
984
|
+
]);
|
|
985
|
+
break;
|
|
986
|
+
case "aider":
|
|
987
|
+
console.log("# Aider OpenAI-compatible starting point:");
|
|
988
|
+
printExports([
|
|
989
|
+
["OPENAI_API_BASE", baseUrl],
|
|
990
|
+
["OPENAI_API_KEY", apiKey],
|
|
991
|
+
["AIDER_MODEL", modelWithProvider],
|
|
992
|
+
]);
|
|
993
|
+
break;
|
|
994
|
+
case "cline":
|
|
995
|
+
case "continue":
|
|
996
|
+
console.log(`# ${preset} UI settings:`);
|
|
997
|
+
console.log(`Base URL: ${baseUrl}`);
|
|
998
|
+
console.log(`API key: ${apiKey}`);
|
|
999
|
+
console.log(`Model: ${modelWithProvider}`);
|
|
1000
|
+
break;
|
|
1001
|
+
case "generic":
|
|
1002
|
+
console.log("# Generic sidecar settings:");
|
|
1003
|
+
printExports([
|
|
1004
|
+
["PASSCONTROL_SIDECAR_BASE_URL", baseUrl],
|
|
1005
|
+
["PASSCONTROL_SIDECAR_API_KEY", apiKey],
|
|
1006
|
+
["PASSCONTROL_MODEL", modelWithProvider],
|
|
1007
|
+
]);
|
|
1008
|
+
break;
|
|
1009
|
+
default:
|
|
1010
|
+
throw new Error("Usage: passcontrol env [generic|openhands|litellm|aider|cline|continue]");
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
function aiderConfig(opts = {}) {
|
|
1015
|
+
const { provider, model, baseUrl } = sidecarBaseUrl(opts);
|
|
1016
|
+
return [
|
|
1017
|
+
"# Generated by PassControl. This file contains no provider API key.",
|
|
1018
|
+
"# Start `passcontrol sidecar` before running Aider.",
|
|
1019
|
+
`model: ${provider}/${model}`,
|
|
1020
|
+
`openai-api-base: ${baseUrl}`,
|
|
1021
|
+
"openai-api-key: passcontrol",
|
|
1022
|
+
"",
|
|
1023
|
+
].join("\n");
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
async function configureCommand(rest, opts = {}) {
|
|
1027
|
+
const integration = String(rest[0] ?? "").toLowerCase();
|
|
1028
|
+
if (!integration) throw new Error("Usage: passcontrol configure <aider|cline|continue|openhands> [--write]");
|
|
1029
|
+
if (integration !== "aider") {
|
|
1030
|
+
if (opts.write) throw new Error(`${integration} configuration is UI- or project-schema-specific; no file was written. Use the preview below.`);
|
|
1031
|
+
printAgentPreset(integration, opts);
|
|
1032
|
+
step("This integration is configured manually from the settings shown above. Aider is the current file-writing integration.");
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
const target = path.join(process.cwd(), ".aider.conf.yml");
|
|
1037
|
+
const content = aiderConfig(opts);
|
|
1038
|
+
console.log(`Preview: .aider.conf.yml\n\n${content}`);
|
|
1039
|
+
if (!opts.write) {
|
|
1040
|
+
step("Dry run only. Re-run with `--write` to create this file.");
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
if (fs.existsSync(target)) throw new Error(`${target} already exists; refusing to overwrite it.`);
|
|
1044
|
+
fs.writeFileSync(target, content, { mode: 0o600 });
|
|
1045
|
+
ok(`wrote ${target}`);
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
async function doctorCommand(opts = {}) {
|
|
1049
|
+
const gateway = await gatewayStatus(false);
|
|
1050
|
+
console.log("PassControl doctor\n");
|
|
1051
|
+
(gateway.ok ? ok : fail)(`Gateway ${gateway.label}: ${config.gateway}`);
|
|
1052
|
+
(config.passportId && config.passportSecret ? ok : fail)(
|
|
1053
|
+
`Passport ${config.passportId && config.passportSecret ? "configured" : "missing"}`
|
|
1054
|
+
);
|
|
1055
|
+
(config.apiKey ? ok : step)(`Control API key ${config.apiKey ? "configured" : "missing (needed only for agent/kill commands)"}`);
|
|
1056
|
+
step(`Config source: ${configPathLabel(config.sources)}`);
|
|
1057
|
+
|
|
1058
|
+
if (opts.fix) {
|
|
1059
|
+
console.log("");
|
|
1060
|
+
let dashboard;
|
|
1061
|
+
try {
|
|
1062
|
+
dashboard = localDashboard();
|
|
1063
|
+
} catch {
|
|
1064
|
+
step("--fix manages only a local dashboard; remote gateways are not changed.");
|
|
1065
|
+
}
|
|
1066
|
+
if (dashboard) {
|
|
1067
|
+
const root = resolveAppRoot();
|
|
1068
|
+
if (gateway.ok) {
|
|
1069
|
+
ok("Local dashboard is already healthy; no repair needed.");
|
|
1070
|
+
} else if (!root) {
|
|
1071
|
+
fail(`No PassControl app checkout found. Run \`${cliCommand("setup")}\` to clone and start the local stack.`);
|
|
1072
|
+
} else if (!fs.existsSync(path.join(root, ".env.docker"))) {
|
|
1073
|
+
fail(`Local stack is not configured. Run \`${cliCommand("setup")}\` in ${root}.`);
|
|
1074
|
+
} else {
|
|
1075
|
+
appRoot = root;
|
|
1076
|
+
await startDashboard();
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
if (!opts.deep) return;
|
|
1082
|
+
|
|
1083
|
+
console.log("");
|
|
1084
|
+
step("Deep checks");
|
|
1085
|
+
if (config.passportId && config.passportSecret) {
|
|
1086
|
+
try {
|
|
1087
|
+
const visa = await mintVisa(config);
|
|
1088
|
+
ok(`Visa mint works (expires in ${visa.expires_in ?? 300}s)`);
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
fail(`Visa mint failed: ${error.message}`);
|
|
1091
|
+
}
|
|
1092
|
+
} else {
|
|
1093
|
+
step("Skipping visa mint check: no passport configured.");
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
if (config.apiKey) {
|
|
1097
|
+
try {
|
|
1098
|
+
const kill = await api("GET", "/kill-switch");
|
|
1099
|
+
ok(`Control API works (kill switch ${kill.armed ? "armed" : "off"})`);
|
|
1100
|
+
} catch (error) {
|
|
1101
|
+
fail(`Control API check failed: ${error.message}`);
|
|
1102
|
+
}
|
|
1103
|
+
} else {
|
|
1104
|
+
step("Skipping control API check: no PASSCONTROL_API_KEY configured.");
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
async function openDashboard(opts = {}) {
|
|
1109
|
+
let parsed;
|
|
1110
|
+
try {
|
|
1111
|
+
parsed = new URL(config.gateway);
|
|
1112
|
+
} catch {
|
|
1113
|
+
throw new Error(`Invalid PASSCONTROL_GATEWAY URL: ${config.gateway}`);
|
|
1114
|
+
}
|
|
1115
|
+
const url = parsed.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)
|
|
1116
|
+
? (await startDashboard(opts)).url
|
|
1117
|
+
: config.gateway;
|
|
1118
|
+
const platform = process.platform;
|
|
1119
|
+
const command =
|
|
1120
|
+
platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
|
|
1121
|
+
const args = platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
1122
|
+
const child = spawn(command, args, { detached: true, stdio: "ignore" });
|
|
1123
|
+
child.on("error", () => step(`Open this URL: ${url}`));
|
|
1124
|
+
child.unref();
|
|
1125
|
+
ok(`opening ${url}`);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
async function main() {
|
|
1129
|
+
const { opts, rest } = parseArgv(process.argv.slice(2));
|
|
1130
|
+
const [command, ...commandRest] = rest;
|
|
1131
|
+
|
|
1132
|
+
if (opts.help || command === "help") {
|
|
1133
|
+
console.log(usage());
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
if (opts.version || command === "version") {
|
|
1137
|
+
console.log("passcontrol 0.1.0");
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
switch (command) {
|
|
1142
|
+
case undefined:
|
|
1143
|
+
case "status":
|
|
1144
|
+
await printCockpit({ noNetwork: Boolean(opts.noNetwork) });
|
|
1145
|
+
break;
|
|
1146
|
+
case "init":
|
|
1147
|
+
await initCommand(opts);
|
|
1148
|
+
break;
|
|
1149
|
+
case "doctor":
|
|
1150
|
+
await doctorCommand(opts);
|
|
1151
|
+
break;
|
|
1152
|
+
case "start":
|
|
1153
|
+
await startDashboard(opts);
|
|
1154
|
+
break;
|
|
1155
|
+
case "stop":
|
|
1156
|
+
await stopDashboard();
|
|
1157
|
+
break;
|
|
1158
|
+
case "restart":
|
|
1159
|
+
await restartDashboard(opts);
|
|
1160
|
+
break;
|
|
1161
|
+
case "local-logs":
|
|
1162
|
+
await localLogsCommand(opts);
|
|
1163
|
+
break;
|
|
1164
|
+
case "reset":
|
|
1165
|
+
await resetLocalStack(opts);
|
|
1166
|
+
break;
|
|
1167
|
+
case "setup":
|
|
1168
|
+
await setupLocal(opts);
|
|
1169
|
+
break;
|
|
1170
|
+
case "call":
|
|
1171
|
+
await callCommand(commandRest, opts);
|
|
1172
|
+
break;
|
|
1173
|
+
case "sidecar":
|
|
1174
|
+
await sidecarCommand(commandRest, opts);
|
|
1175
|
+
break;
|
|
1176
|
+
case "env":
|
|
1177
|
+
printAgentPreset(commandRest[0] || "generic", opts);
|
|
1178
|
+
break;
|
|
1179
|
+
case "configure":
|
|
1180
|
+
await configureCommand(commandRest, opts);
|
|
1181
|
+
break;
|
|
1182
|
+
case "agent":
|
|
1183
|
+
case "fleet":
|
|
1184
|
+
await agentCommand(commandRest, opts);
|
|
1185
|
+
break;
|
|
1186
|
+
case "spend":
|
|
1187
|
+
await spendCommand();
|
|
1188
|
+
break;
|
|
1189
|
+
case "audit":
|
|
1190
|
+
await auditCommand(opts);
|
|
1191
|
+
break;
|
|
1192
|
+
case "logs":
|
|
1193
|
+
await logsCommand(opts);
|
|
1194
|
+
break;
|
|
1195
|
+
case "kill":
|
|
1196
|
+
await killCommand(commandRest);
|
|
1197
|
+
break;
|
|
1198
|
+
case "open":
|
|
1199
|
+
await openDashboard(opts);
|
|
1200
|
+
break;
|
|
1201
|
+
default:
|
|
1202
|
+
throw new Error(`Unknown command "${command}". Run \`passcontrol help\`.`);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
main().catch((error) => {
|
|
1207
|
+
fail(error.message);
|
|
1208
|
+
process.exit(1);
|
|
1209
|
+
});
|