@dicamo/flint-ai-bridge 1.0.8 → 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";
@@ -14,12 +15,84 @@ import { fileURLToPath as fileURLToPath2 } from "url";
14
15
  import { createServer } from "http";
15
16
  import { randomBytes, timingSafeEqual } from "crypto";
16
17
  import { spawn } from "child_process";
17
- import { chmod, mkdir, open, readFile, rename, unlink } from "fs/promises";
18
+ import { chmod, mkdir, open as open2, readFile as readFile2, rename, unlink as unlink2 } from "fs/promises";
18
19
  import { join } from "path";
19
20
  import { z } from "zod";
21
+
22
+ // src/instance.ts
23
+ import { open, readFile, unlink } from "fs/promises";
24
+ import { randomUUID } from "crypto";
25
+ var LOCK_EXISTS = "Bridge instance lock exists. Stop the existing bridge; remove instance.lock only after confirming it is stopped.";
26
+ function isStale(raw) {
27
+ let pid;
28
+ try {
29
+ pid = JSON.parse(raw).pid;
30
+ } catch {
31
+ return false;
32
+ }
33
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
34
+ try {
35
+ process.kill(pid, 0);
36
+ return false;
37
+ } catch (error) {
38
+ return error.code === "ESRCH";
39
+ }
40
+ }
41
+ async function readLock(path) {
42
+ try {
43
+ return await readFile(path, "utf8");
44
+ } catch (error) {
45
+ if (error.code === "ENOENT") return void 0;
46
+ throw error;
47
+ }
48
+ }
49
+ async function instanceLocked(path) {
50
+ const raw = await readLock(path);
51
+ return raw !== void 0 && !isStale(raw);
52
+ }
53
+ async function removeStaleLock(path) {
54
+ const raw = await readLock(path);
55
+ if (raw === void 0) return true;
56
+ if (!isStale(raw)) return false;
57
+ if (await readLock(path) !== raw) return false;
58
+ try {
59
+ await unlink(path);
60
+ } catch (error) {
61
+ if (error.code !== "ENOENT") throw error;
62
+ }
63
+ console.log(`Removed stale instance lock (PID ${JSON.parse(raw).pid} is not running).`);
64
+ return true;
65
+ }
66
+ async function acquireInstance(path) {
67
+ const nonce = randomUUID();
68
+ for (let attempt = 0; ; attempt++) {
69
+ try {
70
+ const handle = await open(path, "wx", 384);
71
+ try {
72
+ await handle.writeFile(JSON.stringify({ pid: process.pid, nonce }));
73
+ } finally {
74
+ await handle.close();
75
+ }
76
+ break;
77
+ } catch (error) {
78
+ if (error.code !== "EEXIST") throw error;
79
+ if (attempt === 0 && await removeStaleLock(path)) continue;
80
+ throw new Error(LOCK_EXISTS);
81
+ }
82
+ }
83
+ return async () => {
84
+ try {
85
+ if (JSON.parse(await readFile(path, "utf8")).nonce === nonce) await unlink(path);
86
+ } catch (error) {
87
+ if (error.code !== "ENOENT") throw error;
88
+ }
89
+ };
90
+ }
91
+
92
+ // src/background.ts
20
93
  var runtimeSchema = z.object({ port: z.number().int().min(1).max(65535), token: z.string().regex(/^[a-f0-9]{64}$/), pid: z.number().int().positive() });
21
94
  async function control(directory, action) {
22
- const runtime = runtimeSchema.parse(JSON.parse(await readFile(join(directory, "runtime.json"), "utf8")));
95
+ const runtime = runtimeSchema.parse(JSON.parse(await readFile2(join(directory, "runtime.json"), "utf8")));
23
96
  const res = await fetch(`http://127.0.0.1:${runtime.port}/${action}`, { method: "POST", headers: { Authorization: `Bearer ${runtime.token}` }, redirect: "error", signal: AbortSignal.timeout(2e3) });
24
97
  if (!res.ok) throw new Error("Bridge control request failed");
25
98
  return z.object({ running: z.boolean(), port: z.number().optional(), chat: z.boolean().optional(), chatReason: z.string().max(512).optional(), pid: z.number().optional() }).parse(await res.json());
@@ -29,10 +102,9 @@ async function backgroundStatus(directory) {
29
102
  return await control(directory, "status");
30
103
  } catch {
31
104
  try {
32
- await readFile(join(directory, "instance.lock"));
33
- return { running: false, unavailable: true };
105
+ return await instanceLocked(join(directory, "instance.lock")) ? { running: false, unavailable: true } : { running: false };
34
106
  } catch {
35
- return { running: false };
107
+ return { running: false, unavailable: true };
36
108
  }
37
109
  }
38
110
  }
@@ -42,12 +114,7 @@ async function stopBackground(directory) {
42
114
  if (!state.running) return false;
43
115
  await control(directory, "stop");
44
116
  for (let i = 0; i < 100; i++) {
45
- try {
46
- await readFile(join(directory, "instance.lock"));
47
- } catch (error) {
48
- if (error.code === "ENOENT") return true;
49
- throw error;
50
- }
117
+ if (!await instanceLocked(join(directory, "instance.lock"))) return true;
51
118
  await new Promise((resolve2) => setTimeout(resolve2, 100));
52
119
  }
53
120
  throw new Error("Bridge is still shutting down. Check status before starting again.");
@@ -79,7 +146,7 @@ async function serveControl(directory, status, shutdown) {
79
146
  const temporary = join(directory, `runtime-${token}.tmp`);
80
147
  try {
81
148
  await mkdir(directory, { recursive: true, mode: 448 });
82
- const file = await open(temporary, "wx", 384);
149
+ const file = await open2(temporary, "wx", 384);
83
150
  try {
84
151
  await file.writeFile(JSON.stringify({ port: address.port, token, pid: process.pid }));
85
152
  } finally {
@@ -88,7 +155,7 @@ async function serveControl(directory, status, shutdown) {
88
155
  await rename(temporary, runtimePath);
89
156
  } catch (error) {
90
157
  server.close();
91
- await unlink(temporary).catch(() => {
158
+ await unlink2(temporary).catch(() => {
92
159
  });
93
160
  throw error;
94
161
  }
@@ -98,8 +165,8 @@ async function serveControl(directory, status, shutdown) {
98
165
  server.closeIdleConnections();
99
166
  });
100
167
  try {
101
- const current = JSON.parse(await readFile(runtimePath, "utf8"));
102
- if (current.token === token) await unlink(runtimePath);
168
+ const current = JSON.parse(await readFile2(runtimePath, "utf8"));
169
+ if (current.token === token) await unlink2(runtimePath);
103
170
  } catch (error) {
104
171
  if (error.code !== "ENOENT") throw error;
105
172
  }
@@ -112,7 +179,7 @@ async function startBackground(directory, entry, chat) {
112
179
  return previous;
113
180
  }
114
181
  await mkdir(directory, { recursive: true, mode: 448 });
115
- const log = await open(join(directory, "bridge.log"), "a", 384);
182
+ const log = await open2(join(directory, "bridge.log"), "a", 384);
116
183
  await chmod(join(directory, "bridge.log"), 384);
117
184
  try {
118
185
  const child = spawn(process.execPath, [entry, "serve", "--data-dir", directory, ...chat ? ["--enable-chat"] : []], { detached: true, stdio: ["ignore", log.fd, log.fd, "ipc"], windowsHide: true });
@@ -144,38 +211,11 @@ async function startBackground(directory, entry, chat) {
144
211
  }
145
212
 
146
213
  // src/cli.ts
147
- import { homedir } from "os";
148
- import { join as join4, resolve } from "path";
214
+ import { homedir as homedir2 } from "os";
215
+ import { join as join5, resolve } from "path";
149
216
  import { parseArgs } from "util";
150
217
  import { watchFile, unwatchFile } from "fs";
151
- import { access, writeFile as writeFile4, mkdir as mkdir3, unlink as unlink3 } from "fs/promises";
152
-
153
- // src/instance.ts
154
- import { open as open2, readFile as readFile2, unlink as unlink2 } from "fs/promises";
155
- import { randomUUID } from "crypto";
156
- async function acquireInstance(path) {
157
- const nonce = randomUUID();
158
- try {
159
- const handle = await open2(path, "wx", 384);
160
- try {
161
- await handle.writeFile(JSON.stringify({ pid: process.pid, nonce }));
162
- } finally {
163
- await handle.close();
164
- }
165
- } catch (error) {
166
- if (error.code === "EEXIST") throw new Error("Bridge instance lock exists. Stop the existing bridge; remove instance.lock only after confirming it is stopped.");
167
- throw error;
168
- }
169
- return async () => {
170
- try {
171
- if (JSON.parse(await readFile2(path, "utf8")).nonce === nonce) await unlink2(path);
172
- } catch (error) {
173
- if (error.code !== "ENOENT") throw error;
174
- }
175
- };
176
- }
177
-
178
- // src/cli.ts
218
+ import { access as access2, writeFile as writeFile5, mkdir as mkdir4, unlink as unlink4 } from "fs/promises";
179
219
  import { createInterface } from "readline";
180
220
 
181
221
  // src/config.ts
@@ -925,7 +965,7 @@ function assertClaudeIsolation(event, allowed) {
925
965
  const e = event;
926
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");
927
967
  }
928
- async function checkClaudeCapabilities(directory, cli, run2 = runJsonProcess) {
968
+ async function checkClaudeCapabilities(directory, cli, run3 = runJsonProcess) {
929
969
  if (!cli?.installed) return { ready: false, reason: "Claude Code is not installed or is not available on PATH." };
930
970
  if (cli.authStatus !== "subscription") return { ready: false, reason: "Sign in to Claude Code with a subscription account, then restart the bridge." };
931
971
  const version = cli.version ?? "unknown";
@@ -937,7 +977,7 @@ async function checkClaudeCapabilities(directory, cli, run2 = runJsonProcess) {
937
977
  const config = join2(dir, "mcp.json");
938
978
  await writeFile2(config, JSON.stringify({ mcpServers: {} }), { mode: 384 });
939
979
  try {
940
- 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) {
941
981
  const e = event;
942
982
  if (e.type !== "system" || e.subtype !== "init") return;
943
983
  try {
@@ -1066,24 +1106,27 @@ import { execFile } from "child_process";
1066
1106
  import { promisify } from "util";
1067
1107
  var exec = promisify(execFile);
1068
1108
  var runCommand = (cli, args) => exec(cli, args, { timeout: 5e3, maxBuffer: 8192, windowsHide: true });
1069
- async function detectClis(run2 = runCommand) {
1109
+ async function detectClis(run3 = runCommand) {
1070
1110
  return Promise.all(["claude", "codex", "gemini"].map(async (id2) => {
1071
1111
  let version;
1072
1112
  try {
1073
- const { stdout } = await run2(id2, ["--version"]);
1113
+ const { stdout } = await run3(id2, ["--version"]);
1074
1114
  version = stdout.match(/\b\d+\.\d+\.\d+(?:[-+][\w.-]+)?\b/)?.[0] ?? null;
1075
1115
  } catch {
1076
1116
  return { id: id2, installed: false, version: null, authStatus: "unknown", cmsReady: false, reason: "not_installed" };
1077
1117
  }
1078
1118
  let authStatus = "unknown";
1119
+ let plan;
1079
1120
  if (id2 === "gemini") return { id: id2, installed: true, version, authStatus, cmsReady: false, reason: "isolation_not_verified" };
1080
1121
  try {
1081
- 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"]);
1082
1123
  if (id2 === "claude") {
1083
1124
  const status = JSON.parse(stdout);
1084
1125
  if (status.loggedIn === false) authStatus = "logged_out";
1085
- else if (status.loggedIn === true && status.authMethod === "claude.ai" && status.apiProvider === "firstParty") authStatus = "subscription";
1086
- 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";
1087
1130
  } else {
1088
1131
  const status = stdout + stderr;
1089
1132
  if (/not logged in/i.test(status)) authStatus = "logged_out";
@@ -1094,7 +1137,7 @@ async function detectClis(run2 = runCommand) {
1094
1137
  const diagnostic = error;
1095
1138
  if (/not logged in/i.test(`${diagnostic.stdout ?? ""}${diagnostic.stderr ?? ""}`)) authStatus = "logged_out";
1096
1139
  }
1097
- 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" };
1098
1141
  }));
1099
1142
  }
1100
1143
 
@@ -1104,7 +1147,7 @@ import { promisify as promisify2 } from "util";
1104
1147
  var run = promisify2(execFile2);
1105
1148
  var script = `on run argv
1106
1149
  activate
1107
- 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."
1108
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
1109
1152
  if gave up of answer then return "denied"
1110
1153
  return button returned of answer
@@ -1213,7 +1256,6 @@ async function startBridge(options) {
1213
1256
  clear(peer);
1214
1257
  });
1215
1258
  socket.on("close", () => {
1216
- config.pairings = config.pairings.filter((p) => p.id !== peer.pairingId);
1217
1259
  clearTimeout(peer.deadline);
1218
1260
  clear(peer);
1219
1261
  peers.delete(peer);
@@ -1248,16 +1290,20 @@ async function startBridge(options) {
1248
1290
  try {
1249
1291
  if (request.type === "hello") {
1250
1292
  if (peer.pairingId) throw new BridgeError("invalid_request");
1251
- 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
+ }
1252
1298
  reply({
1253
1299
  type: "hello.ok",
1254
- bridgeVersion: "1.0.8",
1300
+ bridgeVersion: BRIDGE_VERSION,
1255
1301
  hostId: config.hostId,
1256
1302
  streamId,
1257
1303
  connectionId: peer.id,
1258
- paired: false,
1304
+ paired: !!remembered,
1259
1305
  clis,
1260
- 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 }
1261
1307
  });
1262
1308
  return;
1263
1309
  }
@@ -1290,6 +1336,8 @@ async function startBridge(options) {
1290
1336
  }
1291
1337
  peer.pairingId = exchanged.pairing.id;
1292
1338
  clearTimeout(peer.deadline);
1339
+ await options.persist().catch(() => {
1340
+ });
1293
1341
  reply({ type: "pair.ok", bridgeToken: exchanged.bridgeToken, expiresAt: exchanged.pairing.expiresAt, hostId: config.hostId });
1294
1342
  return;
1295
1343
  }
@@ -1490,7 +1538,101 @@ async function startBridge(options) {
1490
1538
  };
1491
1539
  }
1492
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
+
1493
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
+ }
1494
1636
  async function main() {
1495
1637
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
1496
1638
  "enable-chat": { type: "boolean" },
@@ -1501,7 +1643,9 @@ async function main() {
1501
1643
  help: { type: "boolean", short: "h" }
1502
1644
  } });
1503
1645
  if (values.help) {
1504
- 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.
1505
1649
  configure --id <server-id> --server <https-origin> --origin <cms-origin>
1506
1650
  start --enable-chat: run in the background; terminal can be closed.
1507
1651
  status: show background status. stop: stop the bridge.
@@ -1509,11 +1653,11 @@ serve: loopback connection and pairing. --enable-chat opts into Claude CMS chat
1509
1653
  While serving, type "pair" to issue a new five-minute pairing code.`);
1510
1654
  return;
1511
1655
  }
1512
- const path = join4(resolve(values["data-dir"] ?? join4(homedir(), ".flint-ai-bridge")), "config.json");
1513
- const directory = resolve(values["data-dir"] ?? join4(homedir(), ".flint-ai-bridge"));
1514
- const lockPath = join4(directory, "instance.lock");
1515
- const revokePath = join4(directory, "revoke.request");
1516
- const running = await access(lockPath).then(() => true, () => false);
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");
1660
+ const running = await instanceLocked(lockPath);
1517
1661
  const command = positionals[0] ?? "serve";
1518
1662
  if (command === "status") {
1519
1663
  const state = await backgroundStatus(directory);
@@ -1525,6 +1669,34 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1525
1669
  return;
1526
1670
  }
1527
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
+ }
1528
1700
  if (command === "start") {
1529
1701
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1530
1702
  const state = await startBackground(directory, fileURLToPath2(import.meta.url), !!values["enable-chat"]);
@@ -1536,24 +1708,21 @@ You can close this terminal. The bridge will keep running in the background.
1536
1708
  To stop the bridge, run:
1537
1709
  npx @dicamo/flint-ai-bridge stop${dataDirOption}
1538
1710
 
1539
- Log: ${join4(directory, "bridge.log")}`);
1711
+ Log: ${join5(directory, "bridge.log")}`);
1540
1712
  return;
1541
1713
  }
1542
1714
  switch (command) {
1543
1715
  case "configure": {
1544
1716
  if (running) throw new Error("Stop the running bridge before changing registered servers.");
1545
1717
  if (!values.id || !values.server || !values.origin) throw new Error("configure requires --id, --server and --origin");
1546
- const existing = config.servers.find((s) => s.id === values.id);
1547
- const record = { id: values.id, url: values.server, origins: [.../* @__PURE__ */ new Set([...existing?.url === values.server ? existing.origins : [], values.origin])] };
1548
- config.servers = [...config.servers.filter((s) => s.id !== record.id), record];
1549
- parseConfig(config);
1718
+ register(config, values.id, values.server, values.origin);
1550
1719
  await saveConfig(path, config);
1551
1720
  console.log("Server and CMS Origin registered. Restart a running bridge to load changes.");
1552
1721
  return;
1553
1722
  }
1554
1723
  case "unpair":
1555
1724
  if (running) {
1556
- await writeFile4(revokePath, String(Date.now()), { mode: 384 });
1725
+ await writeFile5(revokePath, String(Date.now()), { mode: 384 });
1557
1726
  console.log("Revocation requested. The running bridge processes it within one second.");
1558
1727
  } else {
1559
1728
  config.pairings = [];
@@ -1562,20 +1731,24 @@ Log: ${join4(directory, "bridge.log")}`);
1562
1731
  }
1563
1732
  return;
1564
1733
  case "serve":
1734
+ if (running) {
1735
+ console.log("Bridge is already running.");
1736
+ return;
1737
+ }
1565
1738
  break;
1566
1739
  default:
1567
1740
  throw new Error("Unknown command. Use --help.");
1568
1741
  }
1569
1742
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1570
- await mkdir3(directory, { recursive: true, mode: 448 });
1743
+ await mkdir4(directory, { recursive: true, mode: 448 });
1571
1744
  const release = await acquireInstance(lockPath);
1572
1745
  try {
1573
- config.pairings = [];
1746
+ config.pairings = config.pairings.filter((p) => p.expiresAt > Date.now());
1574
1747
  await saveConfig(path, config);
1575
1748
  let saving = Promise.resolve();
1576
1749
  const persist = () => {
1577
1750
  saving = saving.catch(() => {
1578
- }).then(() => saveConfig(path, { ...config, pairings: [] }));
1751
+ }).then(() => saveConfig(path, config));
1579
1752
  return saving;
1580
1753
  };
1581
1754
  let execute;
@@ -1591,7 +1764,7 @@ Log: ${join4(directory, "bridge.log")}`);
1591
1764
  console.warn(`CMS chat unavailable: ${chatReason} Bridge discovery remains available.`);
1592
1765
  }
1593
1766
  }
1594
- 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 });
1595
1768
  const issue = () => {
1596
1769
  try {
1597
1770
  console.log(`Pairing code: ${bridge.pairing.issue()} (5 minutes; type pair to reissue)`);
@@ -1611,11 +1784,11 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
1611
1784
  if (revoking) return;
1612
1785
  revoking = true;
1613
1786
  try {
1614
- await access(revokePath);
1787
+ await access2(revokePath);
1615
1788
  config.pairings = [];
1616
1789
  bridge.revoke();
1617
1790
  await persist();
1618
- await unlink3(revokePath);
1791
+ await unlink4(revokePath);
1619
1792
  console.log("All pairings revoked.");
1620
1793
  } catch (error) {
1621
1794
  if (error.code !== "ENOENT") console.error("Revocation persistence failed; retrying.");
@@ -14,9 +14,9 @@ declare const turnUsageSchema: z.ZodObject<{
14
14
  cache_write_tokens: z.ZodNullable<z.ZodNumber>;
15
15
  reasoning_tokens: z.ZodNullable<z.ZodNumber>;
16
16
  usage_status: z.ZodEnum<{
17
- unavailable: "unavailable";
18
17
  complete: "complete";
19
18
  partial: "partial";
19
+ unavailable: "unavailable";
20
20
  }>;
21
21
  source_scope: z.ZodLiteral<"turn">;
22
22
  }, z.core.$strict>;
@@ -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.8",
3
+ "version": "1.1.0",
4
4
  "description": "Local CLI connection bridge for FLiNT CMS",
5
5
  "type": "module",
6
6
  "bin": {