passcontrol 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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";
@@ -217,8 +225,23 @@ export function configPathLabel(sources = configSources) {
217
225
  return "none";
218
226
  }
219
227
 
228
+ /**
229
+ * Write the whole config. Every CONFIG_KEY is emitted, so a key absent from
230
+ * `values` is BLANKED — that is correct for `init`, which collects all of them,
231
+ * and wrong for any caller that means to change a subset. Use mergeConfigFile
232
+ * for those.
233
+ *
234
+ * The chmod is not redundant with the `mode` option. Node applies `mode` only
235
+ * when it CREATES the file, so overwriting a config that already exists as 0644
236
+ * leaves it 0644 — and this file holds a passport secret. The directory mode is
237
+ * applied on the global path only: for a project-local `.passcontrol` the
238
+ * dirname is the user's own project directory, and silently 0700-ing that is a
239
+ * surprising thing for a config write to do.
240
+ */
220
241
  export function writeConfigFile(file, values) {
221
- fs.mkdirSync(path.dirname(file), { recursive: true });
242
+ const dir = path.dirname(file);
243
+ const isGlobal = path.resolve(file) === path.resolve(globalConfigPath());
244
+ fs.mkdirSync(dir, { recursive: true, ...(isGlobal ? { mode: 0o700 } : {}) });
222
245
  const lines = [
223
246
  "# PassControl CLI config.",
224
247
  "# Keep this file private: it can contain a passport secret.",
@@ -228,6 +251,33 @@ export function writeConfigFile(file, values) {
228
251
  lines.push(`${key}=${values[key] ?? ""}`);
229
252
  }
230
253
  fs.writeFileSync(file, `${lines.join("\n")}\n`, { mode: 0o600 });
254
+ // Explicit, because `mode` above is a no-op on an existing file.
255
+ try {
256
+ fs.chmodSync(file, 0o600);
257
+ if (isGlobal) fs.chmodSync(dir, 0o700);
258
+ } catch {
259
+ // Windows and some network filesystems have no meaningful POSIX mode. A
260
+ // config that is written but not tightened beats a login that dies here.
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Change SOME keys, keeping the rest.
266
+ *
267
+ * `passcontrol login` writes three credential keys. Routing that through
268
+ * writeConfigFile would emit `PROVIDER=`, `MODEL=` and `PASSCONTROL_GATEWAY=`
269
+ * as empty strings and wipe a working setup — right result, wrong side effect,
270
+ * and invisible until the next call failed against the wrong provider.
271
+ */
272
+ export function mergeConfigFile(file, patch) {
273
+ let existing = {};
274
+ try {
275
+ existing = readConfigFile(file);
276
+ } catch {
277
+ // No file yet, or unreadable. A first login lands here, and writing the
278
+ // patch alone is exactly right — there is nothing to preserve.
279
+ }
280
+ writeConfigFile(file, { ...existing, ...patch });
231
281
  }
232
282
 
233
283
  export function heading(message = "") {
@@ -347,6 +397,27 @@ export function bareGatewayOrigin(gateway, label = "PASSCONTROL_GATEWAY") {
347
397
  * part of the credential's security, not configuration taste. Every `api()` call
348
398
  * resolves its destination through this, never through the raw config string.
349
399
  */
400
+ /**
401
+ * The same origin rule, for probes that carry NO credential.
402
+ *
403
+ * `passcontrol version` reads an unauthenticated /api/version, so the leak the
404
+ * rule normally prevents — a signature or a `pc_` key reaching a host the
405
+ * operator did not choose — does not apply. The destination still has to be
406
+ * validated: a project-local `.passcontrol` pointing elsewhere would make a
407
+ * DIAGNOSTIC command report a stranger's build as your gateway's, which is its
408
+ * own kind of wrong answer, and it would turn `version` into a beacon.
409
+ *
410
+ * Returns null rather than throwing. A malformed gateway is a row in a report
411
+ * here, not a reason to abort the command the operator actually ran.
412
+ */
413
+ export function probeGatewayOrigin(current = config) {
414
+ try {
415
+ return bareGatewayOrigin(current.gateway);
416
+ } catch {
417
+ return null;
418
+ }
419
+ }
420
+
350
421
  export function requireControlGateway(current = config) {
351
422
  assertConfigLoaded();
352
423
  return bareGatewayOrigin(current.gateway);
package/cli/login.mjs ADDED
@@ -0,0 +1,378 @@
1
+ // `passcontrol login` — browser-approved credentials for this machine.
2
+ //
3
+ // The problem it removes: getting a passport onto a machine used to mean opening
4
+ // the dashboard, issuing an agent, copying two 43-character base64url strings,
5
+ // and pasting both into an interactive prompt with the secret echoed to the
6
+ // terminal. That is the friction that loses the "$5 vs. do it myself" user, and
7
+ // it produced this repo's one real incident — a passport secret pasted into a
8
+ // provider `api_key` field, rejected 401 with no audit row to explain it.
9
+ //
10
+ // ── The shape, and why it is this shape ──────────────────────────────────────
11
+ //
12
+ // RFC 8628 device flow. The CLI opens a login, prints an 8-character code,
13
+ // copies it to the clipboard, opens the browser, and polls. The operator pastes
14
+ // the code and approves once.
15
+ //
16
+ // The code travels TERMINAL → BROWSER and never the reverse, and never in a URL.
17
+ // The human moving it across IS the channel binding — it is the only evidence
18
+ // that the person at the browser is the person at the terminal. A pre-filled
19
+ // approval link removes exactly that: the attacker starts the flow on their own
20
+ // machine, keeps the device_code, sends the victim the link, and the signed-in
21
+ // victim's click hands over a write-scoped control-plane key on their own tenant.
22
+ // tests/cli-login-shape.test.ts pins the URL against that design returning.
23
+ //
24
+ // The clipboard copy is not the same thing and does not reopen it: an attacker
25
+ // cannot write to your clipboard from a link. The code reaches the browser from
26
+ // a process the operator launched on their own machine.
27
+ //
28
+ // ── Why this file exists at all, instead of living in bin/ ───────────────────
29
+ //
30
+ // It must not be able to reach the self-host clone. `openDashboard` in bin/ is
31
+ // not a URL opener — for a localhost gateway it routes through `startDashboard`,
32
+ // which is `ensureAppRoot({ clone: true })`. Putting login beside it invites the
33
+ // obvious reuse, which would make a `git clone` the second thing a Cloud user's
34
+ // first command does. This module opens URLs through `openUrl` only, and the
35
+ // test suite asserts it names neither of the cloning helpers.
36
+ import { spawn } from "node:child_process";
37
+ import os from "node:os";
38
+ import { ed25519 } from "@noble/curves/ed25519";
39
+ import fs from "node:fs";
40
+ import {
41
+ fail,
42
+ findProjectConfig,
43
+ globalConfigPath,
44
+ heading,
45
+ mergeConfigFile,
46
+ ok,
47
+ requireControlGateway,
48
+ step,
49
+ warn,
50
+ } from "./config.mjs";
51
+
52
+ const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
53
+
54
+ /** Display form, `FKDR-8T2W`. Presentation only — the wire form has no hyphen. */
55
+ function formatCode(code) {
56
+ return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
57
+ }
58
+
59
+ /**
60
+ * Copy text to the OS clipboard. Resolves true on success, false on ANY failure.
61
+ *
62
+ * Never throws and never rejects: a clipboard is a convenience, and a login that
63
+ * dies because a Linux box has no `wl-copy` would be a worse product than one
64
+ * that just prints the code. The caller prints the code unconditionally and uses
65
+ * this only to decide whether to add "(copied to your clipboard)".
66
+ *
67
+ * Both failure modes are handled, and they are easy to conflate:
68
+ * - `error` the binary is absent. On Linux this is the COMMON case — none of
69
+ * wl-copy / xclip / xsel is guaranteed installed.
70
+ * - `close` the binary exists and exited non-zero (no display, no Wayland
71
+ * socket, a wedged X server). `error` does not fire for this.
72
+ */
73
+ export function copyToClipboard(text, { platform = process.platform } = {}) {
74
+ const candidates =
75
+ platform === "darwin"
76
+ ? [["pbcopy", []]]
77
+ : platform === "win32"
78
+ ? [["clip", []]]
79
+ : [
80
+ ["wl-copy", []],
81
+ ["xclip", ["-selection", "clipboard"]],
82
+ ["xsel", ["--clipboard", "--input"]],
83
+ ];
84
+
85
+ const tryOne = (index) =>
86
+ new Promise((resolve) => {
87
+ const candidate = candidates[index];
88
+ if (!candidate) return resolve(false);
89
+ const [command, args] = candidate;
90
+ let settled = false;
91
+ const done = (value) => {
92
+ if (settled) return;
93
+ settled = true;
94
+ resolve(value);
95
+ };
96
+ let child;
97
+ try {
98
+ child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] });
99
+ } catch {
100
+ return done(false);
101
+ }
102
+ child.on("error", () => done(false));
103
+ child.on("close", (code) => done(code === 0));
104
+ try {
105
+ child.stdin.on("error", () => done(false));
106
+ child.stdin.write(text);
107
+ // pbcopy does not exit until stdin closes. A forgotten end() here hangs
108
+ // the login on the one step that was supposed to make it effortless.
109
+ child.stdin.end();
110
+ } catch {
111
+ done(false);
112
+ }
113
+ });
114
+
115
+ return (async () => {
116
+ for (let i = 0; i < candidates.length; i++) {
117
+ if (await tryOne(i)) return true;
118
+ }
119
+ return false;
120
+ })();
121
+ }
122
+
123
+ /** The approval route. Fixed here, not taken on trust from the response. */
124
+ export const APPROVAL_PATH = "/dashboard/cli";
125
+
126
+ /**
127
+ * Decide where the browser is sent — locally, from the origin the operator
128
+ * configured, and never from the response body alone.
129
+ *
130
+ * The server does send a `verification_uri`, and honouring it blindly would make
131
+ * "where does my browser go" a value supplied over the network. Two things fall
132
+ * out of that, both bad: a gateway that is wrong or compromised could point the
133
+ * operator anywhere, and a future server could reintroduce the rejected
134
+ * pre-filled `#code=` design without a single line changing in the CLI.
135
+ *
136
+ * So the response is accepted only if it agrees with what we would have built:
137
+ * same origin, same path, and NO fragment or query. Anything else falls back to
138
+ * the local construction rather than failing the login — the code still has to
139
+ * be entered by hand either way, so a mismatch is a reason to distrust the URL,
140
+ * not a reason to strand the operator.
141
+ */
142
+ export function approvalUrl(origin, offered, { onMismatch = () => {} } = {}) {
143
+ const expected = `${origin}${APPROVAL_PATH}`;
144
+ if (offered && offered !== expected) {
145
+ // Always the locally-built URL — the report exists so a disagreement is
146
+ // visible rather than silently obeyed. A gateway offering a different origin,
147
+ // a different path, or a `#code=` fragment is either misconfigured or
148
+ // hostile, and both are worth saying out loud.
149
+ onMismatch(String(offered));
150
+ }
151
+ return expected;
152
+ }
153
+
154
+ /** POST JSON with no credential attached. `login` has no key yet by definition. */
155
+ async function postJson(url, body, { timeoutMs = 15_000, fetchImpl = fetch } = {}) {
156
+ const controller = new AbortController();
157
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
158
+ try {
159
+ const res = await fetchImpl(url, {
160
+ method: "POST",
161
+ headers: { "content-type": "application/json" },
162
+ body: JSON.stringify(body ?? {}),
163
+ signal: controller.signal,
164
+ });
165
+ let parsed = null;
166
+ try {
167
+ parsed = await res.json();
168
+ } catch {
169
+ parsed = null;
170
+ }
171
+ return { status: res.status, body: parsed };
172
+ } finally {
173
+ clearTimeout(timer);
174
+ }
175
+ }
176
+
177
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
178
+
179
+ /**
180
+ * Poll until the operator approves, denies, or the login expires.
181
+ *
182
+ * Honours the server's `interval` and backs off on `slow_down`, so the poll rate
183
+ * is the server's decision and can be widened without shipping a new CLI.
184
+ */
185
+ async function pollForGrant(origin, deviceCode, { interval, expiresIn, fetchImpl, now = Date.now }) {
186
+ const deadline = now() + expiresIn * 1000;
187
+ let waitMs = Math.max(500, interval * 1000);
188
+ while (now() < deadline) {
189
+ await sleep(waitMs);
190
+ const res = await postJson(`${origin}/api/auth/device/token`, { device_code: deviceCode }, { fetchImpl });
191
+ if (res.status === 200 && res.body?.api_key) return res.body;
192
+ const error = res.body?.error;
193
+ if (error === "access_denied") {
194
+ throw new Error("Login was denied in the browser. Nothing was created.");
195
+ }
196
+ if (error === "expired_token") {
197
+ throw new Error("That login expired before it was approved. Run `passcontrol login` again.");
198
+ }
199
+ // slow_down is the server asking for room; anything else unexpected gets the
200
+ // same treatment rather than a tight retry loop against an unhealthy host.
201
+ if (error === "slow_down" || res.status >= 500) waitMs = Math.min(waitMs * 2, 10_000);
202
+ }
203
+ throw new Error("Timed out waiting for approval. Run `passcontrol login` again.");
204
+ }
205
+
206
+ /** Authenticated control-plane call, using the key this flow just collected. */
207
+ async function control(origin, apiKey, method, path, body, fetchImpl = fetch) {
208
+ const res = await fetchImpl(`${origin}/api/control/v1${path}`, {
209
+ method,
210
+ headers: {
211
+ authorization: `Bearer ${apiKey}`,
212
+ ...(body ? { "content-type": "application/json" } : {}),
213
+ },
214
+ ...(body ? { body: JSON.stringify(body) } : {}),
215
+ });
216
+ const parsed = await res.json().catch(() => null);
217
+ if (!res.ok) {
218
+ throw new Error(`Control plane refused ${method} ${path} (${res.status}).`);
219
+ }
220
+ return parsed;
221
+ }
222
+
223
+ /**
224
+ * Warn when the file we are about to write will NOT be the one that wins.
225
+ *
226
+ * `cli/config.mjs` resolves env → nearest project `.passcontrol` → global. A
227
+ * user with a project config in cwd would otherwise see "✓ Wrote
228
+ * ~/.config/passcontrol/config" and then watch `passcontrol call` keep using the
229
+ * old passport — right result, wrong file wins, and nothing visibly broken.
230
+ */
231
+ function warnIfShadowed(target, { cwd = process.cwd() } = {}) {
232
+ if (target !== globalConfigPath()) return false;
233
+ const project = findProjectConfig(cwd);
234
+ if (!project) return false;
235
+ warn(`A project config at ${project} takes priority over the file just written.`);
236
+ step("Commands run from this directory will keep using it. Use --project to write there instead.");
237
+ return true;
238
+ }
239
+
240
+ /**
241
+ * Refuse to destroy a working passport without being told to.
242
+ *
243
+ * `mergeConfigFile` preserves PROVIDER and MODEL, but it necessarily REPLACES
244
+ * PASSPORT_ID and PASSPORT_SECRET — and PassControl has never held a copy of
245
+ * that private key, so overwriting it is unrecoverable. `init` has always asked
246
+ * before clobbering a config; a command designed to be run casually must ask at
247
+ * least as loudly.
248
+ *
249
+ * Defaults to NO. The safe answer is the one you get by pressing enter, because
250
+ * the cost of a stray yes here is an agent that silently stops authenticating on
251
+ * every other machine that shared the passport.
252
+ */
253
+ async function confirmReplacingPassport(target, confirm) {
254
+ let existing = "";
255
+ try {
256
+ existing = fs.readFileSync(target, "utf8");
257
+ } catch {
258
+ return true; // Nothing there. Nothing to lose.
259
+ }
260
+ const current = /^PASSPORT_SECRET=(.+)$/mu.exec(existing)?.[1]?.trim();
261
+ if (!current) return true;
262
+
263
+ warn(`${target} already holds a passport secret.`);
264
+ step("Continuing replaces it, and PassControl has no copy — anything still using that");
265
+ step("passport keeps working only until you revoke or rotate the agent behind it.");
266
+ return confirm("Replace it? [y/N] ", { default: false });
267
+ }
268
+
269
+ export async function loginCommand(opts = {}, deps = {}) {
270
+ const fetchImpl = deps.fetch ?? fetch;
271
+ const openUrl = deps.openUrl ?? (() => {});
272
+ const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
273
+ const promptLine = deps.promptLine ?? (async (_q, fallback) => fallback);
274
+
275
+ // Validate the destination BEFORE anything is requested — the ordering mintVisa
276
+ // uses. A rejected gateway must cost zero sockets.
277
+ const origin = requireControlGateway();
278
+
279
+ const clientName = String(opts.name || os.hostname() || "this machine");
280
+ const started = await postJson(
281
+ `${origin}/api/auth/device/start`,
282
+ { client_name: clientName },
283
+ { fetchImpl }
284
+ );
285
+ if (started.status !== 200 || !started.body?.user_code) {
286
+ throw new Error(`Could not start a login at ${origin} (${started.status}).`);
287
+ }
288
+ const { device_code: deviceCode, user_code: userCode } = started.body;
289
+ const verificationUri = approvalUrl(origin, started.body.verification_uri, {
290
+ onMismatch: () => warn("The gateway offered a different approval URL. Using the configured origin."),
291
+ });
292
+
293
+ // Print FIRST and unconditionally. Only the suffix depends on the clipboard —
294
+ // a headless box that says "copied to your clipboard" with nothing to paste is
295
+ // worse than one that never mentioned a clipboard at all.
296
+ const copied = await copyToClipboard(userCode);
297
+ console.log("");
298
+ console.log(heading("Approve this machine"));
299
+ console.log(` Code: ${formatCode(userCode)}${copied ? " (copied to your clipboard)" : ""}`);
300
+ console.log(` Open: ${verificationUri}`);
301
+ console.log("");
302
+ step("Paste the code there and press Approve. Waiting…");
303
+ openUrl(verificationUri);
304
+
305
+ const grant = await pollForGrant(origin, deviceCode, {
306
+ interval: Number(started.body.interval ?? 1),
307
+ expiresIn: Number(started.body.expires_in ?? 600),
308
+ fetchImpl,
309
+ });
310
+ ok("approved");
311
+
312
+ // ── Provision a passport for this machine ─────────────────────────────────
313
+ //
314
+ // The keypair is generated HERE and only the PUBLIC half is sent. The gateway
315
+ // has never held a passport private key; this command must not be the first
316
+ // thing to change that.
317
+ const agents = (await control(origin, grant.api_key, "GET", "/agents", null, fetchImpl))?.agents ?? [];
318
+ let agentId = null;
319
+ if (agents.length > 0 && !opts.new) {
320
+ step(`This workspace has ${agents.length} agent(s).`);
321
+ const existing = await promptLine("Agent id to reuse, or blank to create a new one: ", "");
322
+ if (existing) {
323
+ // Reusing means ROTATING, and rotation is not free — say so before doing it.
324
+ warn(`PassControl has never held that agent's private key, so this machine cannot be given`);
325
+ step(`the existing one. Continuing rotates it: any other machine using that passport stops`);
326
+ step(`working once the grace window lapses.`);
327
+ if (await confirm("Create a NEW agent for this machine instead? [Y/n] ")) agentId = null;
328
+ else agentId = existing;
329
+ }
330
+ }
331
+
332
+ const priv = ed25519.utils.randomPrivateKey();
333
+ const passportId = b64url(ed25519.getPublicKey(priv));
334
+ const passportSecret = b64url(priv);
335
+
336
+ if (agentId) {
337
+ await control(origin, grant.api_key, "POST", `/agents/${encodeURIComponent(agentId)}/rotate`, {
338
+ passportPubkey: passportId,
339
+ }, fetchImpl);
340
+ ok(`rotated passport for agent ${agentId}`);
341
+ } else {
342
+ const created = await control(origin, grant.api_key, "POST", "/agents", {
343
+ name: clientName,
344
+ passportPubkey: passportId,
345
+ scopes: [{ provider: "anthropic", models: ["claude-*"] }],
346
+ }, fetchImpl);
347
+ agentId = created?.id ?? null;
348
+ ok(`created agent ${created?.name ?? clientName}`);
349
+ }
350
+
351
+ // MERGE, never a full write. writeConfigFile emits every CONFIG_KEY, so a
352
+ // three-key write would blank PROVIDER, MODEL and PASSCONTROL_GATEWAY — right
353
+ // result, wrong side effect, invisible until the next call hit the wrong
354
+ // provider.
355
+ const target = opts.project ? `${process.cwd()}/.passcontrol` : globalConfigPath();
356
+ if (!(await confirmReplacingPassport(target, confirm))) {
357
+ // The agent and its key were already created server-side, so say what exists
358
+ // rather than pretending nothing happened. Leaving the operator with an
359
+ // orphaned agent AND no explanation would be the worse failure.
360
+ warn("Left the existing config unchanged.");
361
+ step(`The new passport was NOT saved. Agent ${agentId ?? "(unknown)"} and the key`);
362
+ step(`"CLI on ${clientName}" now exist unused — revoke them in Settings.`);
363
+ return { agentId, passportId, target: null };
364
+ }
365
+ mergeConfigFile(target, {
366
+ PASSCONTROL_GATEWAY: origin,
367
+ PASSPORT_ID: passportId,
368
+ PASSPORT_SECRET: passportSecret,
369
+ PASSCONTROL_API_KEY: grant.api_key,
370
+ });
371
+ ok(`wrote ${target}`);
372
+ warnIfShadowed(target);
373
+
374
+ step("");
375
+ step('Try it: passcontrol call "hi"');
376
+ step(`The key is listed in Settings as "CLI on ${clientName}" and can be revoked there.`);
377
+ return { agentId, passportId, target };
378
+ }
@@ -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(