@dicamo/flint-ai-bridge 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -15
- package/dist/{chunk-I26SVJRQ.js → chunk-LWN22TEE.js} +1 -1
- package/dist/cli.js +146 -103
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,24 +17,21 @@ Currently verified on macOS. Windows and Linux support is in progress.
|
|
|
17
17
|
|
|
18
18
|
### 1. Set up the bridge (once)
|
|
19
19
|
|
|
20
|
-
Copy the command from CMS **Settings > AI connection**, or
|
|
20
|
+
Copy the command from CMS **Settings > AI connection**, or put the CMS address you open in your browser:
|
|
21
21
|
|
|
22
22
|
```sh
|
|
23
|
-
npx @dicamo/flint-ai-bridge@latest setup
|
|
24
|
-
--server https://api.example.com \
|
|
25
|
-
--origin https://cms.example.com
|
|
23
|
+
npx @dicamo/flint-ai-bridge@latest setup cms.example.com
|
|
26
24
|
```
|
|
27
25
|
|
|
28
26
|
`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
27
|
|
|
30
28
|
| Option | Value |
|
|
31
29
|
| --- | --- |
|
|
32
|
-
|
|
|
33
|
-
| `--
|
|
30
|
+
| `<cms-address>` | The CMS address you open in your browser. `https://` is assumed; page paths are ignored |
|
|
31
|
+
| `--server` | Optional. The server URL. By default it is read from the CMS (`/flint-bridge.json`) |
|
|
32
|
+
| `--origin` | Optional. Same as `<cms-address>`, for older commands |
|
|
34
33
|
| `--id` | Optional connection name (lowercase letters, numbers, hyphens). Default: `flint` |
|
|
35
34
|
|
|
36
|
-
Include `https://`, without page paths such as `/device` or a trailing `/`.
|
|
37
|
-
|
|
38
35
|
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
36
|
|
|
40
37
|
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.
|
|
@@ -42,14 +39,18 @@ When chat is enabled, startup checks Claude Code in a temporary directory and st
|
|
|
42
39
|
### 2. Allow this browser
|
|
43
40
|
|
|
44
41
|
1. In CMS, open **Settings > AI connection** and press **Search again**.
|
|
45
|
-
2.
|
|
46
|
-
3. Allow
|
|
42
|
+
2. Chrome and Edge ask to let the site access devices on your local network. Select **Allow**: CMS reaches the bridge on this computer (`127.0.0.1`) only.
|
|
43
|
+
3. Choose **Connect this PC**. Check the CMS URL in the desktop dialog, then select **Allow**. If the dialog is unavailable, open the code option, run the command below, and enter the six-digit code it prints:
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
npx @dicamo/flint-ai-bridge@latest code
|
|
47
|
+
```
|
|
47
48
|
|
|
48
49
|
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
50
|
|
|
50
51
|
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.
|
|
51
52
|
|
|
52
|
-
Pairing codes expire after five minutes.
|
|
53
|
+
Pairing codes expire after five minutes. Run `code` again for a new one (in foreground mode, you can also enter `pair` in the bridge terminal).
|
|
53
54
|
|
|
54
55
|
## Ask about CMS data
|
|
55
56
|
|
|
@@ -73,7 +74,7 @@ npx @dicamo/flint-ai-bridge@latest stop
|
|
|
73
74
|
npx @dicamo/flint-ai-bridge@latest uninstall
|
|
74
75
|
```
|
|
75
76
|
|
|
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
|
|
77
|
+
`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 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.
|
|
77
78
|
|
|
78
79
|
Use **Disconnect** in CMS settings to forget the current browser.
|
|
79
80
|
To revoke all remembered browsers on this computer, run:
|
|
@@ -85,9 +86,10 @@ npx @dicamo/flint-ai-bridge@latest unpair
|
|
|
85
86
|
## Troubleshooting
|
|
86
87
|
|
|
87
88
|
- **The Flint AI button is missing:** Ask your CMS administrator to check your AI assistant permission.
|
|
88
|
-
- **CMS cannot find the bridge:** Run `status`. If it is stopped, run `setup` again. Also check that your browser allows local network access
|
|
89
|
-
- **The pairing code expired:**
|
|
90
|
-
- **The URL is not registered:** Run `setup` again with the right
|
|
89
|
+
- **CMS cannot find the bridge:** Run `status`. If it is stopped, run `setup` again. Also check that your browser allows local network access: click the icon left of the address bar, open **Site settings**, and set **Local network access** to **Allow**.
|
|
90
|
+
- **The pairing code expired:** Run `code` again. If repeated incorrect attempts have locked pairing, wait 60 seconds before generating another code.
|
|
91
|
+
- **The URL is not registered:** Run `setup` again with the right CMS address.
|
|
92
|
+
- **Could not read /flint-bridge.json:** The CMS is older than this bridge. Pass the server too: `setup cms.example.com --server https://api.example.com`.
|
|
91
93
|
- **Account or permission verification failed:** Sign in to CMS again. Contact your administrator if the problem persists.
|
|
92
94
|
|
|
93
95
|
Command help:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/protocol.ts
|
|
2
2
|
var PROTOCOL_VERSION = 1;
|
|
3
|
-
var BRIDGE_VERSION = "1.1.
|
|
3
|
+
var BRIDGE_VERSION = "1.1.2";
|
|
4
4
|
var PORTS = Array.from({ length: 10 }, (_, i) => 47820 + i);
|
|
5
5
|
var CLAUDE_MODELS = ["default", "sonnet", "opus", "haiku"];
|
|
6
6
|
var CLAUDE_MODEL_PATTERN = /^(?:default|fable|opus|sonnet|haiku|claude-[a-z0-9]+(?:-[a-z0-9]+){0,4})$/;
|
package/dist/cli.js
CHANGED
|
@@ -6,18 +6,38 @@ import {
|
|
|
6
6
|
MAX_MESSAGE_BYTES,
|
|
7
7
|
PORTS,
|
|
8
8
|
RESOURCES
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-LWN22TEE.js";
|
|
10
10
|
|
|
11
11
|
// src/cli.ts
|
|
12
12
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
13
13
|
|
|
14
|
+
// src/discover.ts
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
function cmsOrigin(input) {
|
|
17
|
+
return new URL(/^[a-z]+:\/\//i.test(input) ? input : `https://${input}`).origin;
|
|
18
|
+
}
|
|
19
|
+
async function discoverServer(origin2, fetchImpl = fetch) {
|
|
20
|
+
const url = `${origin2}/flint-bridge.json`;
|
|
21
|
+
let body;
|
|
22
|
+
try {
|
|
23
|
+
const res = await fetchImpl(url, { redirect: "error", signal: AbortSignal.timeout(1e4), headers: { Accept: "application/json" } });
|
|
24
|
+
if (!res.ok) throw new Error(String(res.status));
|
|
25
|
+
body = await res.json();
|
|
26
|
+
} catch {
|
|
27
|
+
throw new Error(`Could not read ${url}. Check the CMS address, or pass --server <https-origin>.`);
|
|
28
|
+
}
|
|
29
|
+
const parsed = z.object({ server: z.string().url() }).safeParse(body);
|
|
30
|
+
if (!parsed.success) throw new Error(`${url} has no server address. Pass --server <https-origin>.`);
|
|
31
|
+
return new URL(parsed.data.server).origin;
|
|
32
|
+
}
|
|
33
|
+
|
|
14
34
|
// src/background.ts
|
|
15
35
|
import { createServer } from "http";
|
|
16
36
|
import { randomBytes, timingSafeEqual } from "crypto";
|
|
17
37
|
import { spawn } from "child_process";
|
|
18
38
|
import { chmod, mkdir, open as open2, readFile as readFile2, rename, unlink as unlink2 } from "fs/promises";
|
|
19
39
|
import { join } from "path";
|
|
20
|
-
import { z } from "zod";
|
|
40
|
+
import { z as z2 } from "zod";
|
|
21
41
|
|
|
22
42
|
// src/instance.ts
|
|
23
43
|
import { open, readFile, unlink } from "fs/promises";
|
|
@@ -90,12 +110,12 @@ async function acquireInstance(path) {
|
|
|
90
110
|
}
|
|
91
111
|
|
|
92
112
|
// src/background.ts
|
|
93
|
-
var runtimeSchema =
|
|
113
|
+
var runtimeSchema = z2.object({ port: z2.number().int().min(1).max(65535), token: z2.string().regex(/^[a-f0-9]{64}$/), pid: z2.number().int().positive() });
|
|
94
114
|
async function control(directory, action) {
|
|
95
115
|
const runtime = runtimeSchema.parse(JSON.parse(await readFile2(join(directory, "runtime.json"), "utf8")));
|
|
96
116
|
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) });
|
|
97
117
|
if (!res.ok) throw new Error("Bridge control request failed");
|
|
98
|
-
return
|
|
118
|
+
return z2.object({ running: z2.boolean(), port: z2.number().optional(), chat: z2.boolean().optional(), chatReason: z2.string().max(512).optional(), pid: z2.number().optional(), code: z2.string().regex(/^\d{6}$/).optional() }).parse(await res.json());
|
|
99
119
|
}
|
|
100
120
|
async function backgroundStatus(directory) {
|
|
101
121
|
try {
|
|
@@ -119,20 +139,29 @@ async function stopBackground(directory) {
|
|
|
119
139
|
}
|
|
120
140
|
throw new Error("Bridge is still shutting down. Check status before starting again.");
|
|
121
141
|
}
|
|
122
|
-
async function
|
|
142
|
+
async function issuePairingCode(directory) {
|
|
143
|
+
const state = await backgroundStatus(directory);
|
|
144
|
+
if (!state.running) return { running: false };
|
|
145
|
+
try {
|
|
146
|
+
return { running: true, code: (await control(directory, "pair")).code };
|
|
147
|
+
} catch {
|
|
148
|
+
return { running: true };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async function serveControl(directory, status, shutdown, issue) {
|
|
123
152
|
const token = randomBytes(32).toString("hex");
|
|
124
153
|
const runtimePath = join(directory, "runtime.json");
|
|
125
154
|
const server = createServer((req, res) => {
|
|
126
155
|
const address2 = server.address();
|
|
127
156
|
const port = address2 && typeof address2 !== "string" ? address2.port : 0;
|
|
128
157
|
const supplied = Buffer.from(req.headers.authorization ?? ""), expected = Buffer.from(`Bearer ${token}`);
|
|
129
|
-
if (req.method !== "POST" || req.headers.origin || req.headers.host !== `127.0.0.1:${port}` || supplied.length !== expected.length || !timingSafeEqual(supplied, expected) || !["/status", "/stop"].includes(req.url ?? "")) {
|
|
158
|
+
if (req.method !== "POST" || req.headers.origin || req.headers.host !== `127.0.0.1:${port}` || supplied.length !== expected.length || !timingSafeEqual(supplied, expected) || !["/status", "/stop", ...issue ? ["/pair"] : []].includes(req.url ?? "")) {
|
|
130
159
|
res.writeHead(403).end();
|
|
131
160
|
return;
|
|
132
161
|
}
|
|
133
162
|
res.setHeader("Content-Type", "application/json");
|
|
134
163
|
res.setHeader("Cache-Control", "no-store");
|
|
135
|
-
res.end(JSON.stringify({ running: true, ...status, pid: process.pid }));
|
|
164
|
+
res.end(JSON.stringify({ running: true, ...status, pid: process.pid, ...req.url === "/pair" ? { code: issue?.() } : {} }));
|
|
136
165
|
if (req.url === "/stop") void shutdown().catch(() => {
|
|
137
166
|
process.exitCode = 1;
|
|
138
167
|
});
|
|
@@ -201,7 +230,7 @@ async function startBackground(directory, entry, chat) {
|
|
|
201
230
|
child.once("error", (error) => finish(error));
|
|
202
231
|
child.once("exit", () => finish(new Error(`Bridge startup failed. Check ${join(directory, "bridge.log")}`)));
|
|
203
232
|
child.on("message", (message) => {
|
|
204
|
-
const result =
|
|
233
|
+
const result = z2.object({ type: z2.literal("bridge.ready"), port: z2.number(), chat: z2.boolean(), chatReason: z2.string().max(512).optional() }).safeParse(message);
|
|
205
234
|
if (result.success) finish(void 0, { running: true, port: result.data.port, chat: result.data.chat, chatReason: result.data.chatReason, pid: child.pid });
|
|
206
235
|
});
|
|
207
236
|
});
|
|
@@ -222,16 +251,16 @@ import { createInterface } from "readline";
|
|
|
222
251
|
import { mkdir as mkdir2, readFile as readFile3, rename as rename2, writeFile, chmod as chmod2, lstat } from "fs/promises";
|
|
223
252
|
import { dirname } from "path";
|
|
224
253
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
225
|
-
import { z as
|
|
226
|
-
var origin =
|
|
254
|
+
import { z as z3 } from "zod";
|
|
255
|
+
var origin = z3.string().url().refine((value) => {
|
|
227
256
|
const u = new URL(value);
|
|
228
257
|
return u.origin === value && (u.protocol === "https:" || u.protocol === "http:" && ["localhost", "127.0.0.1"].includes(u.hostname));
|
|
229
258
|
}, "Use an exact HTTPS origin, or HTTP loopback for development");
|
|
230
|
-
var schema =
|
|
231
|
-
version:
|
|
232
|
-
hostId:
|
|
233
|
-
servers:
|
|
234
|
-
pairings:
|
|
259
|
+
var schema = z3.object({
|
|
260
|
+
version: z3.literal(1),
|
|
261
|
+
hostId: z3.string().uuid(),
|
|
262
|
+
servers: z3.array(z3.object({ id: z3.string().regex(/^[a-z0-9-]{1,64}$/), url: origin, origins: z3.array(origin).min(1) }).strict()).max(32),
|
|
263
|
+
pairings: z3.array(z3.object({ id: z3.string().uuid(), origin, tokenHash: z3.string().regex(/^[a-f0-9]{64}$/), expiresAt: z3.number().int().positive() }).strict()).max(100)
|
|
235
264
|
}).strict();
|
|
236
265
|
function parseConfig(raw) {
|
|
237
266
|
const config = schema.parse(raw);
|
|
@@ -267,19 +296,19 @@ async function saveConfig(path, config) {
|
|
|
267
296
|
import { mkdtemp as mkdtemp2, writeFile as writeFile3, rm as rm2 } from "fs/promises";
|
|
268
297
|
import { join as join3 } from "path";
|
|
269
298
|
import { fileURLToPath } from "url";
|
|
270
|
-
import { z as
|
|
299
|
+
import { z as z9 } from "zod";
|
|
271
300
|
|
|
272
301
|
// src/cmsMcp.ts
|
|
273
302
|
import { createServer as createServer2 } from "http";
|
|
274
303
|
import { randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
275
|
-
import { z as
|
|
304
|
+
import { z as z7 } from "zod";
|
|
276
305
|
|
|
277
306
|
// src/cmsTools.ts
|
|
278
|
-
import { z as
|
|
307
|
+
import { z as z6 } from "zod";
|
|
279
308
|
|
|
280
309
|
// src/auth.ts
|
|
281
310
|
import { randomUUID as randomUUID4 } from "crypto";
|
|
282
|
-
import { z as
|
|
311
|
+
import { z as z4 } from "zod";
|
|
283
312
|
|
|
284
313
|
// src/security.ts
|
|
285
314
|
import { createHash, randomInt, randomBytes as randomBytes2, randomUUID as randomUUID3, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
@@ -345,15 +374,15 @@ var Pairing = class {
|
|
|
345
374
|
};
|
|
346
375
|
|
|
347
376
|
// src/auth.ts
|
|
348
|
-
var scopeSchema =
|
|
349
|
-
company_id:
|
|
350
|
-
company_ids:
|
|
351
|
-
store_ids:
|
|
352
|
-
super_user:
|
|
353
|
-
is_owner:
|
|
354
|
-
include_descendants:
|
|
377
|
+
var scopeSchema = z4.object({
|
|
378
|
+
company_id: z4.number().int().nullable(),
|
|
379
|
+
company_ids: z4.array(z4.number().int()).nullable(),
|
|
380
|
+
store_ids: z4.array(z4.number().int()).nullable(),
|
|
381
|
+
super_user: z4.boolean().nullable(),
|
|
382
|
+
is_owner: z4.boolean().optional(),
|
|
383
|
+
include_descendants: z4.boolean().nullable().optional()
|
|
355
384
|
});
|
|
356
|
-
var claimSchema =
|
|
385
|
+
var claimSchema = z4.array(z4.object({ name: z4.string() }));
|
|
357
386
|
function permissionsRevision(user) {
|
|
358
387
|
const scope = scopeSchema.parse(user.scope);
|
|
359
388
|
if (scope.company_ids !== null) scope.company_ids = [...new Set(scope.company_ids)].sort((a, b) => a - b);
|
|
@@ -384,11 +413,11 @@ var verifySupabase = async ({ url, anonKey, accessToken }) => {
|
|
|
384
413
|
return JSON.parse(body);
|
|
385
414
|
};
|
|
386
415
|
try {
|
|
387
|
-
const user =
|
|
388
|
-
const payload =
|
|
416
|
+
const user = z4.object({ id: z4.string().uuid(), app_metadata: z4.object({ is_owner: z4.boolean().optional() }).passthrough().optional() }).parse(await get("/auth/v1/user"));
|
|
417
|
+
const payload = z4.object({ exp: z4.number() }).parse(JSON.parse(Buffer.from(accessToken.split(".")[1] ?? "", "base64url").toString()));
|
|
389
418
|
if (payload.exp * 1e3 <= Date.now()) throw new BridgeError("auth_invalid");
|
|
390
419
|
const claims = claimSchema.parse(await get("/rest/v1/rpc/load_my_claim_names", true)).map((r) => r.name);
|
|
391
|
-
const scopes =
|
|
420
|
+
const scopes = z4.array(scopeSchema).length(1).parse(await get("/rest/v1/rpc/get_my_scope", true));
|
|
392
421
|
const scope = { ...scopes[0], ...user.app_metadata?.is_owner === true ? { is_owner: true } : scopes[0].is_owner !== void 0 ? { is_owner: false } : {} };
|
|
393
422
|
if (!scope.is_owner && !claims.includes(AI_CLAIM)) throw new BridgeError("auth_forbidden");
|
|
394
423
|
return { userId: user.id, scope, claims, expiresAt: payload.exp * 1e3 };
|
|
@@ -423,7 +452,7 @@ async function authenticate(options) {
|
|
|
423
452
|
}
|
|
424
453
|
|
|
425
454
|
// src/cmsCatalog.ts
|
|
426
|
-
import { z as
|
|
455
|
+
import { z as z5 } from "zod";
|
|
427
456
|
var dataset = (name, label, resource, table, fields, scope, order = ["id"]) => ({ name, label, resource, table, fields: fields.split(","), ...scope, order });
|
|
428
457
|
var CMS_DATASETS = [
|
|
429
458
|
dataset("devices", "Device details", "devices", "v_devices", "id,name,company_id,store_id,online,created_at,updated_at,keep_alive,width,height,network,cpu_usage,memory_usage,service_version,service_version_code,player_app_version,player_app_version_code,supported_32bit_abis,supported_64bit_abis,density,ip,mac,ssid,ssaid,vpn_status,remote_count,uptime,runtime,screen_on,foreground_app,battery,os_time,device_snapshots,snapshot_url", { company: "company_id", store: "store_id" }),
|
|
@@ -452,31 +481,31 @@ var CMS_DATASETS = [
|
|
|
452
481
|
dataset("device_online_daily", "Daily device uptime", "devices", "v_device_online_daily", "device_id,day,online_seconds,outage_count", { parent: { dataset: "devices", field: "device_id" } }, ["day", "device_id"]),
|
|
453
482
|
dataset("device_online_sessions", "Device connection history", "devices", "v_device_online_sessions", "device_id,online,started_at,ended_at", { parent: { dataset: "devices", field: "device_id" } }, ["started_at", "device_id"])
|
|
454
483
|
];
|
|
455
|
-
var queryArgs =
|
|
456
|
-
dataset:
|
|
457
|
-
fields:
|
|
458
|
-
filters:
|
|
459
|
-
order:
|
|
460
|
-
limit:
|
|
461
|
-
offset:
|
|
462
|
-
countOnly:
|
|
484
|
+
var queryArgs = z5.object({
|
|
485
|
+
dataset: z5.string().min(1).max(80),
|
|
486
|
+
fields: z5.array(z5.string().max(80)).min(1).max(50).optional(),
|
|
487
|
+
filters: z5.array(z5.object({ field: z5.string().max(80), op: z5.enum(["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "is"]), value: z5.union([z5.string().max(500), z5.number().finite(), z5.boolean(), z5.null()]) }).strict()).max(12).default([]),
|
|
488
|
+
order: z5.array(z5.object({ field: z5.string().max(80), direction: z5.enum(["asc", "desc"]) }).strict()).max(3).default([]),
|
|
489
|
+
limit: z5.number().int().min(1).max(50).default(20),
|
|
490
|
+
offset: z5.number().int().min(0).max(1e5).default(0),
|
|
491
|
+
countOnly: z5.boolean().default(false)
|
|
463
492
|
}).strict();
|
|
464
493
|
var DEVICE_QUERY_GUIDANCE = "For device information, prefer the devices dataset backed by public.v_devices. service_version and service_version_code describe the service app; player_app_version and player_app_version_code describe the player app. Filter these fields together with query_cms to search all accessible devices in bulk; do not fetch device_apps once per device for these questions. Use ilike with 3.* for the 3.x family or 3.0.* for the 3.0.x family, and eq for an exact reported version. Use countOnly for the total and paginate matching devices only. Use device_apps for installed-app details not available in v_devices. This dataset joins public.device_apps with public.v_devices and supports bulk queries without a required device_id. Combine app filters (name, package_name, version) and device filters (service_version, player_app_version, company_id, store_id, online) in the same query. device_name is the device name; name is the app name. Its total/countOnly counts matching app records, not distinct devices. Do not claim a distinct device count from app record counts or a partial page. Summary version fields do not prove whether an additional old app is also installed. If the app or version relationship is ambiguous, clarify it instead of assuming service and player versions are interchangeable. For black-screen questions use device_snapshots, which supports bulk filtering by online, analysis_status, black_screen_candidate and captured_at. A completed analysis with black_pixel_ratio >= 0.98 is only a dark-snapshot candidate, not proof of a display or backlight failure. Ratios are 0 to 1; mean_luminance is encoded sRGB luma 0 to 255. Check capture age separately from current online status. Pending, failed, stale and not_analyzed are unknown, never healthy or black. Report unanalysed devices separately when answering about all devices. The devices.device_snapshots field contains source metadata; snapshot_path is relative to the public device_captures bucket. The devices and device_snapshots datasets provide a computed snapshot_url field. Select snapshot_url when the user asks to see a snapshot, together with the device name and capture time. It is a public CMS Storage URL with a capture-version query parameter; never filter or sort on this computed field. The chat UI can display images: use  with the exact returned URL, outside large tables. Do not say images cannot be displayed just because you cannot open image bytes yourself. Never invent a server address or derive a URL from a device ID; if snapshot_url is null, report that no valid snapshot URL is available. The storage path is overwritten: this URL points to the current object, not an immutable historical image. An image URL alone does not mean you have viewed or visually analysed it; describe measured brightness separately from visual inspection.";
|
|
465
494
|
var CATALOG_TOOLS = [
|
|
466
495
|
{ name: "describe_cms_queries", description: "Inspect CMS datasets, fields, filters, and required parent IDs available with the current permissions. Use this tool first if the basic device tools lack the information needed to answer the question.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
|
|
467
496
|
{ name: "query_cms", description: "Query CMS data and exact counts. Only use datasets and fields from describe_cms_queries. Use ISO dates, ilike with * patterns for name searches, and created_at desc for recent registrations. Filters are combined with AND. countOnly returns only the total matching the same filters. If hasMore is true, results are partial; continue with nextOffset. " + DEVICE_QUERY_GUIDANCE, inputSchema: { type: "object", properties: { dataset: { type: "string" }, fields: { type: "array", items: { type: "string" } }, filters: { type: "array", items: { type: "object", properties: { field: { type: "string" }, op: { type: "string", enum: ["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "is"] }, value: { type: ["string", "number", "boolean", "null"] } }, required: ["field", "op", "value"], additionalProperties: false } }, order: { type: "array", items: { type: "object", properties: { field: { type: "string" }, direction: { type: "string", enum: ["asc", "desc"] } }, required: ["field", "direction"], additionalProperties: false } }, limit: { type: "integer", minimum: 1, maximum: 50 }, offset: { type: "integer", minimum: 0, maximum: 1e5 }, countOnly: { type: "boolean" } }, required: ["dataset"], additionalProperties: false } }
|
|
468
497
|
].map((tool) => ({ ...tool, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } }));
|
|
469
|
-
var reportArgs =
|
|
498
|
+
var reportArgs = z5.object({ report: z5.enum(["dashboard", "media_log"]), companyIds: z5.array(z5.number().int().nonnegative()).min(1).max(100).optional(), storeId: z5.number().int().nonnegative().optional(), days: z5.number().int().min(1).max(90).default(7) }).strict();
|
|
470
499
|
var REPORT_TOOL = { name: "get_cms_report", description: "Retrieve dashboard statistics (device uptime trends, media and scene totals) or media playback statistics. Specify company IDs to narrow the scope. Store-restricted accounts must specify one accessible storeId. Requires the statistics RPCs to be installed on the server.", inputSchema: { type: "object", properties: { report: { type: "string", enum: ["dashboard", "media_log"] }, companyIds: { type: "array", items: { type: "integer", minimum: 0 }, minItems: 1, maxItems: 100 }, storeId: { type: "integer", minimum: 0 }, days: { type: "integer", minimum: 1, maximum: 90 } }, required: ["report"], additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } };
|
|
471
|
-
var similarSnapshotArgs =
|
|
500
|
+
var similarSnapshotArgs = z5.object({ deviceId: z5.string().min(1).max(256).regex(/^[^\u0000-\u001f\u007f]+$/), limit: z5.number().int().min(1).max(50).default(10), minSimilarity: z5.number().min(-1).max(1).default(0.8), online: z5.boolean().optional() }).strict();
|
|
472
501
|
var SIMILAR_SNAPSHOT_TOOL = { name: "find_similar_snapshots", description: "Find accessible devices whose latest analysed snapshot is visually similar to a reference device snapshot. Requires a ready image embedding. Results are ranked top matches, not an exhaustive count. Similarity is cosine similarity, not a probability or proof of identical content or a display fault. Check capture times and current online state. Does not accept free-text image descriptions.", inputSchema: { type: "object", properties: { deviceId: { type: "string" }, limit: { type: "integer", minimum: 1, maximum: 50 }, minSimilarity: { type: "number", minimum: -1, maximum: 1 }, online: { type: "boolean" } }, required: ["deviceId"], additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } };
|
|
473
502
|
|
|
474
503
|
// src/cmsTools.ts
|
|
475
|
-
var id =
|
|
476
|
-
var deviceId =
|
|
477
|
-
var companySchema =
|
|
478
|
-
var deviceSchema =
|
|
479
|
-
var listArgs =
|
|
504
|
+
var id = z6.number().int().nonnegative().safe();
|
|
505
|
+
var deviceId = z6.string().min(1).max(256).regex(/^[^\u0000-\u001f\u007f]+$/);
|
|
506
|
+
var companySchema = z6.object({ id, name: z6.string().max(500), parent_id: id.nullable() });
|
|
507
|
+
var deviceSchema = z6.object({ id: deviceId, name: z6.string().max(500).nullable(), company_id: id.nullable(), store_id: id.nullable(), online: z6.boolean(), created_at: z6.string().max(100).nullable(), keep_alive: z6.string().max(100).nullable(), service_version: z6.string().max(100).nullable().optional(), player_app_version: z6.string().max(100).nullable().optional() });
|
|
508
|
+
var listArgs = z6.object({ companyId: id.optional(), storeId: id.optional(), online: z6.boolean().optional(), limit: z6.number().int().min(1).max(50).default(20), afterId: deviceId.optional(), sort: z6.enum(["id", "newest"]).default("id"), offset: z6.number().int().min(0).max(1e5).default(0) }).strict().refine((input) => input.sort === "newest" ? !input.afterId : input.offset === 0, { message: "newest uses offset; id uses afterId" });
|
|
480
509
|
var LEGACY_TOOLS = [
|
|
481
510
|
{ name: "list_devices", description: "Retrieve accessible devices with names, registration times (created_at), online status, and last connection times from public.v_devices. For service/player version conditions, use query_cms with dataset=devices to filter matching devices in bulk. Use sort=newest for recently registered devices (registration time descending, unknown last), then pass nextOffset as offset for the next page. With the default ID ordering, pass nextAfterId as afterId. If hasMore=true, the results are incomplete. Do not infer registration time from IDs or versions.", inputSchema: { type: "object", properties: { companyId: { type: "integer", minimum: 0 }, storeId: { type: "integer", minimum: 0 }, online: { type: "boolean" }, limit: { type: "integer", minimum: 1, maximum: 50 }, afterId: { type: "string", minLength: 1, maxLength: 256 }, sort: { type: "string", enum: ["id", "newest"] }, offset: { type: "integer", minimum: 0, maximum: 1e5 } }, additionalProperties: false } },
|
|
482
511
|
{ name: "get_device_status", description: "Retrieve the registration time (created_at) and status of one accessible device.", inputSchema: { type: "object", properties: { deviceId: { type: "string", minLength: 1, maxLength: 256 } }, required: ["deviceId"], additionalProperties: false } },
|
|
@@ -544,7 +573,7 @@ var CmsReadTools = class {
|
|
|
544
573
|
return allowed;
|
|
545
574
|
}
|
|
546
575
|
if (user.scope.include_descendants === false || !allowed.size) return allowed;
|
|
547
|
-
const companies =
|
|
576
|
+
const companies = z6.array(companySchema).max(999).parse(await this.read("companies", new URLSearchParams({ select: "id,name,parent_id", limit: "1001", order: "id.asc" })));
|
|
548
577
|
let changed = true;
|
|
549
578
|
while (changed) {
|
|
550
579
|
changed = false;
|
|
@@ -563,7 +592,7 @@ var CmsReadTools = class {
|
|
|
563
592
|
let companyIds = input.companyIds ?? (allowed !== null ? [...allowed] : null);
|
|
564
593
|
if (companyIds?.some((id2) => allowed !== null && !allowed.has(id2))) throw new Error("cms_scope_forbidden");
|
|
565
594
|
if (companyIds === null) {
|
|
566
|
-
const rows =
|
|
595
|
+
const rows = z6.array(companySchema).max(999).parse(await this.read("companies", new URLSearchParams({ select: "id,name,parent_id", limit: "1001", order: "id.asc" })));
|
|
567
596
|
companyIds = rows.map((row) => row.id);
|
|
568
597
|
}
|
|
569
598
|
const stores = user.scope.super_user || user.scope.is_owner ? null : user.scope.store_ids;
|
|
@@ -612,7 +641,7 @@ var CmsReadTools = class {
|
|
|
612
641
|
query.append(f.field, `${f.op}.${String(f.value)}`);
|
|
613
642
|
}
|
|
614
643
|
const page = await this.readPage(d.table, query, true, void 0, d.schema);
|
|
615
|
-
const rows =
|
|
644
|
+
const rows = z6.array(z6.record(z6.string(), z6.unknown())).max(input.countOnly ? 0 : input.limit + 1).parse(page.rows);
|
|
616
645
|
for (const row of rows) {
|
|
617
646
|
this.assertRowScope(d, row, allowed, stores);
|
|
618
647
|
if (parentCheck && String(row.id) !== String(input.filters.find((f) => f.field === "id" && f.op === "eq")?.value)) throw new Error("cms_filter_violation");
|
|
@@ -638,7 +667,7 @@ var CmsReadTools = class {
|
|
|
638
667
|
const allowed = await this.scope(user);
|
|
639
668
|
const stores = user.scope.super_user || user.scope.is_owner ? null : user.scope.store_ids;
|
|
640
669
|
const page = await this.readPage("rpc/match_device_snapshots", new URLSearchParams(), false, { p_device_id: input.deviceId, p_limit: input.limit, p_min_similarity: input.minSimilarity, p_company_ids: allowed === null ? null : [...allowed], p_store_ids: stores, p_online: input.online ?? null }, "ai");
|
|
641
|
-
const rows =
|
|
670
|
+
const rows = z6.array(z6.object({ device_id: deviceId, device_name: z6.string().nullable(), company_id: id.nullable(), store_id: id.nullable(), online: z6.boolean(), captured_at: z6.string(), similarity: z6.number().finite().min(-1.000001).max(1.000001), embedding_model: z6.string() })).max(input.limit).parse(page.rows);
|
|
642
671
|
for (const row of rows) {
|
|
643
672
|
if (allowed !== null && (row.company_id === null || !allowed.has(row.company_id)) || stores !== null && (row.store_id === null || !stores.includes(row.store_id))) throw new Error("cms_scope_violation");
|
|
644
673
|
if (row.device_id === input.deviceId || row.similarity < input.minSimilarity || input.online !== void 0 && row.online !== input.online) throw new Error("cms_filter_violation");
|
|
@@ -652,7 +681,7 @@ var CmsReadTools = class {
|
|
|
652
681
|
const o = this.options;
|
|
653
682
|
o.assertActive();
|
|
654
683
|
if (!CMS_TOOLS.some((tool) => tool.name === name)) throw new Error("cms_unknown_tool");
|
|
655
|
-
const parsed = name === "find_similar_snapshots" ? similarSnapshotArgs.parse(args) : name === "get_cms_report" ? reportArgs.parse(args) : name === "query_cms" ? queryArgs.parse(args) : name === "list_devices" ? listArgs.parse(args) : name === "get_device_status" ?
|
|
684
|
+
const parsed = name === "find_similar_snapshots" ? similarSnapshotArgs.parse(args) : name === "get_cms_report" ? reportArgs.parse(args) : name === "query_cms" ? queryArgs.parse(args) : name === "list_devices" ? listArgs.parse(args) : name === "get_device_status" ? z6.object({ deviceId }).strict().parse(args) : z6.object({}).strict().parse(args);
|
|
656
685
|
const user = await (o.verify ?? verifySupabase)(o.credentials);
|
|
657
686
|
o.assertActive();
|
|
658
687
|
if (user.userId !== o.userId || user.expiresAt <= Date.now() || !user.scope.is_owner && !user.claims.includes("enable:ai.assistant")) throw new Error("cms_auth_changed");
|
|
@@ -670,7 +699,7 @@ var CmsReadTools = class {
|
|
|
670
699
|
if (!allowed.size) return { companies: [], hasMore: false };
|
|
671
700
|
query2.set("id", `in.(${[...allowed].join(",")})`);
|
|
672
701
|
}
|
|
673
|
-
const rows2 =
|
|
702
|
+
const rows2 = z6.array(companySchema).max(999).parse(await this.read("companies", query2));
|
|
674
703
|
if (allowed !== null && rows2.some((row) => !allowed.has(row.id))) throw new Error("cms_scope_violation");
|
|
675
704
|
return { companies: rows2, hasMore: false };
|
|
676
705
|
}
|
|
@@ -688,7 +717,7 @@ var CmsReadTools = class {
|
|
|
688
717
|
if (input.storeId !== void 0) query.set("store_id", `eq.${input.storeId}`);
|
|
689
718
|
else if (stores !== null) query.set("store_id", `in.(${stores.join(",")})`);
|
|
690
719
|
if (input.online !== void 0) query.set("online", `eq.${input.online}`);
|
|
691
|
-
const rows =
|
|
720
|
+
const rows = z6.array(deviceSchema).max(limit + 1).parse(await this.read("v_devices", query));
|
|
692
721
|
if (rows.some((row) => allowed !== null && (row.company_id === null || !allowed.has(row.company_id)) || stores !== null && (row.store_id === null || !stores.includes(row.store_id)))) throw new Error("cms_scope_violation");
|
|
693
722
|
if (rows.some((row) => input.deviceId !== void 0 && row.id !== input.deviceId || input.companyId !== void 0 && row.company_id !== input.companyId || input.storeId !== void 0 && row.store_id !== input.storeId || input.online !== void 0 && row.online !== input.online)) throw new Error("cms_filter_violation");
|
|
694
723
|
return { devices: rows.slice(0, limit), hasMore: rows.length > limit, nextAfterId: rows.length > limit && input.sort !== "newest" ? rows[limit - 1].id : null, nextOffset: rows.length > limit && input.sort === "newest" ? input.offset + limit : null };
|
|
@@ -725,7 +754,7 @@ async function startCmsMcp(options) {
|
|
|
725
754
|
body += chunk;
|
|
726
755
|
if (Buffer.byteLength(body) > 65536) throw new Error("large_request");
|
|
727
756
|
}
|
|
728
|
-
const input =
|
|
757
|
+
const input = z7.object({ jsonrpc: z7.literal("2.0"), id: z7.union([z7.string().max(200), z7.number().finite()]).optional(), method: z7.string().max(100), params: z7.unknown().optional() }).strict().parse(JSON.parse(body));
|
|
729
758
|
if (input.id === void 0) {
|
|
730
759
|
res.writeHead(204).end();
|
|
731
760
|
return;
|
|
@@ -733,13 +762,13 @@ async function startCmsMcp(options) {
|
|
|
733
762
|
requestId = input.id;
|
|
734
763
|
let result;
|
|
735
764
|
if (input.method === "initialize") {
|
|
736
|
-
const params =
|
|
765
|
+
const params = z7.object({ protocolVersion: z7.string().max(30) }).passthrough().parse(input.params);
|
|
737
766
|
result = { protocolVersion: params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "flint-cms", version: "1.0.0" } };
|
|
738
767
|
} else if (input.method === "tools/list") result = { tools };
|
|
739
768
|
else if (input.method === "ping") result = {};
|
|
740
769
|
else if (input.method === "tools/call") {
|
|
741
770
|
if (++calls > 64) throw new Error("tool_limit");
|
|
742
|
-
const args =
|
|
771
|
+
const args = z7.object({ name: z7.string(), arguments: z7.unknown().optional(), _meta: z7.record(z7.string(), z7.unknown()).optional() }).strict().parse(input.params);
|
|
743
772
|
if (!tools.some((tool) => tool.name === args.name)) throw new Error("tool_forbidden");
|
|
744
773
|
const label = { find_similar_snapshots: "Similar snapshots", list_devices: "Device list", get_device_status: "Device status", list_companies: "Company list", describe_cms_queries: "Query catalog", query_cms: "CMS data", get_cms_report: "CMS statistics" }[args.name];
|
|
745
774
|
options.onActivity?.(`${label}: querying\u2026`);
|
|
@@ -753,7 +782,7 @@ async function startCmsMcp(options) {
|
|
|
753
782
|
options.onActivity?.(`${label}: query failed`);
|
|
754
783
|
const code = error instanceof Error ? error.message : "";
|
|
755
784
|
const permission = ["cms_auth_changed", "cms_permissions_changed", "cms_tool_forbidden", "cms_scope_forbidden", "cms_scope_violation", "auth_forbidden"].includes(code);
|
|
756
|
-
const message = code === "cms_snapshot_vectors_not_installed" ? "Snapshot vector search is not installed on this server." : code === "cms_snapshot_similarity_unavailable" ? "Snapshot similarity search is unavailable. The reference embedding may still be pending or stale. Query device_snapshot_vectors for its status; do not infer that no similar screens exist." : code === "cms_snapshot_analysis_not_installed" ? "Snapshot analysis requires the snapshot-analysis Edge Function and supabase/device_snapshot_analysis/01_install.sql. Missing analysis does not establish whether a screen is black." : code === "cms_device_apps_not_installed" ? "Bulk installed-app queries require the database administrator to apply 06_device_app_inventory.sql. The ai schema must also be exposed by PostgREST. Do not fall back to a per-device scan." : code === "cms_parent_required" ? "This query requires an eq filter on the parent ID. Check requiredFilter in describe_cms_queries." : ["cms_invalid_field", "cms_invalid_filter", "cms_unknown_dataset"].includes(code) ? "The query dataset or fields are invalid. Check describe_cms_queries." : error instanceof
|
|
785
|
+
const message = code === "cms_snapshot_vectors_not_installed" ? "Snapshot vector search is not installed on this server." : code === "cms_snapshot_similarity_unavailable" ? "Snapshot similarity search is unavailable. The reference embedding may still be pending or stale. Query device_snapshot_vectors for its status; do not infer that no similar screens exist." : code === "cms_snapshot_analysis_not_installed" ? "Snapshot analysis requires the snapshot-analysis Edge Function and supabase/device_snapshot_analysis/01_install.sql. Missing analysis does not establish whether a screen is black." : code === "cms_device_apps_not_installed" ? "Bulk installed-app queries require the database administrator to apply 06_device_app_inventory.sql. The ai schema must also be exposed by PostgREST. Do not fall back to a per-device scan." : code === "cms_parent_required" ? "This query requires an eq filter on the parent ID. Check requiredFilter in describe_cms_queries." : ["cms_invalid_field", "cms_invalid_filter", "cms_unknown_dataset"].includes(code) ? "The query dataset or fields are invalid. Check describe_cms_queries." : error instanceof z7.ZodError ? "The bridge could not process the CMS response format or tool arguments. Do not assume this is a permission issue." : permission ? "Authentication or query scope validation failed." : "An error occurred while processing the CMS query. This error alone does not establish a permission issue.";
|
|
757
786
|
result = { isError: true, content: [{ type: "text", text: message + " Do not guess the query results." }] };
|
|
758
787
|
}
|
|
759
788
|
} else {
|
|
@@ -856,20 +885,20 @@ async function runJsonProcess(options) {
|
|
|
856
885
|
}
|
|
857
886
|
|
|
858
887
|
// src/usage.ts
|
|
859
|
-
import { z as
|
|
860
|
-
var count =
|
|
861
|
-
var turnUsageSchema =
|
|
862
|
-
model_key:
|
|
863
|
-
provider:
|
|
864
|
-
cli_version:
|
|
865
|
-
normalizer_version:
|
|
888
|
+
import { z as z8 } from "zod";
|
|
889
|
+
var count = z8.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();
|
|
890
|
+
var turnUsageSchema = z8.object({
|
|
891
|
+
model_key: z8.string().min(1).max(200),
|
|
892
|
+
provider: z8.enum(["claude", "codex"]),
|
|
893
|
+
cli_version: z8.string().min(1).max(50),
|
|
894
|
+
normalizer_version: z8.literal(1),
|
|
866
895
|
input_tokens: count,
|
|
867
896
|
output_tokens: count,
|
|
868
897
|
cache_read_tokens: count,
|
|
869
898
|
cache_write_tokens: count,
|
|
870
899
|
reasoning_tokens: count,
|
|
871
|
-
usage_status:
|
|
872
|
-
source_scope:
|
|
900
|
+
usage_status: z8.enum(["complete", "partial", "unavailable"]),
|
|
901
|
+
source_scope: z8.literal("turn")
|
|
873
902
|
}).strict();
|
|
874
903
|
var rawCount = (value) => count.safeParse(value).success ? value : null;
|
|
875
904
|
var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
@@ -1001,10 +1030,10 @@ async function checkClaudeCapabilities(directory, cli, run3 = runJsonProcess) {
|
|
|
1001
1030
|
}
|
|
1002
1031
|
|
|
1003
1032
|
// src/cmsTurn.ts
|
|
1004
|
-
var dbTurn =
|
|
1033
|
+
var dbTurn = z9.object({ id: z9.string().uuid(), session_id: z9.string().uuid(), host_id: z9.string().uuid(), cli: z9.literal("claude"), status: z9.literal("running"), bridge_stream_id: z9.string().uuid(), prompt: z9.string().min(1).max(32e3), lease_expires_at: z9.string() });
|
|
1005
1034
|
function createCmsExecutor(dataDir, cliVersion = "unknown") {
|
|
1006
1035
|
return async (request) => {
|
|
1007
|
-
const model =
|
|
1036
|
+
const model = z9.string().max(64).regex(CLAUDE_MODEL_PATTERN).parse(request.model ?? "default");
|
|
1008
1037
|
const controller = new AbortController();
|
|
1009
1038
|
const signal = AbortSignal.any([request.signal, controller.signal]);
|
|
1010
1039
|
const active = () => {
|
|
@@ -1036,16 +1065,16 @@ function createCmsExecutor(dataDir, cliVersion = "unknown") {
|
|
|
1036
1065
|
const user = await verifySupabase(request.credentials);
|
|
1037
1066
|
active();
|
|
1038
1067
|
if (user.userId !== request.auth.userId || permissionsRevision(user) !== request.auth.permissionsRevision) throw new Error("cms_permissions_changed");
|
|
1039
|
-
const sessions =
|
|
1068
|
+
const sessions = z9.array(z9.object({ id: z9.string().uuid(), user_id: z9.string().uuid(), mode: z9.literal("cms"), permissions_revision: z9.string() })).length(1).parse(await read("chat_sessions", new URLSearchParams({ select: "id,user_id,mode,permissions_revision", id: `eq.${request.sessionId}` })));
|
|
1040
1069
|
if (sessions[0].user_id !== user.userId || sessions[0].permissions_revision !== request.auth.permissionsRevision) throw new Error("cms_session_scope_changed");
|
|
1041
1070
|
const checkLease = async () => {
|
|
1042
|
-
const rows =
|
|
1071
|
+
const rows = z9.array(dbTurn).length(1).parse(await read("chat_turns", new URLSearchParams({ select: "id,session_id,host_id,cli,status,bridge_stream_id,prompt,lease_expires_at", id: `eq.${request.turnId}` })));
|
|
1043
1072
|
const turn2 = rows[0];
|
|
1044
1073
|
if (turn2.bridge_stream_id !== request.streamId || turn2.session_id !== request.sessionId || turn2.host_id !== request.hostId || Date.parse(turn2.lease_expires_at) - Date.now() <= 15e3 || !Number.isFinite(Date.parse(turn2.lease_expires_at))) throw new Error("cms_lease_lost");
|
|
1045
1074
|
return turn2;
|
|
1046
1075
|
};
|
|
1047
1076
|
const turn = await checkLease();
|
|
1048
|
-
const messages =
|
|
1077
|
+
const messages = z9.array(z9.object({ role: z9.enum(["user", "assistant"]), content: z9.string(), turn_id: z9.string().uuid(), chat_turns: z9.object({ status: z9.literal("completed") }) })).max(20).parse(await read("chat_messages", new URLSearchParams({ select: "role,content,turn_id,chat_turns!inner(status)", "chat_turns.status": "eq.completed", session_id: `eq.${request.sessionId}`, order: "message_seq.desc", limit: "20" }), 2 * 1024 * 1024));
|
|
1049
1078
|
let remaining = 32e3;
|
|
1050
1079
|
const history = messages.filter((m) => m.turn_id !== request.turnId).map((m) => {
|
|
1051
1080
|
const content = remaining > 0 ? m.content.slice(-remaining) : "";
|
|
@@ -1167,27 +1196,27 @@ import { createServer as createServer3 } from "http";
|
|
|
1167
1196
|
import { isDeepStrictEqual } from "util";
|
|
1168
1197
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
1169
1198
|
import { WebSocketServer, WebSocket } from "ws";
|
|
1170
|
-
import { z as
|
|
1171
|
-
var envelope = { v:
|
|
1172
|
-
var turnFields = { ...envelope, authContextId:
|
|
1173
|
-
var requestSchema =
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1199
|
+
import { z as z10 } from "zod";
|
|
1200
|
+
var envelope = { v: z10.literal(1), requestId: z10.string().uuid() };
|
|
1201
|
+
var turnFields = { ...envelope, authContextId: z10.string().uuid(), turnId: z10.string().uuid() };
|
|
1202
|
+
var requestSchema = z10.discriminatedUnion("type", [
|
|
1203
|
+
z10.object({ ...envelope, type: z10.literal("hello"), bridgeToken: z10.string().max(128).optional() }).strict(),
|
|
1204
|
+
z10.object({ ...envelope, type: z10.literal("pair.request") }).strict(),
|
|
1205
|
+
z10.object({ ...envelope, type: z10.literal("pair"), code: z10.string().regex(/^\d{6}$/) }).strict(),
|
|
1206
|
+
z10.object({
|
|
1178
1207
|
...envelope,
|
|
1179
|
-
type:
|
|
1180
|
-
authContextId:
|
|
1181
|
-
supabaseUrl:
|
|
1182
|
-
anonKey:
|
|
1183
|
-
accessToken:
|
|
1184
|
-
accessibleResources:
|
|
1208
|
+
type: z10.literal("auth.update"),
|
|
1209
|
+
authContextId: z10.string().uuid().optional(),
|
|
1210
|
+
supabaseUrl: z10.string().url().max(512),
|
|
1211
|
+
anonKey: z10.string().min(1).max(8192),
|
|
1212
|
+
accessToken: z10.string().min(1).max(16384),
|
|
1213
|
+
accessibleResources: z10.array(z10.string().max(64)).max(32)
|
|
1185
1214
|
}).strict(),
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
...["status", "unpair"].map((type) =>
|
|
1215
|
+
z10.object({ ...envelope, type: z10.literal("auth.clear"), authContextId: z10.string().uuid() }).strict(),
|
|
1216
|
+
z10.object({ ...turnFields, type: z10.literal("turn.start"), sessionId: z10.string().uuid(), model: z10.string().max(64).regex(CLAUDE_MODEL_PATTERN).optional() }).strict(),
|
|
1217
|
+
z10.object({ ...turnFields, type: z10.literal("turn.cancel") }).strict(),
|
|
1218
|
+
z10.object({ ...turnFields, type: z10.literal("turn.ack") }).strict(),
|
|
1219
|
+
...["status", "unpair"].map((type) => z10.object({ ...envelope, type: z10.literal(type) }).strict())
|
|
1191
1220
|
]);
|
|
1192
1221
|
async function startBridge(options) {
|
|
1193
1222
|
const { config } = options;
|
|
@@ -1290,7 +1319,7 @@ async function startBridge(options) {
|
|
|
1290
1319
|
if (!result.success) {
|
|
1291
1320
|
const input = parsed;
|
|
1292
1321
|
const code = input?.v !== 1 ? "version_unsupported" : input?.type === "turn.start" ? "preflight_required" : "invalid_request";
|
|
1293
|
-
send(peer, { type: "request.error", code, message: code }, typeof input?.requestId === "string" &&
|
|
1322
|
+
send(peer, { type: "request.error", code, message: code }, typeof input?.requestId === "string" && z10.string().uuid().safeParse(input.requestId).success ? input.requestId : void 0);
|
|
1294
1323
|
peer.pending--;
|
|
1295
1324
|
return;
|
|
1296
1325
|
}
|
|
@@ -1441,7 +1470,7 @@ async function startBridge(options) {
|
|
|
1441
1470
|
const query = new URLSearchParams({ select: "result_payload", id: `eq.${turn.id}`, session_id: `eq.${turn.sessionId}` });
|
|
1442
1471
|
const result2 = await fetch(`${server.url}/rest/v1/chat_turns?${query}`, { headers: { "Accept-Profile": "ai", apikey: auth.anonKey, Authorization: `Bearer ${auth.accessToken}` }, redirect: "error", signal: AbortSignal.timeout(8e3) });
|
|
1443
1472
|
if (!result2.ok) throw new BridgeError("turn_failed");
|
|
1444
|
-
const rows =
|
|
1473
|
+
const rows = z10.array(z10.object({ result_payload: z10.unknown() })).length(1).parse(await result2.json());
|
|
1445
1474
|
if (!isDeepStrictEqual(rows[0].result_payload, turn.result)) throw new BridgeError("turn_failed");
|
|
1446
1475
|
peer.turn = void 0;
|
|
1447
1476
|
reply({ type: "turn.acked", turnId: request.turnId });
|
|
@@ -1556,8 +1585,8 @@ async function startBridge(options) {
|
|
|
1556
1585
|
// src/claudeModels.ts
|
|
1557
1586
|
import { mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile4 } from "fs/promises";
|
|
1558
1587
|
import { join as join4 } from "path";
|
|
1559
|
-
import { z as
|
|
1560
|
-
var listSchema =
|
|
1588
|
+
import { z as z11 } from "zod";
|
|
1589
|
+
var listSchema = z11.array(z11.object({ value: z11.string(), displayName: z11.string(), description: z11.string().optional() }).passthrough()).max(64);
|
|
1561
1590
|
function parseModels(raw) {
|
|
1562
1591
|
const list = listSchema.safeParse(raw);
|
|
1563
1592
|
if (!list.success) return [];
|
|
@@ -1698,12 +1727,13 @@ async function main() {
|
|
|
1698
1727
|
help: { type: "boolean", short: "h" }
|
|
1699
1728
|
} });
|
|
1700
1729
|
if (values.help) {
|
|
1701
|
-
console.log(`flint-ai-bridge [setup|uninstall|start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
|
|
1702
|
-
setup
|
|
1730
|
+
console.log(`flint-ai-bridge [setup|uninstall|start|status|code|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
|
|
1731
|
+
setup <cms-address> [--server <https-origin>] [--id <server-id>]: register the CMS, start the bridge at login, and start it now.
|
|
1732
|
+
The server is read from the CMS unless --server is given. --origin <cms-origin> also works in place of <cms-address>.
|
|
1703
1733
|
uninstall: stop starting at login and stop the bridge. Registered servers and remembered browsers are kept.
|
|
1704
1734
|
configure --id <server-id> --server <https-origin> --origin <cms-origin>
|
|
1705
1735
|
start --enable-chat: run in the background; terminal can be closed.
|
|
1706
|
-
status: show background status. stop: stop the bridge.
|
|
1736
|
+
status: show background status. code: show a new six-digit pairing code. stop: stop the bridge.
|
|
1707
1737
|
serve: loopback connection and pairing. --enable-chat opts into Claude CMS chat after SQL/claim preparation.
|
|
1708
1738
|
While serving, type "pair" to issue a new five-minute pairing code.`);
|
|
1709
1739
|
return;
|
|
@@ -1719,15 +1749,24 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
|
|
|
1719
1749
|
console.log(state.running ? `Bridge running: ws://127.0.0.1:${state.port} (chat ${state.chat ? "enabled" : "disabled"})${state.chatReason ? ` \u2014 ${state.chatReason}` : ""}` : state.unavailable ? "Bridge status unavailable: an instance lock exists. Check bridge.log." : "Bridge is stopped.");
|
|
1720
1750
|
return;
|
|
1721
1751
|
}
|
|
1752
|
+
if (command === "code") {
|
|
1753
|
+
const result = await issuePairingCode(directory);
|
|
1754
|
+
console.log(!result.running ? "Bridge is stopped. Run setup again, then run this command." : result.code ? `Pairing code: ${result.code}
|
|
1755
|
+
Type it in CMS Settings > AI connection within 5 minutes.` : "No code issued. Wait 60 seconds after failed attempts, or run setup again to update the bridge.");
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1722
1758
|
if (command === "stop") {
|
|
1723
1759
|
console.log(await stopBackground(directory) ? "Bridge stopped." : "Bridge is already stopped.");
|
|
1724
1760
|
return;
|
|
1725
1761
|
}
|
|
1726
1762
|
const config = await readConfig(path);
|
|
1727
1763
|
if (command === "setup") {
|
|
1728
|
-
|
|
1764
|
+
const input = values.origin ?? positionals[1];
|
|
1765
|
+
if (!input) throw new Error("setup requires the CMS address, e.g. setup new.dusta.dev");
|
|
1766
|
+
const origin2 = cmsOrigin(input);
|
|
1767
|
+
const server = values.server ?? await discoverServer(origin2);
|
|
1729
1768
|
if (running) await stopBackground(directory);
|
|
1730
|
-
register(config, values.id ?? "flint",
|
|
1769
|
+
register(config, values.id ?? "flint", server, origin2);
|
|
1731
1770
|
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
1732
1771
|
await saveConfig(path, config);
|
|
1733
1772
|
const kind = await installAutostart(directory, BRIDGE_VERSION);
|
|
@@ -1820,13 +1859,17 @@ Log: ${join6(directory, "bridge.log")}`);
|
|
|
1820
1859
|
}
|
|
1821
1860
|
}
|
|
1822
1861
|
const bridge = await startBridge({ config, persist, execute, autostart: await autostartInstalled(), listModels: execute ? () => listClaudeModels(directory) : void 0, approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
|
|
1823
|
-
const
|
|
1862
|
+
const issueCode = () => {
|
|
1824
1863
|
try {
|
|
1825
|
-
|
|
1864
|
+
return bridge.pairing.issue();
|
|
1826
1865
|
} catch {
|
|
1827
|
-
|
|
1866
|
+
return void 0;
|
|
1828
1867
|
}
|
|
1829
1868
|
};
|
|
1869
|
+
const issue = () => {
|
|
1870
|
+
const code = issueCode();
|
|
1871
|
+
console.log(code ? `Pairing code: ${code} (5 minutes; type pair or run the code command to reissue)` : "Pairing locked. Wait 60 seconds before retrying.");
|
|
1872
|
+
};
|
|
1830
1873
|
console.log(`FLiNT AI bridge: ws://127.0.0.1:${bridge.port}
|
|
1831
1874
|
${execute ? "CMS chat enabled; server claim and SQL preflight required per turn." : "Chat disabled: isolation and database preflight verification required."}`);
|
|
1832
1875
|
issue();
|
|
@@ -1869,7 +1912,7 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
|
|
|
1869
1912
|
await release();
|
|
1870
1913
|
};
|
|
1871
1914
|
try {
|
|
1872
|
-
closeControl = await serveControl(directory, { port: bridge.port, chat: !!execute, chatReason }, shutdown);
|
|
1915
|
+
closeControl = await serveControl(directory, { port: bridge.port, chat: !!execute, chatReason }, shutdown, issueCode);
|
|
1873
1916
|
} catch (error) {
|
|
1874
1917
|
await shutdown();
|
|
1875
1918
|
throw error;
|
package/dist/protocol.d.ts
CHANGED
|
@@ -24,7 +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.
|
|
27
|
+
declare const BRIDGE_VERSION = "1.1.2";
|
|
28
28
|
declare const PORTS: number[];
|
|
29
29
|
/** The only models bridges up to 1.1.0 accept. Newer bridges report capabilities.anyModel. */
|
|
30
30
|
declare const CLAUDE_MODELS: readonly ["default", "sonnet", "opus", "haiku"];
|
package/dist/protocol.js
CHANGED