@dicamo/flint-ai-bridge 1.0.9 → 1.1.1

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
 
@@ -62,23 +59,24 @@ Ask about companies, stores, devices, media, scenes, users, login history, autom
62
59
 
63
60
  Every query respects your menu claims, company and store access scope, and server data policies. Owners have full read access. Data changes and remote commands are not supported. History and other child records require the parent resource ID first. Installed apps support bulk queries combining app name, package, and version with device company, store, and service/player version filters. This requires the administrator to apply the installed-app inventory SQL update. Counts refer to matching app records, not distinct devices. Statistics require the corresponding query functions on the server.
64
61
 
65
- Select the Claude model at the top of the chat: CLI default, Sonnet, Opus, or Haiku. Changes apply to the next message, and selection is disabled while a response is in progress. The actual model reported by the CLI is saved with usage data. Model availability depends on your Claude account.
62
+ Select the Claude model at the top of the chat or as the default in CMS settings. The list is the one Claude Code itself offers for your account (aliases such as Opus or Sonnet that follow the newest model, and pinned versions). The bridge reads it from Claude Code's `initialize` response at startup and every hour, without running a model, so new models appear when you update Claude Code. Changes apply to the next message, and selection is disabled while a response is in progress. The actual model reported by the CLI is saved with usage data. Model availability depends on your Claude account.
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,15 +1,19 @@
1
1
  // src/protocol.ts
2
2
  var PROTOCOL_VERSION = 1;
3
+ var BRIDGE_VERSION = "1.1.1";
3
4
  var PORTS = Array.from({ length: 10 }, (_, i) => 47820 + i);
4
5
  var CLAUDE_MODELS = ["default", "sonnet", "opus", "haiku"];
6
+ var CLAUDE_MODEL_PATTERN = /^(?:default|fable|opus|sonnet|haiku|claude-[a-z0-9]+(?:-[a-z0-9]+){0,4})$/;
5
7
  var AI_CLAIM = "enable:ai.assistant";
6
8
  var MAX_MESSAGE_BYTES = 256 * 1024;
7
9
  var RESOURCES = ["companies", "devices", "studio", "media", "dashboard", "users", "users.login_history", "automations", "holidays", "app_store", "alterra", "media_log"];
8
10
 
9
11
  export {
10
12
  PROTOCOL_VERSION,
13
+ BRIDGE_VERSION,
11
14
  PORTS,
12
15
  CLAUDE_MODELS,
16
+ CLAUDE_MODEL_PATTERN,
13
17
  AI_CLAIM,
14
18
  MAX_MESSAGE_BYTES,
15
19
  RESOURCES
package/dist/cli.js CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  AI_CLAIM,
4
- CLAUDE_MODELS,
4
+ BRIDGE_VERSION,
5
+ CLAUDE_MODEL_PATTERN,
5
6
  MAX_MESSAGE_BYTES,
6
7
  PORTS,
7
8
  RESOURCES
8
- } from "./chunk-ZUPMLKCI.js";
9
+ } from "./chunk-I26SVJRQ.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 join6, 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 writeFile6, 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 {
@@ -1003,7 +1004,7 @@ async function checkClaudeCapabilities(directory, cli, run2 = runJsonProcess) {
1003
1004
  var dbTurn = z8.object({ id: z8.string().uuid(), session_id: z8.string().uuid(), host_id: z8.string().uuid(), cli: z8.literal("claude"), status: z8.literal("running"), bridge_stream_id: z8.string().uuid(), prompt: z8.string().min(1).max(32e3), lease_expires_at: z8.string() });
1004
1005
  function createCmsExecutor(dataDir, cliVersion = "unknown") {
1005
1006
  return async (request) => {
1006
- const model = z8.enum(CLAUDE_MODELS).parse(request.model ?? "default");
1007
+ const model = z8.string().max(64).regex(CLAUDE_MODEL_PATTERN).parse(request.model ?? "default");
1007
1008
  const controller = new AbortController();
1008
1009
  const signal = AbortSignal.any([request.signal, controller.signal]);
1009
1010
  const active = () => {
@@ -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
@@ -1180,7 +1184,7 @@ var requestSchema = z9.discriminatedUnion("type", [
1180
1184
  accessibleResources: z9.array(z9.string().max(64)).max(32)
1181
1185
  }).strict(),
1182
1186
  z9.object({ ...envelope, type: z9.literal("auth.clear"), authContextId: z9.string().uuid() }).strict(),
1183
- z9.object({ ...turnFields, type: z9.literal("turn.start"), sessionId: z9.string().uuid(), model: z9.enum(CLAUDE_MODELS).optional() }).strict(),
1187
+ z9.object({ ...turnFields, type: z9.literal("turn.start"), sessionId: z9.string().uuid(), model: z9.string().max(64).regex(CLAUDE_MODEL_PATTERN).optional() }).strict(),
1184
1188
  z9.object({ ...turnFields, type: z9.literal("turn.cancel") }).strict(),
1185
1189
  z9.object({ ...turnFields, type: z9.literal("turn.ack") }).strict(),
1186
1190
  ...["status", "unpair"].map((type) => z9.object({ ...envelope, type: z9.literal(type) }).strict())
@@ -1196,6 +1200,19 @@ async function startBridge(options) {
1196
1200
  const detect = options.detect ?? detectClis;
1197
1201
  let clis = await detect();
1198
1202
  let lastDetection = Date.now();
1203
+ let models;
1204
+ let modelsAt = 0;
1205
+ let loadingModels;
1206
+ const refreshModels = () => {
1207
+ if (!options.listModels || loadingModels || Date.now() - modelsAt < 36e5) return loadingModels;
1208
+ loadingModels = options.listModels().then((list) => list, () => void 0).then((list) => {
1209
+ if (list) models = list;
1210
+ modelsAt = list ? Date.now() : Date.now() - 33e5;
1211
+ loadingModels = void 0;
1212
+ });
1213
+ return loadingModels;
1214
+ };
1215
+ await refreshModels();
1199
1216
  const http = createServer3((_req, res) => {
1200
1217
  res.writeHead(404, { "Cache-Control": "no-store" });
1201
1218
  res.end();
@@ -1252,7 +1269,6 @@ async function startBridge(options) {
1252
1269
  clear(peer);
1253
1270
  });
1254
1271
  socket.on("close", () => {
1255
- config.pairings = config.pairings.filter((p) => p.id !== peer.pairingId);
1256
1272
  clearTimeout(peer.deadline);
1257
1273
  clear(peer);
1258
1274
  peers.delete(peer);
@@ -1287,16 +1303,22 @@ async function startBridge(options) {
1287
1303
  try {
1288
1304
  if (request.type === "hello") {
1289
1305
  if (peer.pairingId) throw new BridgeError("invalid_request");
1290
- if (request.bridgeToken) throw new BridgeError("pair_required");
1306
+ const remembered = request.bridgeToken ? pairing.authenticate(request.bridgeToken, peer.origin) : void 0;
1307
+ if (remembered) {
1308
+ peer.pairingId = remembered.id;
1309
+ clearTimeout(peer.deadline);
1310
+ }
1311
+ void refreshModels();
1291
1312
  reply({
1292
1313
  type: "hello.ok",
1293
- bridgeVersion: "1.0.9",
1314
+ bridgeVersion: BRIDGE_VERSION,
1294
1315
  hostId: config.hostId,
1295
1316
  streamId,
1296
1317
  connectionId: peer.id,
1297
- paired: false,
1318
+ paired: !!remembered,
1298
1319
  clis,
1299
- capabilities: { modelSelection: true, localApproval: !!options.approve, chat: !!options.execute, reason: options.execute ? "ready" : "preflight_required" }
1320
+ ...models ? { models } : {},
1321
+ capabilities: { modelSelection: true, localApproval: !!options.approve, chat: !!options.execute, reason: options.execute ? "ready" : "preflight_required", autostart: !!options.autostart, anyModel: true }
1300
1322
  });
1301
1323
  return;
1302
1324
  }
@@ -1329,6 +1351,8 @@ async function startBridge(options) {
1329
1351
  }
1330
1352
  peer.pairingId = exchanged.pairing.id;
1331
1353
  clearTimeout(peer.deadline);
1354
+ await options.persist().catch(() => {
1355
+ });
1332
1356
  reply({ type: "pair.ok", bridgeToken: exchanged.bridgeToken, expiresAt: exchanged.pairing.expiresAt, hostId: config.hostId });
1333
1357
  return;
1334
1358
  }
@@ -1529,7 +1553,141 @@ async function startBridge(options) {
1529
1553
  };
1530
1554
  }
1531
1555
 
1556
+ // src/claudeModels.ts
1557
+ import { mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile4 } from "fs/promises";
1558
+ import { join as join4 } from "path";
1559
+ import { z as z10 } from "zod";
1560
+ var listSchema = z10.array(z10.object({ value: z10.string(), displayName: z10.string(), description: z10.string().optional() }).passthrough()).max(64);
1561
+ function parseModels(raw) {
1562
+ const list = listSchema.safeParse(raw);
1563
+ if (!list.success) return [];
1564
+ return list.data.filter((m) => CLAUDE_MODEL_PATTERN.test(m.value)).slice(0, 40).map((m) => ({
1565
+ value: m.value,
1566
+ displayName: m.displayName.slice(0, 60),
1567
+ ...m.description ? { description: m.description.slice(0, 120) } : {}
1568
+ }));
1569
+ }
1570
+ async function listClaudeModels(directory, run3 = runJsonProcess) {
1571
+ const dir = await mkdtemp3(join4(directory, "claude-models-"));
1572
+ let models;
1573
+ try {
1574
+ const config = join4(dir, "mcp.json");
1575
+ await writeFile4(config, JSON.stringify({ mcpServers: {} }), { mode: 384 });
1576
+ await run3({
1577
+ command: "claude",
1578
+ args: [...claudeIsolationArgs(config), "--input-format", "stream-json"],
1579
+ cwd: dir,
1580
+ env: claudeEnvironment(),
1581
+ input: JSON.stringify({ type: "control_request", request_id: "models", request: { subtype: "initialize" } }) + "\n",
1582
+ timeoutMs: 15e3,
1583
+ maxBytes: 1024 * 1024,
1584
+ onEvent(event) {
1585
+ const e = event;
1586
+ if (e.type === "control_response" && e.response?.request_id === "models") models = parseModels(e.response.response?.models);
1587
+ }
1588
+ }).catch(() => {
1589
+ });
1590
+ return models?.length ? models : void 0;
1591
+ } finally {
1592
+ await rm3(dir, { recursive: true, force: true });
1593
+ }
1594
+ }
1595
+
1596
+ // src/autostart.ts
1597
+ import { execFile as execFile3 } from "child_process";
1598
+ import { access, mkdir as mkdir3, unlink as unlink3, writeFile as writeFile5 } from "fs/promises";
1599
+ import { homedir } from "os";
1600
+ import { dirname as dirname2, join as join5 } from "path";
1601
+ import { promisify as promisify3 } from "util";
1602
+ var run2 = promisify3(execFile3);
1603
+ var LAUNCH_LABEL = "dev.dicamo.flint-ai-bridge";
1604
+ var WINDOWS_RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
1605
+ var WINDOWS_VALUE = "FlintAiBridge";
1606
+ var plistPath = () => join5(homedir(), "Library", "LaunchAgents", `${LAUNCH_LABEL}.plist`);
1607
+ var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1608
+ var exists = (path) => access(path).then(() => true, () => false);
1609
+ async function npxPath() {
1610
+ const candidate = join5(dirname2(process.execPath), process.platform === "win32" ? "npx.cmd" : "npx");
1611
+ if (await exists(candidate)) return candidate;
1612
+ const { stdout } = await run2(process.platform === "win32" ? "where" : "which", ["npx"], { timeout: 5e3 });
1613
+ const found = stdout.split(/\r?\n/)[0]?.trim();
1614
+ if (!found) throw new Error("npx was not found. Install Node.js 22 or later.");
1615
+ return found;
1616
+ }
1617
+ function bridgeArgs(version, directory, command) {
1618
+ return ["-y", `@dicamo/flint-ai-bridge@${version}`, command, "--enable-chat", "--data-dir", directory];
1619
+ }
1620
+ function launchAgentPlist(npx, args, directory, path) {
1621
+ const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join("\n");
1622
+ const log = xml(join5(directory, "bridge.log"));
1623
+ return `<?xml version="1.0" encoding="UTF-8"?>
1624
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1625
+ <plist version="1.0">
1626
+ <dict>
1627
+ <key>Label</key><string>${LAUNCH_LABEL}</string>
1628
+ <key>ProgramArguments</key>
1629
+ <array>
1630
+ ${strings([npx, ...args])}
1631
+ </array>
1632
+ <key>EnvironmentVariables</key>
1633
+ <dict><key>PATH</key><string>${xml(path)}</string></dict>
1634
+ <key>RunAtLoad</key><true/>
1635
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
1636
+ <key>ThrottleInterval</key><integer>60</integer>
1637
+ <key>ProcessType</key><string>Interactive</string>
1638
+ <key>StandardOutPath</key><string>${log}</string>
1639
+ <key>StandardErrorPath</key><string>${log}</string>
1640
+ </dict>
1641
+ </plist>
1642
+ `;
1643
+ }
1644
+ async function installAutostart(directory, version) {
1645
+ if (process.platform === "darwin") {
1646
+ const npx = await npxPath();
1647
+ const path = plistPath();
1648
+ await mkdir3(dirname2(path), { recursive: true });
1649
+ await writeFile5(path, launchAgentPlist(npx, bridgeArgs(version, directory, "serve"), directory, process.env.PATH ?? "/usr/bin:/bin"), { mode: 420 });
1650
+ const domain = `gui/${process.getuid?.()}`;
1651
+ await run2("launchctl", ["bootout", `${domain}/${LAUNCH_LABEL}`]).catch(() => {
1652
+ });
1653
+ await run2("launchctl", ["bootstrap", domain, path]);
1654
+ return "launchd";
1655
+ }
1656
+ if (process.platform === "win32") {
1657
+ const npx = await npxPath();
1658
+ const command = [npx, ...bridgeArgs(version, directory, "start")].map((part) => `"${part.replace(/"/g, "")}"`).join(" ");
1659
+ await run2("reg", ["add", WINDOWS_RUN_KEY, "/v", WINDOWS_VALUE, "/t", "REG_SZ", "/d", command, "/f"], { windowsHide: true });
1660
+ return "windows";
1661
+ }
1662
+ return "unsupported";
1663
+ }
1664
+ async function removeAutostart() {
1665
+ if (process.platform === "darwin") {
1666
+ const path = plistPath();
1667
+ if (!await exists(path)) return false;
1668
+ await run2("launchctl", ["bootout", `gui/${process.getuid?.()}/${LAUNCH_LABEL}`]).catch(() => {
1669
+ });
1670
+ await unlink3(path);
1671
+ return true;
1672
+ }
1673
+ if (process.platform === "win32") {
1674
+ return run2("reg", ["delete", WINDOWS_RUN_KEY, "/v", WINDOWS_VALUE, "/f"], { windowsHide: true }).then(() => true, () => false);
1675
+ }
1676
+ return false;
1677
+ }
1678
+ async function autostartInstalled() {
1679
+ if (process.platform === "darwin") return exists(plistPath());
1680
+ if (process.platform === "win32") return run2("reg", ["query", WINDOWS_RUN_KEY, "/v", WINDOWS_VALUE], { windowsHide: true }).then(() => true, () => false);
1681
+ return false;
1682
+ }
1683
+
1532
1684
  // src/cli.ts
1685
+ function register(config, id2, server, origin2) {
1686
+ const existing = config.servers.find((s) => s.id === id2);
1687
+ const record = { id: id2, url: server, origins: [.../* @__PURE__ */ new Set([...existing?.url === server ? existing.origins : [], origin2])] };
1688
+ config.servers = [...config.servers.filter((s) => s.id !== record.id), record];
1689
+ parseConfig(config);
1690
+ }
1533
1691
  async function main() {
1534
1692
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
1535
1693
  "enable-chat": { type: "boolean" },
@@ -1540,7 +1698,9 @@ async function main() {
1540
1698
  help: { type: "boolean", short: "h" }
1541
1699
  } });
1542
1700
  if (values.help) {
1543
- console.log(`flint-ai-bridge [start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
1701
+ console.log(`flint-ai-bridge [setup|uninstall|start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
1702
+ setup --server <https-origin> --origin <cms-origin> [--id <server-id>]: register the CMS, start the bridge at login, and start it now.
1703
+ uninstall: stop starting at login and stop the bridge. Registered servers and remembered browsers are kept.
1544
1704
  configure --id <server-id> --server <https-origin> --origin <cms-origin>
1545
1705
  start --enable-chat: run in the background; terminal can be closed.
1546
1706
  status: show background status. stop: stop the bridge.
@@ -1548,10 +1708,10 @@ serve: loopback connection and pairing. --enable-chat opts into Claude CMS chat
1548
1708
  While serving, type "pair" to issue a new five-minute pairing code.`);
1549
1709
  return;
1550
1710
  }
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");
1711
+ const path = join6(resolve(values["data-dir"] ?? join6(homedir2(), ".flint-ai-bridge")), "config.json");
1712
+ const directory = resolve(values["data-dir"] ?? join6(homedir2(), ".flint-ai-bridge"));
1713
+ const lockPath = join6(directory, "instance.lock");
1714
+ const revokePath = join6(directory, "revoke.request");
1555
1715
  const running = await instanceLocked(lockPath);
1556
1716
  const command = positionals[0] ?? "serve";
1557
1717
  if (command === "status") {
@@ -1564,6 +1724,34 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1564
1724
  return;
1565
1725
  }
1566
1726
  const config = await readConfig(path);
1727
+ if (command === "setup") {
1728
+ if (!values.server || !values.origin) throw new Error("setup requires --server and --origin");
1729
+ if (running) await stopBackground(directory);
1730
+ register(config, values.id ?? "flint", values.server, values.origin);
1731
+ await mkdir4(directory, { recursive: true, mode: 448 });
1732
+ await saveConfig(path, config);
1733
+ const kind = await installAutostart(directory, BRIDGE_VERSION);
1734
+ let state = await backgroundStatus(directory);
1735
+ if (kind === "launchd") {
1736
+ for (let i = 0; i < 90 && !state.running; i++) {
1737
+ await new Promise((resolve2) => setTimeout(resolve2, 500));
1738
+ state = await backgroundStatus(directory);
1739
+ }
1740
+ if (!state.running) throw new Error(`Bridge did not start. Check ${join6(directory, "bridge.log")}`);
1741
+ } else state = await startBackground(directory, fileURLToPath2(import.meta.url), true);
1742
+ console.log(`FLiNT AI bridge is ready: ws://127.0.0.1:${state.port}
1743
+ Chat: ${state.chat ? "enabled" : `disabled${state.chatReason ? `: ${state.chatReason}` : ""}`}
1744
+ Start at login: ${kind === "unsupported" ? "not supported on this OS. Run start --enable-chat after each login." : "on"}
1745
+
1746
+ Go back to CMS and connect this computer in Settings > AI connection.`);
1747
+ return;
1748
+ }
1749
+ if (command === "uninstall") {
1750
+ const removed = await removeAutostart();
1751
+ const stopped = await stopBackground(directory);
1752
+ console.log(`${removed ? "Start at login removed." : "Start at login was not set up."} ${stopped ? "Bridge stopped." : "Bridge was not running."}`);
1753
+ return;
1754
+ }
1567
1755
  if (command === "start") {
1568
1756
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1569
1757
  const state = await startBackground(directory, fileURLToPath2(import.meta.url), !!values["enable-chat"]);
@@ -1575,24 +1763,21 @@ You can close this terminal. The bridge will keep running in the background.
1575
1763
  To stop the bridge, run:
1576
1764
  npx @dicamo/flint-ai-bridge stop${dataDirOption}
1577
1765
 
1578
- Log: ${join4(directory, "bridge.log")}`);
1766
+ Log: ${join6(directory, "bridge.log")}`);
1579
1767
  return;
1580
1768
  }
1581
1769
  switch (command) {
1582
1770
  case "configure": {
1583
1771
  if (running) throw new Error("Stop the running bridge before changing registered servers.");
1584
1772
  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);
1773
+ register(config, values.id, values.server, values.origin);
1589
1774
  await saveConfig(path, config);
1590
1775
  console.log("Server and CMS Origin registered. Restart a running bridge to load changes.");
1591
1776
  return;
1592
1777
  }
1593
1778
  case "unpair":
1594
1779
  if (running) {
1595
- await writeFile4(revokePath, String(Date.now()), { mode: 384 });
1780
+ await writeFile6(revokePath, String(Date.now()), { mode: 384 });
1596
1781
  console.log("Revocation requested. The running bridge processes it within one second.");
1597
1782
  } else {
1598
1783
  config.pairings = [];
@@ -1601,20 +1786,24 @@ Log: ${join4(directory, "bridge.log")}`);
1601
1786
  }
1602
1787
  return;
1603
1788
  case "serve":
1789
+ if (running) {
1790
+ console.log("Bridge is already running.");
1791
+ return;
1792
+ }
1604
1793
  break;
1605
1794
  default:
1606
1795
  throw new Error("Unknown command. Use --help.");
1607
1796
  }
1608
1797
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1609
- await mkdir3(directory, { recursive: true, mode: 448 });
1798
+ await mkdir4(directory, { recursive: true, mode: 448 });
1610
1799
  const release = await acquireInstance(lockPath);
1611
1800
  try {
1612
- config.pairings = [];
1801
+ config.pairings = config.pairings.filter((p) => p.expiresAt > Date.now());
1613
1802
  await saveConfig(path, config);
1614
1803
  let saving = Promise.resolve();
1615
1804
  const persist = () => {
1616
1805
  saving = saving.catch(() => {
1617
- }).then(() => saveConfig(path, { ...config, pairings: [] }));
1806
+ }).then(() => saveConfig(path, config));
1618
1807
  return saving;
1619
1808
  };
1620
1809
  let execute;
@@ -1630,7 +1819,7 @@ Log: ${join4(directory, "bridge.log")}`);
1630
1819
  console.warn(`CMS chat unavailable: ${chatReason} Bridge discovery remains available.`);
1631
1820
  }
1632
1821
  }
1633
- const bridge = await startBridge({ config, persist, execute, approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
1822
+ const bridge = await startBridge({ config, persist, execute, autostart: await autostartInstalled(), listModels: execute ? () => listClaudeModels(directory) : void 0, approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
1634
1823
  const issue = () => {
1635
1824
  try {
1636
1825
  console.log(`Pairing code: ${bridge.pairing.issue()} (5 minutes; type pair to reissue)`);
@@ -1650,11 +1839,11 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
1650
1839
  if (revoking) return;
1651
1840
  revoking = true;
1652
1841
  try {
1653
- await access(revokePath);
1842
+ await access2(revokePath);
1654
1843
  config.pairings = [];
1655
1844
  bridge.revoke();
1656
1845
  await persist();
1657
- await unlink3(revokePath);
1846
+ await unlink4(revokePath);
1658
1847
  console.log("All pairings revoked.");
1659
1848
  } catch (error) {
1660
1849
  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";
17
18
  complete: "complete";
18
19
  partial: "partial";
19
- unavailable: "unavailable";
20
20
  }>;
21
21
  source_scope: z.ZodLiteral<"turn">;
22
22
  }, z.core.$strict>;
@@ -24,9 +24,19 @@ 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.1";
27
28
  declare const PORTS: number[];
29
+ /** The only models bridges up to 1.1.0 accept. Newer bridges report capabilities.anyModel. */
28
30
  declare const CLAUDE_MODELS: readonly ["default", "sonnet", "opus", "haiku"];
29
- type ClaudeModel = typeof CLAUDE_MODELS[number];
31
+ /** An alias or a full Claude model name for `claude --model`. Never starts with "-", so it cannot become a CLI flag. */
32
+ declare const CLAUDE_MODEL_PATTERN: RegExp;
33
+ type ClaudeModel = string;
34
+ /** One model the user's Claude Code offers (from its `initialize` response). value goes to `--model`. */
35
+ type ModelInfo = {
36
+ value: string;
37
+ displayName: string;
38
+ description?: string;
39
+ };
30
40
  declare const AI_CLAIM = "enable:ai.assistant";
31
41
  declare const MAX_MESSAGE_BYTES: number;
32
42
  declare const RESOURCES: readonly ["companies", "devices", "studio", "media", "dashboard", "users", "users.login_history", "automations", "holidays", "app_store", "alterra", "media_log"];
@@ -36,6 +46,8 @@ type CliInfo = {
36
46
  installed: boolean;
37
47
  version: string | null;
38
48
  authStatus: 'subscription' | 'api_key' | 'logged_out' | 'unknown';
49
+ /** Subscription tier reported by the CLI (e.g. pro, max, team), when it reports one. */
50
+ plan?: string;
39
51
  cmsReady: false;
40
52
  reason: 'isolation_not_verified' | 'not_installed';
41
53
  };
@@ -95,11 +107,14 @@ type ResponseBody = {
95
107
  connectionId: string;
96
108
  paired: boolean;
97
109
  clis: CliInfo[];
110
+ models?: ModelInfo[];
98
111
  capabilities: {
99
112
  localApproval?: boolean;
100
113
  modelSelection?: boolean;
101
114
  chat: boolean;
102
115
  reason: 'preflight_required' | 'ready';
116
+ autostart?: boolean;
117
+ anyModel?: boolean;
103
118
  };
104
119
  } | {
105
120
  type: 'pair.ok';
@@ -150,4 +165,4 @@ type BridgeResponse = ResponseBody & {
150
165
  };
151
166
  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
167
 
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 };
168
+ export { AI_CLAIM, BRIDGE_VERSION, type BridgeRequest, type BridgeResponse, CLAUDE_MODELS, CLAUDE_MODEL_PATTERN, type ClaudeModel, type CliInfo, type ErrorCode, type Identity, MAX_MESSAGE_BYTES, type ModelInfo, PORTS, PROTOCOL_VERSION, RESOURCES, type RequestBody, type Resource, type ResponseBody };
package/dist/protocol.js CHANGED
@@ -1,14 +1,18 @@
1
1
  import {
2
2
  AI_CLAIM,
3
+ BRIDGE_VERSION,
3
4
  CLAUDE_MODELS,
5
+ CLAUDE_MODEL_PATTERN,
4
6
  MAX_MESSAGE_BYTES,
5
7
  PORTS,
6
8
  PROTOCOL_VERSION,
7
9
  RESOURCES
8
- } from "./chunk-ZUPMLKCI.js";
10
+ } from "./chunk-I26SVJRQ.js";
9
11
  export {
10
12
  AI_CLAIM,
13
+ BRIDGE_VERSION,
11
14
  CLAUDE_MODELS,
15
+ CLAUDE_MODEL_PATTERN,
12
16
  MAX_MESSAGE_BYTES,
13
17
  PORTS,
14
18
  PROTOCOL_VERSION,
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.1",
4
4
  "description": "Local CLI connection bridge for FLiNT CMS",
5
5
  "type": "module",
6
6
  "bin": {