passcontrol 0.6.1 → 0.6.2

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 CHANGED
@@ -207,7 +207,7 @@ const pc = new PassControl({ gateway, passportId, passportSecret });
207
207
  const openai = new OpenAI(pc.clientOptions("openai")); // baseURL + auth wired; visas auto-refresh
208
208
  ```
209
209
 
210
- The compiled ESM SDK ships at `passcontrol/sdk` in npm version 0.6.0. Keep the Passport secret
210
+ The compiled ESM SDK ships at `passcontrol/sdk` with the current CLI release. Keep the Passport secret
211
211
  in a trusted agent runtime; never place it in a browser-exposed environment variable. See the
212
212
  [Cloud Passport SDK guide](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/passport-sdk.md).
213
213
 
@@ -11,6 +11,7 @@ import {
11
11
  CONFIG_FILE,
12
12
  OPENAI_SHAPE_PROVIDERS,
13
13
  PROVIDERS,
14
+ WORKSPACE_IMPORT_MAX_VERSION,
14
15
  assertConfigLoaded,
15
16
  config,
16
17
  configPathLabel,
@@ -26,6 +27,7 @@ import {
26
27
  requireControlApiKey,
27
28
  requireControlGateway,
28
29
  operatorEnv,
30
+ probeGatewayOrigin,
29
31
  requirePassportGateway,
30
32
  requirePassport,
31
33
  step,
@@ -47,6 +49,8 @@ import {
47
49
  isIntegration,
48
50
  supportsWrite,
49
51
  } from "../cli/presets.mjs";
52
+ import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
53
+ import { checkForUpdate } from "../cli/update-check.mjs";
50
54
  import { startSidecar } from "../cli/sidecar.mjs";
51
55
  import {
52
56
  checkIssuerPublishesKey,
@@ -54,6 +58,7 @@ import {
54
58
  instanceKidFromSeed,
55
59
  } from "../cli/instance-key.mjs";
56
60
  import { FAILURE_REASONS, verifyAgentToken, verifyReceipt } from "../cli/verify.mjs";
61
+ import { compareProtocolSets } from "../cli/protocols.mjs";
57
62
 
58
63
  const b64url = (bytes) =>
59
64
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -144,6 +149,7 @@ ${heading("Quick start")}
144
149
  ${heading("Operate")}
145
150
  ${cmd} status [--no-network] [--json]
146
151
  show active config and instance state
152
+ ${cmd} version [--json] CLI, gateway and database schema versions
147
153
  ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
148
154
  ${cmd} call "hi" mint a visa and make a governed model call
149
155
  ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
@@ -163,6 +169,9 @@ ${heading("Manage")}
163
169
  ${cmd} logs [--limit 20] [--json]
164
170
  show governed call logs
165
171
  ${cmd} kill on|off toggle the tenant kill switch
172
+ ${cmd} export [--out FILE] save a workspace configuration snapshot
173
+ ${cmd} import <file> [--confirm IMPORT]
174
+ restore agents from a snapshot (never overwrites)
166
175
 
167
176
  ${heading("Integrate")}
168
177
  ${cmd} env [integration] print settings without writing anything
@@ -262,6 +271,10 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
262
271
  const dashboard = dashboardStatusLabel(gateway, noNetwork);
263
272
  const app = appRootLabel();
264
273
  const configFile = configPathLabel(config.sources);
274
+ // This is deliberately credential-gated. Status remains useful to an agent
275
+ // install with no Control key, but it must never probe a tenant endpoint
276
+ // anonymously or make that normal setup state look like a failure.
277
+ const systemHealth = noNetwork ? { state: "not-checked" } : await fetchSystemHealth();
265
278
 
266
279
  if (json) {
267
280
  console.log(JSON.stringify({
@@ -276,6 +289,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
276
289
  passport_configured: passportConfigured,
277
290
  control_api_key_configured: adminConfigured,
278
291
  },
292
+ system_health: systemHealthForJson(systemHealth),
279
293
  }, null, 2));
280
294
  return;
281
295
  }
@@ -289,6 +303,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
289
303
  console.log(formatLabel("Model", config.model));
290
304
  console.log(formatLabel("Passport", passportConfigured ? redact(config.passportId) : "missing"));
291
305
  console.log(formatLabel("Admin key", adminConfigured ? redact(config.apiKey, 6) : "missing"));
306
+ console.log(formatLabel("System health", systemHealthLabel(systemHealth)));
292
307
  console.log(`${formatLabel("Sidecar", `foreground command (\`${cliCommand("sidecar")}\`)`)}\n`);
293
308
  const next = [];
294
309
  if (config.sources.length === 0) {
@@ -312,6 +327,99 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
312
327
  }
313
328
  }
314
329
 
330
+ function safeHealthText(value, fallback = "unavailable") {
331
+ if (typeof value !== "string") return fallback;
332
+ // Keep a compromised/misconfigured server from writing terminal control
333
+ // sequences or an unbounded line into an operator's terminal.
334
+ const clean = value.replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 240);
335
+ return clean || fallback;
336
+ }
337
+
338
+ async function fetchSystemHealth() {
339
+ if (!config.apiKey) return { state: "skipped" };
340
+ try {
341
+ const health = await api("GET", "/system");
342
+ if (!health || typeof health !== "object") return { state: "unavailable", reason: "invalid response" };
343
+ return { state: "available", health };
344
+ } catch (error) {
345
+ const message = error instanceof Error ? error.message : "request failed";
346
+ return { state: message.startsWith("403 ") ? "restricted" : "unavailable", reason: message };
347
+ }
348
+ }
349
+
350
+ function healthCompatibility(health) {
351
+ return compareProtocolSets(health && typeof health === "object" ? health.protocols : undefined);
352
+ }
353
+
354
+ function shortBuildCommit(value) {
355
+ return typeof value === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value)
356
+ ? value.slice(0, 12).toLowerCase()
357
+ : "unknown";
358
+ }
359
+
360
+ function systemBuildSummary(health) {
361
+ const build = health?.build && typeof health.build === "object" ? health.build : {};
362
+ const migrations = health?.migrations && typeof health.migrations === "object" ? health.migrations : {};
363
+ return {
364
+ version: safeHealthText(build.version, "unknown"),
365
+ channel: safeHealthText(build.channel, "unknown"),
366
+ commit: shortBuildCommit(build.commit),
367
+ migrationState: safeHealthText(migrations.state, "unknown"),
368
+ migrationHead: safeHealthText(migrations.expected_head, "unknown"),
369
+ appliedMigrationHead: migrations.applied_head == null
370
+ ? "not recorded"
371
+ : safeHealthText(migrations.applied_head, "unknown"),
372
+ };
373
+ }
374
+
375
+ function systemHealthLabel(result) {
376
+ if (result.state === "skipped") return "skipped (operator read key required)";
377
+ if (result.state === "not-checked") return "not checked (--no-network)";
378
+ if (result.state === "restricted") return "restricted (control key cannot read system health)";
379
+ if (result.state !== "available") return `unavailable (${safeHealthText(result.reason)})`;
380
+ const build = systemBuildSummary(result.health);
381
+ const observed = safeHealthText(result.health.generated_at, "unknown");
382
+ return `${safeHealthText(result.health.overall, "reported")} · observed ${observed} · v${build.version} ${build.channel} ${build.commit} · migrations ${build.migrationState} (${build.appliedMigrationHead} → ${build.migrationHead}) · protocols ${healthCompatibility(result.health).state}`;
383
+ }
384
+
385
+ function systemHealthForJson(result) {
386
+ if (result.state !== "available") return { state: result.state };
387
+ return {
388
+ state: "available",
389
+ overall: safeHealthText(result.health.overall, "reported"),
390
+ observed_at: safeHealthText(result.health.generated_at, "unknown"),
391
+ protocol_compatibility: healthCompatibility(result.health).state,
392
+ build: systemBuildSummary(result.health),
393
+ };
394
+ }
395
+
396
+ function printSystemHealthDiagnostic(result) {
397
+ if (result.state === "skipped") {
398
+ step("System health skipped: an operator read key is required.");
399
+ return;
400
+ }
401
+ if (result.state === "restricted") {
402
+ fail("System health diagnostic restricted (403): this key's owner is not an allowlisted MFA-enrolled system operator.");
403
+ return;
404
+ }
405
+ if (result.state !== "available") {
406
+ fail(`System health diagnostic failed: ${safeHealthText(result.reason)}`);
407
+ return;
408
+ }
409
+ const compatibility = healthCompatibility(result.health);
410
+ const build = systemBuildSummary(result.health);
411
+ const observed = safeHealthText(result.health.generated_at, "unknown");
412
+ ok(`System health ${safeHealthText(result.health.overall, "reported")} · observed ${observed} · v${build.version} ${build.channel} ${build.commit} · migrations ${build.migrationState} (${build.appliedMigrationHead} → ${build.migrationHead}) · protocol compatibility ${compatibility.state}`);
413
+ for (const check of Array.isArray(result.health.checks) ? result.health.checks : []) {
414
+ if (!check || typeof check !== "object") continue;
415
+ const label = safeHealthText(check.label, "System check");
416
+ const state = safeHealthText(check.state, "unknown");
417
+ const summary = safeHealthText(check.summary, "No summary provided.");
418
+ console.log(` ${label}: ${state} — ${summary}`);
419
+ if (typeof check.action === "string" && check.action.trim()) step(`Remediation: ${safeHealthText(check.action)}`);
420
+ }
421
+ }
422
+
315
423
  function appConfigDir(env = process.env) {
316
424
  const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
317
425
  return path.join(base, "passcontrol");
@@ -1327,22 +1435,34 @@ async function tryCommand() {
1327
1435
  step("Next: add a real provider key in the Control Tower and re-point your agent at the gateway (see the README).");
1328
1436
  }
1329
1437
 
1330
- async function api(method, pathPart, body) {
1438
+ async function api(method, pathPart, body, { timeoutMs } = {}) {
1331
1439
  // Destination first, key second — same order and same reason as the SDK's
1332
1440
  // ControlClient. `config.gateway` is whatever PASSCONTROL_GATEWAY said, and
1333
1441
  // this is the one place a long-lived fleet-wide `pc_` key goes on the wire, so
1334
1442
  // the URL is built from the validated origin rather than from that string.
1335
1443
  const origin = requireControlGateway(config);
1336
1444
  const apiKey = requireControlApiKey(config);
1337
- const res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1338
- method,
1339
- headers: {
1340
- authorization: `Bearer ${apiKey}`,
1341
- ...(body ? { "content-type": "application/json" } : {}),
1342
- ...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
1343
- },
1344
- body: body ? JSON.stringify(body) : undefined,
1345
- });
1445
+ // Unbounded by default, deliberately: a fleet mutation must not be abandoned
1446
+ // halfway because a caller guessed a duration. `timeoutMs` is opt-in, for the
1447
+ // one kind of caller that is a REPORT — where a gateway that never answers is
1448
+ // itself the finding, and hanging turns a diagnostic into a hang.
1449
+ const controller = timeoutMs ? new AbortController() : null;
1450
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
1451
+ let res;
1452
+ try {
1453
+ res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1454
+ method,
1455
+ headers: {
1456
+ authorization: `Bearer ${apiKey}`,
1457
+ ...(body ? { "content-type": "application/json" } : {}),
1458
+ ...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
1459
+ },
1460
+ body: body ? JSON.stringify(body) : undefined,
1461
+ ...(controller ? { signal: controller.signal } : {}),
1462
+ });
1463
+ } finally {
1464
+ if (timer) clearTimeout(timer);
1465
+ }
1346
1466
  const text = await res.text();
1347
1467
  let json = {};
1348
1468
  try {
@@ -1354,7 +1474,7 @@ async function api(method, pathPart, body) {
1354
1474
  const e = json.error ?? {};
1355
1475
  throw new Error(`${res.status} ${e.code ?? ""} ${e.message ?? ""} (req ${e.request_id ?? "?"})`);
1356
1476
  }
1357
- return json.data;
1477
+ return Object.prototype.hasOwnProperty.call(json, "data") ? json.data : json;
1358
1478
  }
1359
1479
 
1360
1480
  function controlPath(pathPart, params = {}) {
@@ -1811,6 +1931,133 @@ async function configureCommand(rest, opts = {}) {
1811
1931
  ok(`wrote ${target}`);
1812
1932
  }
1813
1933
 
1934
+ // ── Which build is which ─────────────────────────────────────────────────────
1935
+ //
1936
+ // Version drift between the CLI, the gateway and the database is the support
1937
+ // question that hides behind every other support question, and until now the
1938
+ // CLI could only answer a third of it. `passcontrol version` printed its own
1939
+ // number and stopped.
1940
+ //
1941
+ // The three rows come from three different places on purpose, and each degrades
1942
+ // on its own:
1943
+ //
1944
+ // CLI — the installed package. Always available.
1945
+ // Server — GET /api/version on the configured gateway. Unauthenticated,
1946
+ // because the release version is already on the site footer.
1947
+ // Schema — the migration block of /api/control/v1/system, which is behind
1948
+ // the operator gate. How far behind a database is doubles as a
1949
+ // list of the fixes it does not have, so it stays authenticated;
1950
+ // on a self-host the operator is the person running this, and on
1951
+ // Cloud a tenant correctly cannot read the instance's lag.
1952
+
1953
+ /** The gateway's own build, or null. Never throws: this is a report, not a gate. */
1954
+ async function serverVersion() {
1955
+ // Same origin rule as every other outbound path in this file, even though no
1956
+ // credential travels here — see probeGatewayOrigin.
1957
+ const origin = probeGatewayOrigin();
1958
+ if (!origin) return { version: null, detail: "the configured gateway is not a bare origin" };
1959
+ try {
1960
+ const res = await fetchWithTimeout(`${origin}/api/version`);
1961
+ // A gateway that predates this endpoint is a real PassControl gateway, and
1962
+ // saying "unreachable" about one that answered would send an operator to
1963
+ // debug their network instead of deploying.
1964
+ if (res.status === 404) return { version: null, detail: "running a build older than /api/version" };
1965
+ if (!res.ok) return { version: null, detail: `the gateway answered ${res.status}` };
1966
+ const body = await res.json();
1967
+ const version = typeof body?.version === "string" ? body.version : null;
1968
+ return { version, detail: version ? null : "the gateway did not report a version" };
1969
+ } catch {
1970
+ return { version: null, detail: "unreachable" };
1971
+ }
1972
+ }
1973
+
1974
+ /**
1975
+ * The migration block, or why it could not be read.
1976
+ *
1977
+ * Every branch is a distinct, actionable answer. "not checked" is not the same
1978
+ * as "forbidden", and neither is the same as a gateway that is simply down —
1979
+ * collapsing them is how an operator ends up debugging the wrong thing.
1980
+ */
1981
+ async function schemaState() {
1982
+ if (!config.apiKey) return { state: "unchecked", detail: "no control API key configured" };
1983
+ try {
1984
+ // Bounded: `doctor` exists to explain an unavailable gateway, so this line
1985
+ // must never be the reason the report does not print.
1986
+ const snapshot = await api("GET", "/system", undefined, { timeoutMs: 2500 });
1987
+ const migrations = snapshot?.data?.migrations ?? snapshot?.migrations ?? null;
1988
+ if (!migrations) return { state: "unchecked", detail: "the gateway returned no migration block" };
1989
+ return { state: migrations.state ?? "unknown", migrations };
1990
+ } catch (error) {
1991
+ const message = String(error?.message ?? error);
1992
+ if (/system_forbidden|system_not_configured|system_totp_required|system_allowlist_invalid/.test(message)) {
1993
+ return { state: "unchecked", detail: "this control key is not an operator of that instance" };
1994
+ }
1995
+ // A bare "fetch failed" reads as a bug in the CLI rather than as a gateway
1996
+ // that is not running, which is what it almost always means.
1997
+ if (/fetch failed|ECONNREFUSED|ENOTFOUND|aborted/i.test(message)) {
1998
+ return { state: "unchecked", detail: "the gateway is unreachable" };
1999
+ }
2000
+ // Never echo the upstream error body into this report: it is remote text,
2001
+ // and "401 invalid_api_key no (req ?)" tells an operator less than the
2002
+ // sentence it is standing in for.
2003
+ if (/invalid_api_key|\b401\b/.test(message)) {
2004
+ return { state: "unchecked", detail: "the control API key was rejected" };
2005
+ }
2006
+ if (/\b404\b/.test(message)) {
2007
+ return { state: "unchecked", detail: "this gateway is too old to report its schema" };
2008
+ }
2009
+ return { state: "unchecked", detail: "the gateway did not answer the system check" };
2010
+ }
2011
+ }
2012
+
2013
+ const SCHEMA_WORD = {
2014
+ current: "compatible",
2015
+ behind: "the database is missing migrations this build expects",
2016
+ ahead: "the database is newer than this build — was the app rolled back?",
2017
+ incompatible: "the applied migrations do not match this build",
2018
+ unknown: "could not be determined",
2019
+ };
2020
+
2021
+ async function versionCommand({ json = false } = {}) {
2022
+ const [server, schema] = await Promise.all([serverVersion(), schemaState()]);
2023
+ const migrations = schema.migrations ?? null;
2024
+ const serverLabel =
2025
+ server.version === null
2026
+ ? `not reported (${server.detail})`
2027
+ : `${server.version}${server.version === CLI_VERSION ? " ✓" : " ✗ different build from this CLI"}`;
2028
+
2029
+ if (json) {
2030
+ console.log(JSON.stringify({
2031
+ cli: CLI_VERSION,
2032
+ server: server.version,
2033
+ server_detail: server.detail,
2034
+ server_matches_cli: server.version === null ? null : server.version === CLI_VERSION,
2035
+ schema: migrations
2036
+ ? {
2037
+ state: schema.state,
2038
+ applied_head: migrations.applied_head ?? null,
2039
+ expected_head: migrations.expected_head ?? null,
2040
+ missing_count: migrations.missing_count ?? 0,
2041
+ extra_count: migrations.extra_count ?? 0,
2042
+ }
2043
+ : { state: schema.state, detail: schema.detail ?? null },
2044
+ }, null, 2));
2045
+ return;
2046
+ }
2047
+
2048
+ console.log(`${heading("PassControl")}\n`);
2049
+ console.log(formatLabel("CLI", CLI_VERSION, 18));
2050
+ console.log(formatLabel("Server", serverLabel, 18));
2051
+ if (migrations) {
2052
+ console.log(formatLabel("Database schema", migrations.applied_head ?? "none recorded", 18));
2053
+ console.log(formatLabel("Expected schema", migrations.expected_head ?? "unknown", 18));
2054
+ console.log(formatLabel("Status", `${schema.state} — ${SCHEMA_WORD[schema.state] ?? "see the dashboard"}`, 18));
2055
+ if (migrations.action) step(migrations.action);
2056
+ } else {
2057
+ console.log(formatLabel("Database schema", `not checked (${schema.detail})`, 18));
2058
+ }
2059
+ }
2060
+
1814
2061
  async function doctorCommand(opts = {}) {
1815
2062
  const gateway = await gatewayStatus(false);
1816
2063
  console.log(`${heading("PassControl doctor")}\n`);
@@ -1820,6 +2067,16 @@ async function doctorCommand(opts = {}) {
1820
2067
  );
1821
2068
  (config.apiKey ? ok : step)(`Control API key ${config.apiKey ? "configured" : "missing (needed only for agent/kill commands)"}`);
1822
2069
  step(`Config source: ${configPathLabel(config.sources)}`);
2070
+ // The check that answers "why did this work yesterday". A database behind the
2071
+ // build it serves is not visible from any other line in this report.
2072
+ const schema = await schemaState();
2073
+ if (schema.migrations) {
2074
+ (schema.state === "current" ? ok : fail)(
2075
+ `Database migrations ${schema.state} — ${SCHEMA_WORD[schema.state] ?? "see the dashboard"}`
2076
+ );
2077
+ } else {
2078
+ step(`Database migrations not checked (${schema.detail})`);
2079
+ }
1823
2080
 
1824
2081
  if (opts.fix) {
1825
2082
  console.log("");
@@ -1848,6 +2105,9 @@ async function doctorCommand(opts = {}) {
1848
2105
 
1849
2106
  console.log("");
1850
2107
  step("Deep checks");
2108
+ // One authenticated request for this command. Its failure is a failed
2109
+ // diagnostic, not a CLI crash: remaining local checks are still useful.
2110
+ printSystemHealthDiagnostic(await fetchSystemHealth());
1851
2111
  await runLocalPrerequisiteChecks({ report: true });
1852
2112
  if (config.passportId && config.passportSecret) {
1853
2113
  try {
@@ -2000,17 +2260,154 @@ async function openDashboard(opts = {}) {
2000
2260
  ok(`opening ${url}`);
2001
2261
  }
2002
2262
 
2263
+ // ── Workspace snapshots ─────────────────────────────────────────────────────
2264
+ // A recovery snapshot is CONFIGURATION, not a backup: it carries agents, their
2265
+ // scopes, budgets, policies and failover order, and deliberately carries no
2266
+ // secret value at all. What it cannot restore is stated in the file itself,
2267
+ // under `exclusions`, because this is the artifact someone opens at the worst
2268
+ // possible moment.
2269
+
2270
+ // lib/control/body.ts caps every control-plane request at 64 KiB, and it is not
2271
+ // raised for one route. Checking here means a large fleet is told what to do
2272
+ // instead of being handed a bare 413 by the server.
2273
+ const IMPORT_BODY_LIMIT = 64 * 1024;
2274
+
2275
+ // Wide enough for "Skipped (already exist)", the longest label below. formatLabel
2276
+ // pads to the width and does not truncate, so a short width silently glues the
2277
+ // value onto the colon.
2278
+ const REPORT_LABEL_WIDTH = 26;
2279
+
2280
+ // A passport public key is unique across the whole instance, not per workspace,
2281
+ // because the gateway identifies an agent BY that key. So importing a file into
2282
+ // a second workspace on the SAME instance refuses every agent still held by the
2283
+ // first — which is correct, and is not what a restore looks like. A restore
2284
+ // goes into a fresh instance, where the passports are free.
2285
+ const IMPORT_REASONS = {
2286
+ passport_registered_elsewhere:
2287
+ "its passport is already registered on this instance. Nothing was created for it. " +
2288
+ "Passports are unique per instance, so this file restores into a FRESH deployment, " +
2289
+ "not alongside the workspace it came from.",
2290
+ policy_malformed: "its policy could not be parsed, and creating it without one would leave it unrestricted.",
2291
+ policy_shadow_malformed: "its shadow policy could not be parsed.",
2292
+ unknown_status: "it records a status this version does not recognise.",
2293
+ };
2294
+
2295
+ async function exportCommand(opts = {}) {
2296
+ const snapshot = await api("GET", "/workspace/export");
2297
+ const body = JSON.stringify(snapshot, null, 2);
2298
+ const target = typeof opts.out === "string" ? opts.out : null;
2299
+ if (!target) {
2300
+ console.log(body);
2301
+ return;
2302
+ }
2303
+ fs.writeFileSync(target, `${body}\n`, { mode: 0o600 });
2304
+ ok(`Wrote ${snapshot.workspace.agents.length} agents to ${target}`);
2305
+ console.log(`\n${heading("Not in this file")}`);
2306
+ for (const line of snapshot.exclusions) console.log(` • ${line}`);
2307
+ }
2308
+
2309
+ async function importCommand(rest = [], opts = {}) {
2310
+ const file = rest[0];
2311
+ if (!file) throw new Error(`Usage: ${cliPrefix()} import <file> [--confirm IMPORT]`);
2312
+
2313
+ let snapshot;
2314
+ try {
2315
+ snapshot = JSON.parse(fs.readFileSync(file, "utf8"));
2316
+ } catch (error) {
2317
+ throw new Error(`Could not read ${file} as JSON: ${error.message}`);
2318
+ }
2319
+ if (snapshot?.format !== "passcontrol-export") {
2320
+ throw new Error(`${file} is not a PassControl workspace export.`);
2321
+ }
2322
+ // A file from a LATER schema may describe fields this CLI would silently drop.
2323
+ // Refusing is the honest move: a partial restore that reports success is the
2324
+ // failure this whole feature exists to prevent.
2325
+ if (Number(snapshot.version) > WORKSPACE_IMPORT_MAX_VERSION) {
2326
+ throw new Error(
2327
+ `${file} uses export format v${snapshot.version}; this CLI understands up to ` +
2328
+ `v${WORKSPACE_IMPORT_MAX_VERSION}. Upgrade PassControl and try again.`
2329
+ );
2330
+ }
2331
+
2332
+ // Only what the import writes goes on the wire. Provider mappings, break-glass
2333
+ // grants, the exclusions prose and the display settings stay on disk — they
2334
+ // are not importable, so sending them would spend the size budget on bytes the
2335
+ // server ignores.
2336
+ const agents = snapshot.workspace?.agents ?? [];
2337
+ const payload = { agents, ownership: snapshot.workspace?.ownership ?? null };
2338
+ const size = Buffer.byteLength(JSON.stringify(payload));
2339
+ if (size > IMPORT_BODY_LIMIT) {
2340
+ throw new Error(
2341
+ `This snapshot holds ${agents.length} agents (${Math.ceil(size / 1024)} KiB) and the import ` +
2342
+ `API accepts ${IMPORT_BODY_LIMIT / 1024} KiB per request. Split the "agents" array across ` +
2343
+ `several files and import them one at a time — importing is additive, so the parts combine.`
2344
+ );
2345
+ }
2346
+
2347
+ const preview = await api("POST", "/workspace/import?dry_run=true", payload);
2348
+ printImportReport(preview, { preview: true });
2349
+
2350
+ if (preview.agents.create === 0) {
2351
+ ok(noAgentCreateMessage(preview.agents));
2352
+ return;
2353
+ }
2354
+ if (opts.confirm !== "IMPORT") {
2355
+ console.log(
2356
+ `\nNothing has been written. Re-run with \`--confirm IMPORT\` to create the ` +
2357
+ `${preview.agents.create} agent(s) above.`
2358
+ );
2359
+ return;
2360
+ }
2361
+
2362
+ const result = await api("POST", "/workspace/import", payload);
2363
+ printImportReport(result, { preview: false });
2364
+ ok(importCompletionMessage(result));
2365
+ }
2366
+
2367
+ function printImportReport(report, { preview }) {
2368
+ console.log(`\n${heading(preview ? "Dry run — nothing written yet" : "Imported")}`);
2369
+ const created = preview ? report.agents.create : report.agents.created.length;
2370
+ console.log(formatLabel(preview ? "Will create" : "Created", String(created), REPORT_LABEL_WIDTH));
2371
+ if (report.agents.skipped.length > 0) {
2372
+ console.log(formatLabel("Skipped (already exist)", report.agents.skipped.join(", "), REPORT_LABEL_WIDTH));
2373
+ }
2374
+ for (const entry of report.agents.rejected) {
2375
+ console.log(formatLabel("Refused", `${entry.name} — ${IMPORT_REASONS[entry.reason] ?? entry.reason}`, REPORT_LABEL_WIDTH));
2376
+ }
2377
+ console.log(formatLabel("Ownership", report.ownership, REPORT_LABEL_WIDTH));
2378
+ console.log(`\n${heading("Not restored")}`);
2379
+ for (const line of report.not_restored) console.log(` • ${line}`);
2380
+ // Said once, plainly: an existing agent is never touched, so a re-run is safe.
2381
+ console.log(`\nAn agent already in the workspace is left exactly as it is — import never overwrites.`);
2382
+ }
2383
+
2003
2384
  async function main() {
2004
2385
  const { opts, rest } = parseArgv(process.argv.slice(2));
2005
2386
  const [command, ...commandRest] = rest;
2006
2387
 
2388
+ // Started here and awaited at the very end, so the registry lookup overlaps
2389
+ // the command instead of being tacked onto the exit. On anything that touches
2390
+ // the network — which is most of this CLI — it costs nothing measurable, and
2391
+ // it can never turn a registry outage into a slow `passcontrol call`.
2392
+ // .catch() rather than try/catch: an unhandled rejection from a background
2393
+ // nicety must not take down a command that already did its job.
2394
+ const updateNotice = checkForUpdate({
2395
+ current: CLI_VERSION,
2396
+ json: Boolean(opts.json),
2397
+ }).catch(() => null);
2398
+ const announceUpdate = async () => {
2399
+ const notice = await updateNotice;
2400
+ if (notice) console.log(`\n${notice}`);
2401
+ };
2402
+
2007
2403
  if (opts.help || command === "help") {
2008
2404
  const target = command === "help" ? commandRest[0] : command;
2009
2405
  console.log(target === "agent" || target === "fleet" ? agentUsage() : usage());
2010
2406
  return;
2011
2407
  }
2012
2408
  if (opts.version || command === "version") {
2013
- console.log(`passcontrol ${CLI_VERSION}`);
2409
+ await versionCommand({ json: Boolean(opts.json) });
2410
+ await announceUpdate();
2014
2411
  return;
2015
2412
  }
2016
2413
 
@@ -2080,6 +2477,12 @@ async function main() {
2080
2477
  case "kill":
2081
2478
  await killCommand(commandRest);
2082
2479
  break;
2480
+ case "export":
2481
+ await exportCommand(opts);
2482
+ break;
2483
+ case "import":
2484
+ await importCommand(commandRest, opts);
2485
+ break;
2083
2486
  case "open":
2084
2487
  await openDashboard(opts);
2085
2488
  break;
@@ -2092,6 +2495,8 @@ async function main() {
2092
2495
  default:
2093
2496
  throw new Error(`Unknown command "${command}". Run \`passcontrol help\`.`);
2094
2497
  }
2498
+ // Only on success. A notice printed under a failure buries the error.
2499
+ await announceUpdate();
2095
2500
  }
2096
2501
 
2097
2502
  main().catch((error) => {
package/cli/config.mjs CHANGED
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { WORKSPACE_EXPORT_PROTOCOL } from "./protocols.mjs";
5
6
 
6
7
  export const CONFIG_FILE = ".passcontrol";
7
8
 
@@ -16,8 +17,13 @@ export const PACKAGE_VERSION = (() => {
16
17
  return "0.0.0";
17
18
  }
18
19
  })();
19
- export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together", "deepseek"];
20
- export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek"]);
20
+ // The CLI imports snapshots only through the shared protocol declaration. A
21
+ // standalone package still has no app dependency, but no longer carries a
22
+ // second numeric copy that can drift from system-health capability reporting.
23
+ export const WORKSPACE_IMPORT_MAX_VERSION = WORKSPACE_EXPORT_PROTOCOL.maximum;
24
+
25
+ export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together", "deepseek", "gemini"];
26
+ export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek", "gemini"]);
21
27
 
22
28
  const DEFAULT_GATEWAY = "http://localhost:3000";
23
29
  const DEFAULT_PROVIDER = "anthropic";
@@ -63,6 +69,8 @@ export function defaultModelForProvider(provider) {
63
69
  return "openai/gpt-oss-20b";
64
70
  case "deepseek":
65
71
  return "deepseek-chat";
72
+ case "gemini":
73
+ return "gemini-2.5-flash";
66
74
  case "anthropic":
67
75
  default:
68
76
  return "claude-haiku-4-5";
@@ -347,6 +355,27 @@ export function bareGatewayOrigin(gateway, label = "PASSCONTROL_GATEWAY") {
347
355
  * part of the credential's security, not configuration taste. Every `api()` call
348
356
  * resolves its destination through this, never through the raw config string.
349
357
  */
358
+ /**
359
+ * The same origin rule, for probes that carry NO credential.
360
+ *
361
+ * `passcontrol version` reads an unauthenticated /api/version, so the leak the
362
+ * rule normally prevents — a signature or a `pc_` key reaching a host the
363
+ * operator did not choose — does not apply. The destination still has to be
364
+ * validated: a project-local `.passcontrol` pointing elsewhere would make a
365
+ * DIAGNOSTIC command report a stranger's build as your gateway's, which is its
366
+ * own kind of wrong answer, and it would turn `version` into a beacon.
367
+ *
368
+ * Returns null rather than throwing. A malformed gateway is a row in a report
369
+ * here, not a reason to abort the command the operator actually ran.
370
+ */
371
+ export function probeGatewayOrigin(current = config) {
372
+ try {
373
+ return bareGatewayOrigin(current.gateway);
374
+ } catch {
375
+ return null;
376
+ }
377
+ }
378
+
350
379
  export function requireControlGateway(current = config) {
351
380
  assertConfigLoaded();
352
381
  return bareGatewayOrigin(current.gateway);
@@ -0,0 +1,16 @@
1
+ export interface ProtocolRange {
2
+ minimum: number;
3
+ maximum: number;
4
+ }
5
+
6
+ export const CONTROL_API_PROTOCOL: ProtocolRange;
7
+ export const GATEWAY_API_PROTOCOL: ProtocolRange;
8
+ export const RECEIPT_PROTOCOL: ProtocolRange;
9
+ export const AGENT_TOKEN_PROTOCOL: ProtocolRange;
10
+ export const WORKSPACE_EXPORT_PROTOCOL: ProtocolRange;
11
+ export const CLIENT_PROTOCOLS: Readonly<Record<string, ProtocolRange>>;
12
+ export function compareProtocolRanges(client: ProtocolRange, server: unknown): "compatible" | "partial" | "update-required" | "unavailable";
13
+ export function compareProtocolSets(serverProtocols: unknown): {
14
+ state: "compatible" | "partial" | "update-required" | "unavailable";
15
+ checks: Array<{ name: string; client: ProtocolRange; server: unknown; state: "compatible" | "partial" | "update-required" | "unavailable" }>;
16
+ };
@@ -0,0 +1,61 @@
1
+ // Compatibility vocabulary shared by the Control API and the standalone CLI.
2
+ // The CLI ships without the Next app, so this plain ESM module is the canonical
3
+ // runtime source; its declaration lets Edge TypeScript import the same values.
4
+ export const CONTROL_API_PROTOCOL = { minimum: 1, maximum: 1 };
5
+ export const GATEWAY_API_PROTOCOL = { minimum: 1, maximum: 1 };
6
+ export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 2 };
7
+ export const AGENT_TOKEN_PROTOCOL = { minimum: 1, maximum: 1 };
8
+ export const WORKSPACE_EXPORT_PROTOCOL = { minimum: 1, maximum: 1 };
9
+
10
+ export const CLIENT_PROTOCOLS = Object.freeze({
11
+ control_api: CONTROL_API_PROTOCOL,
12
+ gateway_api: GATEWAY_API_PROTOCOL,
13
+ receipt: RECEIPT_PROTOCOL,
14
+ agent_token: AGENT_TOKEN_PROTOCOL,
15
+ workspace_export: WORKSPACE_EXPORT_PROTOCOL,
16
+ });
17
+
18
+ const validRange = (value) =>
19
+ value &&
20
+ Number.isInteger(value.minimum) &&
21
+ Number.isInteger(value.maximum) &&
22
+ value.minimum >= 1 &&
23
+ value.minimum <= value.maximum;
24
+
25
+ /**
26
+ * Compare negotiated version ranges without pretending a missing or malformed
27
+ * server declaration is compatible. A non-identical overlap is useful but
28
+ * partial: an operator should know the pair is not speaking precisely the same
29
+ * contract before relying on a newer optional feature.
30
+ */
31
+ export function compareProtocolRanges(client, server) {
32
+ if (!validRange(server)) return "unavailable";
33
+ // A server declaring a higher maximum may emit semantics this CLI cannot
34
+ // interpret, even when the numeric ranges overlap. Do not dress that up as
35
+ // partial compatibility. Conversely, an older server inside our maximum can
36
+ // still serve the shared contract and is merely partial.
37
+ if (
38
+ server.maximum > client.maximum ||
39
+ server.maximum < client.minimum
40
+ ) return "update-required";
41
+ if (server.minimum !== client.minimum || server.maximum !== client.maximum) return "partial";
42
+ return "compatible";
43
+ }
44
+
45
+ export function compareProtocolSets(serverProtocols) {
46
+ const checks = Object.entries(CLIENT_PROTOCOLS).map(([name, client]) => ({
47
+ name,
48
+ client,
49
+ server: serverProtocols?.[name],
50
+ state: compareProtocolRanges(client, serverProtocols?.[name]),
51
+ }));
52
+ const states = checks.map((check) => check.state);
53
+ const state = states.includes("update-required")
54
+ ? "update-required"
55
+ : states.includes("unavailable")
56
+ ? "unavailable"
57
+ : states.includes("partial")
58
+ ? "partial"
59
+ : "compatible";
60
+ return { state, checks };
61
+ }
@@ -37,6 +37,11 @@ export const PROVIDER_UPSTREAMS = {
37
37
  mistral: { hostname: "api.mistral.ai", basePath: "" },
38
38
  together: { hostname: "api.together.ai", basePath: "" },
39
39
  deepseek: { hostname: "api.deepseek.com", basePath: "" },
40
+ // Gemini's OpenAI-compat base carries a two-segment prefix, unlike groq's
41
+ // single `/openai`. Listing it here is what makes a CONNECT to Google refuse
42
+ // as `provider_tunnel_not_governed` — and, deliberately, what makes it
43
+ // permanently ineligible for `--allow-connect`.
44
+ gemini: { hostname: "generativelanguage.googleapis.com", basePath: "/v1beta/openai" },
40
45
  };
41
46
 
42
47
  const HOST_BY_NAME = new Map(
@@ -0,0 +1,169 @@
1
+ // "There is a newer PassControl" — the one outbound call this CLI makes on its
2
+ // own initiative, and the constraints that come with that.
3
+ //
4
+ // This is a credential tool. A registry lookup nobody asked for is the kind of
5
+ // thing a security reviewer finds and writes up, so every guard below exists to
6
+ // make the behaviour predictable rather than clever:
7
+ //
8
+ // * It never blocks. The check is fire-and-forget with a short timeout; a
9
+ // registry outage must not add a second to `passcontrol call`.
10
+ // * TTY only. If stdout is not a terminal there is no human to read a notice,
11
+ // which means an agent run, a CI job or a piped command never phones npm.
12
+ // * Never under --json. A notice on stdout would corrupt the document.
13
+ // * Opt-out honoured: PASSCONTROL_NO_UPDATE_CHECK, and NO_UPDATE_NOTIFIER
14
+ // because that is the variable people already set for this class of tool.
15
+ // * Cached for a day in the config directory, so the frequency is bounded by
16
+ // wall-clock time rather than by how often the CLI is run.
17
+ //
18
+ // It reports only that a newer version exists. It never downloads, installs or
19
+ // runs anything — upgrading stays a thing the operator types.
20
+ import fs from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+
24
+ export const REGISTRY_URL = "https://registry.npmjs.org/passcontrol/latest";
25
+ export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
26
+
27
+ /** Beside the existing config and app.json, and created with the same 0700. */
28
+ export function updateCachePath(env = process.env) {
29
+ const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
30
+ return path.join(base, "passcontrol", "update-check.json");
31
+ }
32
+
33
+ /**
34
+ * Compare two versions numerically, segment by segment.
35
+ *
36
+ * A string compare gets this wrong the moment a segment reaches double digits
37
+ * ("0.10.0" < "0.9.0"), which is precisely when an update notice starts to
38
+ * matter. Anything with a prerelease suffix is treated as NOT newer: someone
39
+ * running 0.7.0-rc.1 asked for it and should not be nagged back to 0.6.1.
40
+ */
41
+ export function isNewer(candidate, current) {
42
+ const parse = (value) => {
43
+ const match = /^(\d+)\.(\d+)\.(\d+)$/u.exec(String(value ?? "").trim());
44
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
45
+ };
46
+ const a = parse(candidate);
47
+ const b = parse(current);
48
+ if (!a || !b) return false;
49
+ for (let i = 0; i < 3; i += 1) {
50
+ if (a[i] !== b[i]) return a[i] > b[i];
51
+ }
52
+ return false;
53
+ }
54
+
55
+ // Two gates, and keeping them apart is load-bearing.
56
+ //
57
+ // They answer different questions — "may anything be printed?" and "may the
58
+ // network be touched?" — and a single predicate collapsing both got this
59
+ // wrong: a fresh cache made the combined check return false for the SAME
60
+ // reason a pipe did, so the cached-notice fallback happily printed a notice
61
+ // into a --json document and into piped output. Caught by running it, not by
62
+ // the unit test that asserted the non-TTY case against an empty cache.
63
+
64
+ /** May a notice be shown at all? Nothing here is about time or the network. */
65
+ export function mayAnnounce({ isTty, json = false, env = process.env } = {}) {
66
+ if (!isTty) return false;
67
+ if (json) return false;
68
+ if (env.PASSCONTROL_NO_UPDATE_CHECK || env.NO_UPDATE_NOTIFIER) return false;
69
+ if (env.CI) return false;
70
+ return true;
71
+ }
72
+
73
+ /** May we ask the registry again, or is the cached answer still fresh? */
74
+ export function shouldFetch({ now = Date.now(), cache = null, ttlMs = CACHE_TTL_MS } = {}) {
75
+ if (cache && typeof cache.checkedAt === "number" && now - cache.checkedAt < ttlMs) return false;
76
+ return true;
77
+ }
78
+
79
+ /** Both gates together: check the registry now? */
80
+ export function shouldCheck({
81
+ isTty,
82
+ json = false,
83
+ env = process.env,
84
+ now = Date.now(),
85
+ cache = null,
86
+ ttlMs = CACHE_TTL_MS,
87
+ } = {}) {
88
+ return mayAnnounce({ isTty, json, env }) && shouldFetch({ now, cache, ttlMs });
89
+ }
90
+
91
+ export function readCache(file) {
92
+ try {
93
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
94
+ return parsed && typeof parsed === "object" ? parsed : null;
95
+ } catch {
96
+ // A missing or corrupt cache means "check again", never a crash.
97
+ return null;
98
+ }
99
+ }
100
+
101
+ export function writeCache(file, data) {
102
+ try {
103
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
104
+ fs.writeFileSync(file, `${JSON.stringify(data)}\n`, { mode: 0o600 });
105
+ } catch {
106
+ // An unwritable config dir costs a repeat check, nothing more.
107
+ }
108
+ }
109
+
110
+ /** The notice itself, or null when there is nothing worth saying. */
111
+ export function updateNotice(current, latest) {
112
+ if (!isNewer(latest, current)) return null;
113
+ return `Update available ${current} → ${latest} npm install -g passcontrol@latest`;
114
+ }
115
+
116
+ /**
117
+ * Look up the latest published version. Resolves to null on ANY failure —
118
+ * offline, DNS, a 500, a slow registry, malformed JSON. There is no error path
119
+ * a user should ever see from a background nicety.
120
+ */
121
+ export async function fetchLatest(url = REGISTRY_URL, timeoutMs = 1500, fetchImpl = fetch) {
122
+ const controller = new AbortController();
123
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
124
+ try {
125
+ const res = await fetchImpl(url, {
126
+ signal: controller.signal,
127
+ headers: { accept: "application/vnd.npm.install-v1+json" },
128
+ });
129
+ if (!res.ok) return null;
130
+ const body = await res.json();
131
+ const version = body?.version;
132
+ return typeof version === "string" ? version : null;
133
+ } catch {
134
+ return null;
135
+ } finally {
136
+ clearTimeout(timer);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Run the check and return the notice to print, or null.
142
+ *
143
+ * The caller decides WHEN to print it — after the command's own output, so a
144
+ * nicety never pushes the thing the operator ran off the top of the screen.
145
+ */
146
+ export async function checkForUpdate({
147
+ current,
148
+ isTty = Boolean(process.stdout.isTTY),
149
+ json = false,
150
+ env = process.env,
151
+ now = Date.now(),
152
+ file = updateCachePath(env),
153
+ fetchLatestImpl = fetchLatest,
154
+ } = {}) {
155
+ // Display gate FIRST, and it short-circuits everything: no cache read, no
156
+ // network, no notice. Under --json or a pipe this function does nothing at all.
157
+ if (!mayAnnounce({ isTty, json, env })) return null;
158
+
159
+ const cache = readCache(file);
160
+ if (!shouldFetch({ now, cache })) {
161
+ // Inside the daily window a cached answer is still worth showing — the TTL
162
+ // bounds the network call, not the notice, or an update discovered a minute
163
+ // ago would go unmentioned for the rest of the day.
164
+ return typeof cache?.latest === "string" ? updateNotice(current, cache.latest) : null;
165
+ }
166
+ const latest = await fetchLatestImpl();
167
+ writeCache(file, { checkedAt: now, latest: latest ?? cache?.latest ?? null });
168
+ return latest ? updateNotice(current, latest) : null;
169
+ }
package/cli/verify.mjs CHANGED
@@ -7,10 +7,13 @@
7
7
  // Nothing here needs a PassControl account, an API key, or a passport. You need
8
8
  // the artifact and the issuer's origin. That is the whole point.
9
9
  import { ed25519 } from "@noble/curves/ed25519";
10
+ import { RECEIPT_PROTOCOL } from "./protocols.mjs";
10
11
 
11
12
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
12
13
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
13
- export const SUPPORTED_VER = 1;
14
+ // Receipts v2 add Direct Agent identity claims. This is a maximum, not an
15
+ // equality check: v1 receipts remain independently verifiable forever.
16
+ export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
14
17
 
15
18
  const fromB64url = (value) =>
16
19
  new Uint8Array(Buffer.from(String(value).replace(/-/g, "+").replace(/_/g, "/"), "base64"));
@@ -0,0 +1,24 @@
1
+ // Import reporting is shared as a tiny pure module so the CLI's terminal
2
+ // branch is tested as behaviour, not merely as a source-text string. In
3
+ // particular, a file whose agents were all REFUSED must never print the
4
+ // reassuring message reserved for a workspace that already owns every agent.
5
+
6
+ export function noAgentCreateMessage(agents) {
7
+ const rejected = Array.isArray(agents?.rejected) ? agents.rejected.length : 0;
8
+ const skipped = Array.isArray(agents?.skipped) ? agents.skipped.length : 0;
9
+
10
+ if (rejected > 0) {
11
+ return `Nothing was created. ${rejected} agent(s) were refused; review the reasons above before retrying.`;
12
+ }
13
+ if (skipped > 0) {
14
+ return "Nothing to create. The workspace already holds every agent in this file.";
15
+ }
16
+ return "Nothing to create.";
17
+ }
18
+
19
+ export function importCompletionMessage(report) {
20
+ const created = Array.isArray(report?.agents?.created) ? report.agents.created.length : 0;
21
+ return report?.complete === false
22
+ ? `Import completed partially: ${created} agent(s) created; review the refused entries above.`
23
+ : `Created ${created} agent(s).`;
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",
package/sdk/control.d.ts CHANGED
@@ -70,9 +70,16 @@ export declare class ControlClient {
70
70
  }>;
71
71
  };
72
72
  readonly logs: {
73
+ /**
74
+ * `class` selects a view, never a different record: omitted returns every
75
+ * call, `inference` drops SDK housekeeping (startup model-listing probes),
76
+ * `housekeeping` returns only those. The limit is applied before the
77
+ * filter, so a filtered page can be shorter than the limit asked for.
78
+ */
73
79
  list: (params?: {
74
80
  agent_id?: string;
75
81
  status?: string;
82
+ class?: "inference" | "housekeeping";
76
83
  limit?: number;
77
84
  }) => Promise<any[]>;
78
85
  };
package/sdk/control.js CHANGED
@@ -87,6 +87,12 @@ export class ControlClient {
87
87
  revoke: (id, opts) => this.req("DELETE", `/agents/${encodeURIComponent(id)}`, { idempotencyKey: opts?.idempotencyKey }),
88
88
  };
89
89
  logs = {
90
+ /**
91
+ * `class` selects a view, never a different record: omitted returns every
92
+ * call, `inference` drops SDK housekeeping (startup model-listing probes),
93
+ * `housekeeping` returns only those. The limit is applied before the
94
+ * filter, so a filtered page can be shorter than the limit asked for.
95
+ */
90
96
  list: (params) => this.req("GET", "/logs", { query: params }),
91
97
  };
92
98
  audit = {
@@ -1,4 +1,4 @@
1
- export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek";
1
+ export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek" | "gemini";
2
2
  export interface PassControlOptions {
3
3
  /**
4
4
  * Gateway origin, e.g. https://passcontrol.example.com — scheme, host and
package/sdk/verify.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export declare const RECEIPT_TYP = "passcontrol-receipt+jwt";
2
2
  export declare const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
3
3
  /** The newest artifact version this verifier understands. */
4
- export declare const SUPPORTED_VER = 2;
4
+ export declare const SUPPORTED_VER: number;
5
5
  export type VerifyFailure = "malformed" | "untrusted_issuer" | "unknown_key" | "bad_signature" | "wrong_type" | "unsupported_version" | "jwks_unreachable" | "expired" | "wrong_audience" | "revoked" | "status_unavailable";
6
6
  export type VerifyResult<T> = {
7
7
  ok: true;
@@ -44,9 +44,20 @@ export interface ReceiptClaims {
44
44
  dig: string;
45
45
  len: number;
46
46
  };
47
+ /**
48
+ * Tokens the call consumed. `in` is the provider's own uncached input count;
49
+ * `cr` / `cw` are prompt-cache reads and writes, present only when the provider
50
+ * reported them, so the whole input is `in + (cr ?? 0) + (cw ?? 0)`. Do not sum
51
+ * them into `in` — it is already exclusive of both, and `cost` covers all three.
52
+ *
53
+ * Added after v2 shipped and readable by verifiers that predate them, because
54
+ * unknown claims inside a supported version are ignored by design.
55
+ */
47
56
  use: {
48
57
  in: number;
49
58
  out: number;
59
+ cr?: number;
60
+ cw?: number;
50
61
  };
51
62
  cost: number;
52
63
  res: {
package/sdk/verify.js CHANGED
@@ -8,10 +8,11 @@
8
8
  // Dependencies: only @noble/curves + the platform `fetch`. Runs on Node 18+,
9
9
  // edge runtimes, and the browser.
10
10
  import { ed25519 } from "@noble/curves/ed25519";
11
+ import { RECEIPT_PROTOCOL } from "../cli/protocols.mjs";
11
12
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
12
13
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
13
14
  /** The newest artifact version this verifier understands. */
14
- export const SUPPORTED_VER = 2;
15
+ export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
15
16
  const b64urlToBytes = (value) => {
16
17
  const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
17
18
  const pad = b64.length % 4 === 0 ? "" : "=".repeat(4 - (b64.length % 4));