@dicamo/flint-ai-bridge 1.0.9 → 1.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/README.md CHANGED
@@ -15,42 +15,39 @@ Currently verified on macOS. Windows and Linux support is in progress.
15
15
 
16
16
  ## Connect for the first time
17
17
 
18
- ### 1. Register your CMS
18
+ ### 1. Set up the bridge (once)
19
19
 
20
- Replace the example URLs with the values provided by your administrator.
20
+ Copy the command from CMS **Settings > AI connection**, or replace the example URLs with the values provided by your administrator:
21
21
 
22
22
  ```sh
23
- npx @dicamo/flint-ai-bridge@latest configure \
24
- --id my-cms \
23
+ npx @dicamo/flint-ai-bridge@latest setup \
25
24
  --server https://api.example.com \
26
25
  --origin https://cms.example.com
27
26
  ```
28
27
 
28
+ `setup` registers the CMS, makes the bridge start whenever you sign in to your computer, and starts it now with chat enabled. Run it again to change the URLs or to upgrade; it restarts the bridge for you.
29
+
29
30
  | Option | Value |
30
31
  | --- | --- |
31
- | `--id` | A name for this connection using lowercase letters, numbers, and hyphens |
32
32
  | `--server` | The server URL provided by your administrator |
33
33
  | `--origin` | The CMS URL you open in your browser |
34
+ | `--id` | Optional connection name (lowercase letters, numbers, hyphens). Default: `flint` |
34
35
 
35
36
  Include `https://`, without page paths such as `/device` or a trailing `/`.
36
- Stop the running bridge before changing these URLs.
37
37
 
38
- ### 2. Start the bridge
38
+ Start at login uses a LaunchAgent on macOS (`~/Library/LaunchAgents/dev.dicamo.flint-ai-bridge.plist`) and the current user's Run registry key on Windows. On Linux, run `start --enable-chat` after each login. The login item is pinned to the bridge version that ran `setup`, so it works offline from the npx cache.
39
39
 
40
- ```sh
41
- npx @dicamo/flint-ai-bridge@latest start --enable-chat
42
- ```
40
+ When chat is enabled, startup checks Claude Code in a temporary directory and stops it after inspecting its initialization event. No CMS credentials or data are passed to this check. If the check fails, the bridge stays available for pairing and CMS shows that chat is off.
43
41
 
44
- When chat is requested, startup checks Claude Code in a temporary directory and stops it after inspecting its initialization event. No CMS credentials or data are passed to this check. If the check fails, the bridge stays available for pairing and displays the reason chat is disabled. Retry by stopping and starting the bridge after resolving the issue.
42
+ ### 2. Allow this browser
45
43
 
46
- You can close the terminal after startup. The bridge keeps running in the background. On macOS, approve the connection in the desktop dialog. A six-digit pairing code is also available in `~/.flint-ai-bridge/bridge.log` as a fallback.
44
+ 1. In CMS, open **Settings > AI connection** and press **Search again**.
45
+ 2. Choose **Connect this PC**. Check the CMS URL in the desktop dialog, then select **Allow**. If the dialog is unavailable, open the code option and enter the six-digit code from `~/.flint-ai-bridge/bridge.log`.
46
+ 3. Allow local network access if your browser requests it.
47
47
 
48
- ### 3. Connect from CMS
48
+ The bridge remembers an allowed browser for 30 days, also across restarts, so the chat connects on its own. Only a hash of the browser's token is stored on your computer.
49
49
 
50
- 1. Sign in to CMS and open **Flint AI** in the bottom-right corner.
51
- 2. Choose the option to connect to this computer. Check the CMS URL in the desktop dialog, then select **Allow**. Use the code-pairing option if the dialog is unavailable.
52
- 3. Allow local network access if your browser requests it.
53
- 4. Wait for connection and account verification to complete.
50
+ After that, open **Flint AI** in the bottom-right corner of CMS and chat. If the browser is not connected yet, the chat links to Settings.
54
51
 
55
52
  Pairing codes expire after five minutes. In foreground mode (`serve --enable-chat`), enter `pair` in the bridge terminal to generate a new code.
56
53
 
@@ -66,19 +63,20 @@ Select the Claude model at the top of the chat: CLI default, Sonnet, Opus, or Ha
66
63
 
67
64
  ## Reconnect or stop
68
65
 
69
- The bridge does not reconnect automatically or save pairing credentials in the browser. If disconnected, start the bridge, search again in CMS, and approve a new connection to this computer. The approval dialog expires after 60 seconds.
66
+ An allowed browser reconnects on its own for 30 days. After that, or after you disconnect it in CMS settings, allow it again.
70
67
 
71
- Check the bridge status or stop it:
68
+ Check the bridge status, stop it, or stop starting it at login:
72
69
 
73
70
  ```sh
74
71
  npx @dicamo/flint-ai-bridge@latest status
75
72
  npx @dicamo/flint-ai-bridge@latest stop
73
+ npx @dicamo/flint-ai-bridge@latest uninstall
76
74
  ```
77
75
 
78
- Run `start --enable-chat` again after restarting your computer. The bridge does not register itself to start at login. Runtime errors and fallback pairing codes are written to `~/.flint-ai-bridge/bridge.log`. To view output directly in a terminal, use `serve --enable-chat` and press `Ctrl+C` to stop.
76
+ `stop` keeps the login item, so the bridge starts again at your next login. `uninstall` removes the login item and stops the bridge; registered servers and remembered browsers are kept. Runtime errors and fallback pairing codes are written to `~/.flint-ai-bridge/bridge.log`. To view output directly in a terminal, stop the bridge and use `serve --enable-chat`; press `Ctrl+C` to stop.
79
77
 
80
- Use the unpair option in Flint AI to disconnect the current CMS.
81
- To revoke all CMS pairings on this computer, run:
78
+ Use **Disconnect** in CMS settings to forget the current browser.
79
+ To revoke all remembered browsers on this computer, run:
82
80
 
83
81
  ```sh
84
82
  npx @dicamo/flint-ai-bridge@latest unpair
@@ -87,9 +85,9 @@ npx @dicamo/flint-ai-bridge@latest unpair
87
85
  ## Troubleshooting
88
86
 
89
87
  - **The Flint AI button is missing:** Ask your CMS administrator to check your AI assistant permission.
90
- - **CMS cannot find the bridge:** Check that the bridge is running and that your browser allows local network access.
88
+ - **CMS cannot find the bridge:** Run `status`. If it is stopped, run `setup` again. Also check that your browser allows local network access.
91
89
  - **The pairing code expired:** In foreground mode, enter `pair` in the bridge terminal. If repeated incorrect attempts have locked pairing, wait 60 seconds before generating another code.
92
- - **The URL is not registered:** Stop the bridge and register the CMS and server URLs again.
90
+ - **The URL is not registered:** Run `setup` again with the right URLs.
93
91
  - **Account or permission verification failed:** Sign in to CMS again. Contact your administrator if the problem persists.
94
92
 
95
93
  Command help:
@@ -1,5 +1,6 @@
1
1
  // src/protocol.ts
2
2
  var PROTOCOL_VERSION = 1;
3
+ var BRIDGE_VERSION = "1.1.0";
3
4
  var PORTS = Array.from({ length: 10 }, (_, i) => 47820 + i);
4
5
  var CLAUDE_MODELS = ["default", "sonnet", "opus", "haiku"];
5
6
  var AI_CLAIM = "enable:ai.assistant";
@@ -8,6 +9,7 @@ var RESOURCES = ["companies", "devices", "studio", "media", "dashboard", "users"
8
9
 
9
10
  export {
10
11
  PROTOCOL_VERSION,
12
+ BRIDGE_VERSION,
11
13
  PORTS,
12
14
  CLAUDE_MODELS,
13
15
  AI_CLAIM,
package/dist/cli.js CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  AI_CLAIM,
4
+ BRIDGE_VERSION,
4
5
  CLAUDE_MODELS,
5
6
  MAX_MESSAGE_BYTES,
6
7
  PORTS,
7
8
  RESOURCES
8
- } from "./chunk-ZUPMLKCI.js";
9
+ } from "./chunk-SST2QOUV.js";
9
10
 
10
11
  // src/cli.ts
11
12
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -210,11 +211,11 @@ async function startBackground(directory, entry, chat) {
210
211
  }
211
212
 
212
213
  // src/cli.ts
213
- import { homedir } from "os";
214
- import { join as join4, resolve } from "path";
214
+ import { homedir as homedir2 } from "os";
215
+ import { join as join5, resolve } from "path";
215
216
  import { parseArgs } from "util";
216
217
  import { watchFile, unwatchFile } from "fs";
217
- import { access, writeFile as writeFile4, mkdir as mkdir3, unlink as unlink3 } from "fs/promises";
218
+ import { access as access2, writeFile as writeFile5, mkdir as mkdir4, unlink as unlink4 } from "fs/promises";
218
219
  import { createInterface } from "readline";
219
220
 
220
221
  // src/config.ts
@@ -964,7 +965,7 @@ function assertClaudeIsolation(event, allowed) {
964
965
  const e = event;
965
966
  if (!e || !Array.isArray(e.tools) || e.tools.some((tool) => typeof tool !== "string" || !allowed.has(tool)) || e.permissionMode !== "dontAsk" || !Array.isArray(e.skills) || e.skills.length !== 0 || !Array.isArray(e.plugins) || e.plugins.some((plugin) => !plugin || typeof plugin !== "object" || plugin.path !== "builtin") || !Array.isArray(e.mcp_servers) || e.mcp_servers.some((server) => !server || typeof server !== "object" || server.name !== "flint-cms")) throw new Error("claude_isolation_unavailable");
966
967
  }
967
- async function checkClaudeCapabilities(directory, cli, run2 = runJsonProcess) {
968
+ async function checkClaudeCapabilities(directory, cli, run3 = runJsonProcess) {
968
969
  if (!cli?.installed) return { ready: false, reason: "Claude Code is not installed or is not available on PATH." };
969
970
  if (cli.authStatus !== "subscription") return { ready: false, reason: "Sign in to Claude Code with a subscription account, then restart the bridge." };
970
971
  const version = cli.version ?? "unknown";
@@ -976,7 +977,7 @@ async function checkClaudeCapabilities(directory, cli, run2 = runJsonProcess) {
976
977
  const config = join2(dir, "mcp.json");
977
978
  await writeFile2(config, JSON.stringify({ mcpServers: {} }), { mode: 384 });
978
979
  try {
979
- await run2({ command: "claude", args: [...claudeIsolationArgs(config), "--system-prompt", "Initialize the CLI capability check."], cwd: dir, env: claudeEnvironment(), input: "Initialize.", signal: controller.signal, timeoutMs: 12e3, maxBytes: 262144, onEvent(event) {
980
+ await run3({ command: "claude", args: [...claudeIsolationArgs(config), "--system-prompt", "Initialize the CLI capability check."], cwd: dir, env: claudeEnvironment(), input: "Initialize.", signal: controller.signal, timeoutMs: 12e3, maxBytes: 262144, onEvent(event) {
980
981
  const e = event;
981
982
  if (e.type !== "system" || e.subtype !== "init") return;
982
983
  try {
@@ -1105,24 +1106,27 @@ import { execFile } from "child_process";
1105
1106
  import { promisify } from "util";
1106
1107
  var exec = promisify(execFile);
1107
1108
  var runCommand = (cli, args) => exec(cli, args, { timeout: 5e3, maxBuffer: 8192, windowsHide: true });
1108
- async function detectClis(run2 = runCommand) {
1109
+ async function detectClis(run3 = runCommand) {
1109
1110
  return Promise.all(["claude", "codex", "gemini"].map(async (id2) => {
1110
1111
  let version;
1111
1112
  try {
1112
- const { stdout } = await run2(id2, ["--version"]);
1113
+ const { stdout } = await run3(id2, ["--version"]);
1113
1114
  version = stdout.match(/\b\d+\.\d+\.\d+(?:[-+][\w.-]+)?\b/)?.[0] ?? null;
1114
1115
  } catch {
1115
1116
  return { id: id2, installed: false, version: null, authStatus: "unknown", cmsReady: false, reason: "not_installed" };
1116
1117
  }
1117
1118
  let authStatus = "unknown";
1119
+ let plan;
1118
1120
  if (id2 === "gemini") return { id: id2, installed: true, version, authStatus, cmsReady: false, reason: "isolation_not_verified" };
1119
1121
  try {
1120
- const { stdout, stderr } = await run2(id2, id2 === "claude" ? ["auth", "status", "--json"] : ["login", "status"]);
1122
+ const { stdout, stderr } = await run3(id2, id2 === "claude" ? ["auth", "status", "--json"] : ["login", "status"]);
1121
1123
  if (id2 === "claude") {
1122
1124
  const status = JSON.parse(stdout);
1123
1125
  if (status.loggedIn === false) authStatus = "logged_out";
1124
- else if (status.loggedIn === true && status.authMethod === "claude.ai" && status.apiProvider === "firstParty") authStatus = "subscription";
1125
- else if (status.loggedIn === true) authStatus = "api_key";
1126
+ else if (status.loggedIn === true && status.authMethod === "claude.ai" && status.apiProvider === "firstParty") {
1127
+ authStatus = "subscription";
1128
+ if (typeof status.subscriptionType === "string" && /^[a-z_]{1,32}$/.test(status.subscriptionType)) plan = status.subscriptionType;
1129
+ } else if (status.loggedIn === true) authStatus = "api_key";
1126
1130
  } else {
1127
1131
  const status = stdout + stderr;
1128
1132
  if (/not logged in/i.test(status)) authStatus = "logged_out";
@@ -1133,7 +1137,7 @@ async function detectClis(run2 = runCommand) {
1133
1137
  const diagnostic = error;
1134
1138
  if (/not logged in/i.test(`${diagnostic.stdout ?? ""}${diagnostic.stderr ?? ""}`)) authStatus = "logged_out";
1135
1139
  }
1136
- return { id: id2, installed: true, version, authStatus, cmsReady: false, reason: "isolation_not_verified" };
1140
+ return { id: id2, installed: true, version, authStatus, ...plan ? { plan } : {}, cmsReady: false, reason: "isolation_not_verified" };
1137
1141
  }));
1138
1142
  }
1139
1143
 
@@ -1143,7 +1147,7 @@ import { promisify as promisify2 } from "util";
1143
1147
  var run = promisify2(execFile2);
1144
1148
  var script = `on run argv
1145
1149
  activate
1146
- set promptText to "Connect this CMS to the FLiNT bridge on this computer?" & return & return & item 1 of argv & return & return & "This approval applies only to the current connection. Reconnecting requires approval again. Your CMS account and read permissions are verified separately."
1150
+ set promptText to "Connect this CMS to the FLiNT bridge on this computer?" & return & return & item 1 of argv & return & return & "This browser will be remembered for 30 days. You can disconnect it anytime in CMS settings. Your CMS account and read permissions are verified separately."
1147
1151
  set answer to display dialog promptText with title "FLiNT Connection Approval" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" giving up after 60
1148
1152
  if gave up of answer then return "denied"
1149
1153
  return button returned of answer
@@ -1252,7 +1256,6 @@ async function startBridge(options) {
1252
1256
  clear(peer);
1253
1257
  });
1254
1258
  socket.on("close", () => {
1255
- config.pairings = config.pairings.filter((p) => p.id !== peer.pairingId);
1256
1259
  clearTimeout(peer.deadline);
1257
1260
  clear(peer);
1258
1261
  peers.delete(peer);
@@ -1287,16 +1290,20 @@ async function startBridge(options) {
1287
1290
  try {
1288
1291
  if (request.type === "hello") {
1289
1292
  if (peer.pairingId) throw new BridgeError("invalid_request");
1290
- if (request.bridgeToken) throw new BridgeError("pair_required");
1293
+ const remembered = request.bridgeToken ? pairing.authenticate(request.bridgeToken, peer.origin) : void 0;
1294
+ if (remembered) {
1295
+ peer.pairingId = remembered.id;
1296
+ clearTimeout(peer.deadline);
1297
+ }
1291
1298
  reply({
1292
1299
  type: "hello.ok",
1293
- bridgeVersion: "1.0.9",
1300
+ bridgeVersion: BRIDGE_VERSION,
1294
1301
  hostId: config.hostId,
1295
1302
  streamId,
1296
1303
  connectionId: peer.id,
1297
- paired: false,
1304
+ paired: !!remembered,
1298
1305
  clis,
1299
- capabilities: { modelSelection: true, localApproval: !!options.approve, chat: !!options.execute, reason: options.execute ? "ready" : "preflight_required" }
1306
+ capabilities: { modelSelection: true, localApproval: !!options.approve, chat: !!options.execute, reason: options.execute ? "ready" : "preflight_required", autostart: !!options.autostart }
1300
1307
  });
1301
1308
  return;
1302
1309
  }
@@ -1329,6 +1336,8 @@ async function startBridge(options) {
1329
1336
  }
1330
1337
  peer.pairingId = exchanged.pairing.id;
1331
1338
  clearTimeout(peer.deadline);
1339
+ await options.persist().catch(() => {
1340
+ });
1332
1341
  reply({ type: "pair.ok", bridgeToken: exchanged.bridgeToken, expiresAt: exchanged.pairing.expiresAt, hostId: config.hostId });
1333
1342
  return;
1334
1343
  }
@@ -1529,7 +1538,101 @@ async function startBridge(options) {
1529
1538
  };
1530
1539
  }
1531
1540
 
1541
+ // src/autostart.ts
1542
+ import { execFile as execFile3 } from "child_process";
1543
+ import { access, mkdir as mkdir3, unlink as unlink3, writeFile as writeFile4 } from "fs/promises";
1544
+ import { homedir } from "os";
1545
+ import { dirname as dirname2, join as join4 } from "path";
1546
+ import { promisify as promisify3 } from "util";
1547
+ var run2 = promisify3(execFile3);
1548
+ var LAUNCH_LABEL = "dev.dicamo.flint-ai-bridge";
1549
+ var WINDOWS_RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
1550
+ var WINDOWS_VALUE = "FlintAiBridge";
1551
+ var plistPath = () => join4(homedir(), "Library", "LaunchAgents", `${LAUNCH_LABEL}.plist`);
1552
+ var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1553
+ var exists = (path) => access(path).then(() => true, () => false);
1554
+ async function npxPath() {
1555
+ const candidate = join4(dirname2(process.execPath), process.platform === "win32" ? "npx.cmd" : "npx");
1556
+ if (await exists(candidate)) return candidate;
1557
+ const { stdout } = await run2(process.platform === "win32" ? "where" : "which", ["npx"], { timeout: 5e3 });
1558
+ const found = stdout.split(/\r?\n/)[0]?.trim();
1559
+ if (!found) throw new Error("npx was not found. Install Node.js 22 or later.");
1560
+ return found;
1561
+ }
1562
+ function bridgeArgs(version, directory, command) {
1563
+ return ["-y", `@dicamo/flint-ai-bridge@${version}`, command, "--enable-chat", "--data-dir", directory];
1564
+ }
1565
+ function launchAgentPlist(npx, args, directory, path) {
1566
+ const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join("\n");
1567
+ const log = xml(join4(directory, "bridge.log"));
1568
+ return `<?xml version="1.0" encoding="UTF-8"?>
1569
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1570
+ <plist version="1.0">
1571
+ <dict>
1572
+ <key>Label</key><string>${LAUNCH_LABEL}</string>
1573
+ <key>ProgramArguments</key>
1574
+ <array>
1575
+ ${strings([npx, ...args])}
1576
+ </array>
1577
+ <key>EnvironmentVariables</key>
1578
+ <dict><key>PATH</key><string>${xml(path)}</string></dict>
1579
+ <key>RunAtLoad</key><true/>
1580
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
1581
+ <key>ThrottleInterval</key><integer>60</integer>
1582
+ <key>ProcessType</key><string>Interactive</string>
1583
+ <key>StandardOutPath</key><string>${log}</string>
1584
+ <key>StandardErrorPath</key><string>${log}</string>
1585
+ </dict>
1586
+ </plist>
1587
+ `;
1588
+ }
1589
+ async function installAutostart(directory, version) {
1590
+ if (process.platform === "darwin") {
1591
+ const npx = await npxPath();
1592
+ const path = plistPath();
1593
+ await mkdir3(dirname2(path), { recursive: true });
1594
+ await writeFile4(path, launchAgentPlist(npx, bridgeArgs(version, directory, "serve"), directory, process.env.PATH ?? "/usr/bin:/bin"), { mode: 420 });
1595
+ const domain = `gui/${process.getuid?.()}`;
1596
+ await run2("launchctl", ["bootout", `${domain}/${LAUNCH_LABEL}`]).catch(() => {
1597
+ });
1598
+ await run2("launchctl", ["bootstrap", domain, path]);
1599
+ return "launchd";
1600
+ }
1601
+ if (process.platform === "win32") {
1602
+ const npx = await npxPath();
1603
+ const command = [npx, ...bridgeArgs(version, directory, "start")].map((part) => `"${part.replace(/"/g, "")}"`).join(" ");
1604
+ await run2("reg", ["add", WINDOWS_RUN_KEY, "/v", WINDOWS_VALUE, "/t", "REG_SZ", "/d", command, "/f"], { windowsHide: true });
1605
+ return "windows";
1606
+ }
1607
+ return "unsupported";
1608
+ }
1609
+ async function removeAutostart() {
1610
+ if (process.platform === "darwin") {
1611
+ const path = plistPath();
1612
+ if (!await exists(path)) return false;
1613
+ await run2("launchctl", ["bootout", `gui/${process.getuid?.()}/${LAUNCH_LABEL}`]).catch(() => {
1614
+ });
1615
+ await unlink3(path);
1616
+ return true;
1617
+ }
1618
+ if (process.platform === "win32") {
1619
+ return run2("reg", ["delete", WINDOWS_RUN_KEY, "/v", WINDOWS_VALUE, "/f"], { windowsHide: true }).then(() => true, () => false);
1620
+ }
1621
+ return false;
1622
+ }
1623
+ async function autostartInstalled() {
1624
+ if (process.platform === "darwin") return exists(plistPath());
1625
+ if (process.platform === "win32") return run2("reg", ["query", WINDOWS_RUN_KEY, "/v", WINDOWS_VALUE], { windowsHide: true }).then(() => true, () => false);
1626
+ return false;
1627
+ }
1628
+
1532
1629
  // src/cli.ts
1630
+ function register(config, id2, server, origin2) {
1631
+ const existing = config.servers.find((s) => s.id === id2);
1632
+ const record = { id: id2, url: server, origins: [.../* @__PURE__ */ new Set([...existing?.url === server ? existing.origins : [], origin2])] };
1633
+ config.servers = [...config.servers.filter((s) => s.id !== record.id), record];
1634
+ parseConfig(config);
1635
+ }
1533
1636
  async function main() {
1534
1637
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
1535
1638
  "enable-chat": { type: "boolean" },
@@ -1540,7 +1643,9 @@ async function main() {
1540
1643
  help: { type: "boolean", short: "h" }
1541
1644
  } });
1542
1645
  if (values.help) {
1543
- console.log(`flint-ai-bridge [start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
1646
+ console.log(`flint-ai-bridge [setup|uninstall|start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
1647
+ setup --server <https-origin> --origin <cms-origin> [--id <server-id>]: register the CMS, start the bridge at login, and start it now.
1648
+ uninstall: stop starting at login and stop the bridge. Registered servers and remembered browsers are kept.
1544
1649
  configure --id <server-id> --server <https-origin> --origin <cms-origin>
1545
1650
  start --enable-chat: run in the background; terminal can be closed.
1546
1651
  status: show background status. stop: stop the bridge.
@@ -1548,10 +1653,10 @@ serve: loopback connection and pairing. --enable-chat opts into Claude CMS chat
1548
1653
  While serving, type "pair" to issue a new five-minute pairing code.`);
1549
1654
  return;
1550
1655
  }
1551
- const path = join4(resolve(values["data-dir"] ?? join4(homedir(), ".flint-ai-bridge")), "config.json");
1552
- const directory = resolve(values["data-dir"] ?? join4(homedir(), ".flint-ai-bridge"));
1553
- const lockPath = join4(directory, "instance.lock");
1554
- const revokePath = join4(directory, "revoke.request");
1656
+ const path = join5(resolve(values["data-dir"] ?? join5(homedir2(), ".flint-ai-bridge")), "config.json");
1657
+ const directory = resolve(values["data-dir"] ?? join5(homedir2(), ".flint-ai-bridge"));
1658
+ const lockPath = join5(directory, "instance.lock");
1659
+ const revokePath = join5(directory, "revoke.request");
1555
1660
  const running = await instanceLocked(lockPath);
1556
1661
  const command = positionals[0] ?? "serve";
1557
1662
  if (command === "status") {
@@ -1564,6 +1669,34 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1564
1669
  return;
1565
1670
  }
1566
1671
  const config = await readConfig(path);
1672
+ if (command === "setup") {
1673
+ if (!values.server || !values.origin) throw new Error("setup requires --server and --origin");
1674
+ if (running) await stopBackground(directory);
1675
+ register(config, values.id ?? "flint", values.server, values.origin);
1676
+ await mkdir4(directory, { recursive: true, mode: 448 });
1677
+ await saveConfig(path, config);
1678
+ const kind = await installAutostart(directory, BRIDGE_VERSION);
1679
+ let state = await backgroundStatus(directory);
1680
+ if (kind === "launchd") {
1681
+ for (let i = 0; i < 90 && !state.running; i++) {
1682
+ await new Promise((resolve2) => setTimeout(resolve2, 500));
1683
+ state = await backgroundStatus(directory);
1684
+ }
1685
+ if (!state.running) throw new Error(`Bridge did not start. Check ${join5(directory, "bridge.log")}`);
1686
+ } else state = await startBackground(directory, fileURLToPath2(import.meta.url), true);
1687
+ console.log(`FLiNT AI bridge is ready: ws://127.0.0.1:${state.port}
1688
+ Chat: ${state.chat ? "enabled" : `disabled${state.chatReason ? `: ${state.chatReason}` : ""}`}
1689
+ Start at login: ${kind === "unsupported" ? "not supported on this OS. Run start --enable-chat after each login." : "on"}
1690
+
1691
+ Go back to CMS and connect this computer in Settings > AI connection.`);
1692
+ return;
1693
+ }
1694
+ if (command === "uninstall") {
1695
+ const removed = await removeAutostart();
1696
+ const stopped = await stopBackground(directory);
1697
+ console.log(`${removed ? "Start at login removed." : "Start at login was not set up."} ${stopped ? "Bridge stopped." : "Bridge was not running."}`);
1698
+ return;
1699
+ }
1567
1700
  if (command === "start") {
1568
1701
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1569
1702
  const state = await startBackground(directory, fileURLToPath2(import.meta.url), !!values["enable-chat"]);
@@ -1575,24 +1708,21 @@ You can close this terminal. The bridge will keep running in the background.
1575
1708
  To stop the bridge, run:
1576
1709
  npx @dicamo/flint-ai-bridge stop${dataDirOption}
1577
1710
 
1578
- Log: ${join4(directory, "bridge.log")}`);
1711
+ Log: ${join5(directory, "bridge.log")}`);
1579
1712
  return;
1580
1713
  }
1581
1714
  switch (command) {
1582
1715
  case "configure": {
1583
1716
  if (running) throw new Error("Stop the running bridge before changing registered servers.");
1584
1717
  if (!values.id || !values.server || !values.origin) throw new Error("configure requires --id, --server and --origin");
1585
- const existing = config.servers.find((s) => s.id === values.id);
1586
- const record = { id: values.id, url: values.server, origins: [.../* @__PURE__ */ new Set([...existing?.url === values.server ? existing.origins : [], values.origin])] };
1587
- config.servers = [...config.servers.filter((s) => s.id !== record.id), record];
1588
- parseConfig(config);
1718
+ register(config, values.id, values.server, values.origin);
1589
1719
  await saveConfig(path, config);
1590
1720
  console.log("Server and CMS Origin registered. Restart a running bridge to load changes.");
1591
1721
  return;
1592
1722
  }
1593
1723
  case "unpair":
1594
1724
  if (running) {
1595
- await writeFile4(revokePath, String(Date.now()), { mode: 384 });
1725
+ await writeFile5(revokePath, String(Date.now()), { mode: 384 });
1596
1726
  console.log("Revocation requested. The running bridge processes it within one second.");
1597
1727
  } else {
1598
1728
  config.pairings = [];
@@ -1601,20 +1731,24 @@ Log: ${join4(directory, "bridge.log")}`);
1601
1731
  }
1602
1732
  return;
1603
1733
  case "serve":
1734
+ if (running) {
1735
+ console.log("Bridge is already running.");
1736
+ return;
1737
+ }
1604
1738
  break;
1605
1739
  default:
1606
1740
  throw new Error("Unknown command. Use --help.");
1607
1741
  }
1608
1742
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1609
- await mkdir3(directory, { recursive: true, mode: 448 });
1743
+ await mkdir4(directory, { recursive: true, mode: 448 });
1610
1744
  const release = await acquireInstance(lockPath);
1611
1745
  try {
1612
- config.pairings = [];
1746
+ config.pairings = config.pairings.filter((p) => p.expiresAt > Date.now());
1613
1747
  await saveConfig(path, config);
1614
1748
  let saving = Promise.resolve();
1615
1749
  const persist = () => {
1616
1750
  saving = saving.catch(() => {
1617
- }).then(() => saveConfig(path, { ...config, pairings: [] }));
1751
+ }).then(() => saveConfig(path, config));
1618
1752
  return saving;
1619
1753
  };
1620
1754
  let execute;
@@ -1630,7 +1764,7 @@ Log: ${join4(directory, "bridge.log")}`);
1630
1764
  console.warn(`CMS chat unavailable: ${chatReason} Bridge discovery remains available.`);
1631
1765
  }
1632
1766
  }
1633
- const bridge = await startBridge({ config, persist, execute, approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
1767
+ const bridge = await startBridge({ config, persist, execute, autostart: await autostartInstalled(), approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
1634
1768
  const issue = () => {
1635
1769
  try {
1636
1770
  console.log(`Pairing code: ${bridge.pairing.issue()} (5 minutes; type pair to reissue)`);
@@ -1650,11 +1784,11 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
1650
1784
  if (revoking) return;
1651
1785
  revoking = true;
1652
1786
  try {
1653
- await access(revokePath);
1787
+ await access2(revokePath);
1654
1788
  config.pairings = [];
1655
1789
  bridge.revoke();
1656
1790
  await persist();
1657
- await unlink3(revokePath);
1791
+ await unlink4(revokePath);
1658
1792
  console.log("All pairings revoked.");
1659
1793
  } catch (error) {
1660
1794
  if (error.code !== "ENOENT") console.error("Revocation persistence failed; retrying.");
@@ -24,6 +24,7 @@ type TurnUsage = z.infer<typeof turnUsageSchema>;
24
24
 
25
25
  /** Browser-safe protocol. Keep Node imports and runtime dependencies out of this file. */
26
26
  declare const PROTOCOL_VERSION: 1;
27
+ declare const BRIDGE_VERSION = "1.1.0";
27
28
  declare const PORTS: number[];
28
29
  declare const CLAUDE_MODELS: readonly ["default", "sonnet", "opus", "haiku"];
29
30
  type ClaudeModel = typeof CLAUDE_MODELS[number];
@@ -36,6 +37,8 @@ type CliInfo = {
36
37
  installed: boolean;
37
38
  version: string | null;
38
39
  authStatus: 'subscription' | 'api_key' | 'logged_out' | 'unknown';
40
+ /** Subscription tier reported by the CLI (e.g. pro, max, team), when it reports one. */
41
+ plan?: string;
39
42
  cmsReady: false;
40
43
  reason: 'isolation_not_verified' | 'not_installed';
41
44
  };
@@ -100,6 +103,7 @@ type ResponseBody = {
100
103
  modelSelection?: boolean;
101
104
  chat: boolean;
102
105
  reason: 'preflight_required' | 'ready';
106
+ autostart?: boolean;
103
107
  };
104
108
  } | {
105
109
  type: 'pair.ok';
@@ -150,4 +154,4 @@ type BridgeResponse = ResponseBody & {
150
154
  };
151
155
  type ErrorCode = 'invalid_request' | 'version_unsupported' | 'pair_required' | 'pair_invalid' | 'pair_denied' | 'approval_unavailable' | 'pair_locked' | 'pair_expired' | 'rate_limited' | 'server_not_allowed' | 'auth_invalid' | 'api_key_invalid' | 'auth_forbidden' | 'auth_context_mismatch' | 'scope_unavailable' | 'preflight_required' | 'internal_error' | 'turn_busy' | 'turn_failed';
152
156
 
153
- export { AI_CLAIM, type BridgeRequest, type BridgeResponse, CLAUDE_MODELS, type ClaudeModel, type CliInfo, type ErrorCode, type Identity, MAX_MESSAGE_BYTES, PORTS, PROTOCOL_VERSION, RESOURCES, type RequestBody, type Resource, type ResponseBody };
157
+ export { AI_CLAIM, BRIDGE_VERSION, type BridgeRequest, type BridgeResponse, CLAUDE_MODELS, type ClaudeModel, type CliInfo, type ErrorCode, type Identity, MAX_MESSAGE_BYTES, PORTS, PROTOCOL_VERSION, RESOURCES, type RequestBody, type Resource, type ResponseBody };
package/dist/protocol.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import {
2
2
  AI_CLAIM,
3
+ BRIDGE_VERSION,
3
4
  CLAUDE_MODELS,
4
5
  MAX_MESSAGE_BYTES,
5
6
  PORTS,
6
7
  PROTOCOL_VERSION,
7
8
  RESOURCES
8
- } from "./chunk-ZUPMLKCI.js";
9
+ } from "./chunk-SST2QOUV.js";
9
10
  export {
10
11
  AI_CLAIM,
12
+ BRIDGE_VERSION,
11
13
  CLAUDE_MODELS,
12
14
  MAX_MESSAGE_BYTES,
13
15
  PORTS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dicamo/flint-ai-bridge",
3
- "version": "1.0.9",
3
+ "version": "1.1.0",
4
4
  "description": "Local CLI connection bridge for FLiNT CMS",
5
5
  "type": "module",
6
6
  "bin": {