@dicamo/flint-ai-bridge 1.1.0 → 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 +18 -16
- package/dist/{chunk-SST2QOUV.js → chunk-LWN22TEE.js} +3 -1
- package/dist/cli.js +217 -119
- package/dist/protocol.d.ts +15 -4
- package/dist/protocol.js +3 -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
|
|
|
@@ -59,7 +60,7 @@ Ask about companies, stores, devices, media, scenes, users, login history, autom
|
|
|
59
60
|
|
|
60
61
|
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.
|
|
61
62
|
|
|
62
|
-
Select the Claude model at the top of the chat
|
|
63
|
+
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.
|
|
63
64
|
|
|
64
65
|
## Reconnect or stop
|
|
65
66
|
|
|
@@ -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,8 +1,9 @@
|
|
|
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
|
+
var CLAUDE_MODEL_PATTERN = /^(?:default|fable|opus|sonnet|haiku|claude-[a-z0-9]+(?:-[a-z0-9]+){0,4})$/;
|
|
6
7
|
var AI_CLAIM = "enable:ai.assistant";
|
|
7
8
|
var MAX_MESSAGE_BYTES = 256 * 1024;
|
|
8
9
|
var RESOURCES = ["companies", "devices", "studio", "media", "dashboard", "users", "users.login_history", "automations", "holidays", "app_store", "alterra", "media_log"];
|
|
@@ -12,6 +13,7 @@ export {
|
|
|
12
13
|
BRIDGE_VERSION,
|
|
13
14
|
PORTS,
|
|
14
15
|
CLAUDE_MODELS,
|
|
16
|
+
CLAUDE_MODEL_PATTERN,
|
|
15
17
|
AI_CLAIM,
|
|
16
18
|
MAX_MESSAGE_BYTES,
|
|
17
19
|
RESOURCES
|
package/dist/cli.js
CHANGED
|
@@ -2,22 +2,42 @@
|
|
|
2
2
|
import {
|
|
3
3
|
AI_CLAIM,
|
|
4
4
|
BRIDGE_VERSION,
|
|
5
|
-
|
|
5
|
+
CLAUDE_MODEL_PATTERN,
|
|
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
|
});
|
|
@@ -212,26 +241,26 @@ async function startBackground(directory, entry, chat) {
|
|
|
212
241
|
|
|
213
242
|
// src/cli.ts
|
|
214
243
|
import { homedir as homedir2 } from "os";
|
|
215
|
-
import { join as
|
|
244
|
+
import { join as join6, resolve } from "path";
|
|
216
245
|
import { parseArgs } from "util";
|
|
217
246
|
import { watchFile, unwatchFile } from "fs";
|
|
218
|
-
import { access as access2, writeFile as
|
|
247
|
+
import { access as access2, writeFile as writeFile6, mkdir as mkdir4, unlink as unlink4 } from "fs/promises";
|
|
219
248
|
import { createInterface } from "readline";
|
|
220
249
|
|
|
221
250
|
// src/config.ts
|
|
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;
|
|
@@ -1200,6 +1229,19 @@ async function startBridge(options) {
|
|
|
1200
1229
|
const detect = options.detect ?? detectClis;
|
|
1201
1230
|
let clis = await detect();
|
|
1202
1231
|
let lastDetection = Date.now();
|
|
1232
|
+
let models;
|
|
1233
|
+
let modelsAt = 0;
|
|
1234
|
+
let loadingModels;
|
|
1235
|
+
const refreshModels = () => {
|
|
1236
|
+
if (!options.listModels || loadingModels || Date.now() - modelsAt < 36e5) return loadingModels;
|
|
1237
|
+
loadingModels = options.listModels().then((list) => list, () => void 0).then((list) => {
|
|
1238
|
+
if (list) models = list;
|
|
1239
|
+
modelsAt = list ? Date.now() : Date.now() - 33e5;
|
|
1240
|
+
loadingModels = void 0;
|
|
1241
|
+
});
|
|
1242
|
+
return loadingModels;
|
|
1243
|
+
};
|
|
1244
|
+
await refreshModels();
|
|
1203
1245
|
const http = createServer3((_req, res) => {
|
|
1204
1246
|
res.writeHead(404, { "Cache-Control": "no-store" });
|
|
1205
1247
|
res.end();
|
|
@@ -1277,7 +1319,7 @@ async function startBridge(options) {
|
|
|
1277
1319
|
if (!result.success) {
|
|
1278
1320
|
const input = parsed;
|
|
1279
1321
|
const code = input?.v !== 1 ? "version_unsupported" : input?.type === "turn.start" ? "preflight_required" : "invalid_request";
|
|
1280
|
-
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);
|
|
1281
1323
|
peer.pending--;
|
|
1282
1324
|
return;
|
|
1283
1325
|
}
|
|
@@ -1295,6 +1337,7 @@ async function startBridge(options) {
|
|
|
1295
1337
|
peer.pairingId = remembered.id;
|
|
1296
1338
|
clearTimeout(peer.deadline);
|
|
1297
1339
|
}
|
|
1340
|
+
void refreshModels();
|
|
1298
1341
|
reply({
|
|
1299
1342
|
type: "hello.ok",
|
|
1300
1343
|
bridgeVersion: BRIDGE_VERSION,
|
|
@@ -1303,7 +1346,8 @@ async function startBridge(options) {
|
|
|
1303
1346
|
connectionId: peer.id,
|
|
1304
1347
|
paired: !!remembered,
|
|
1305
1348
|
clis,
|
|
1306
|
-
|
|
1349
|
+
...models ? { models } : {},
|
|
1350
|
+
capabilities: { modelSelection: true, localApproval: !!options.approve, chat: !!options.execute, reason: options.execute ? "ready" : "preflight_required", autostart: !!options.autostart, anyModel: true }
|
|
1307
1351
|
});
|
|
1308
1352
|
return;
|
|
1309
1353
|
}
|
|
@@ -1426,7 +1470,7 @@ async function startBridge(options) {
|
|
|
1426
1470
|
const query = new URLSearchParams({ select: "result_payload", id: `eq.${turn.id}`, session_id: `eq.${turn.sessionId}` });
|
|
1427
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) });
|
|
1428
1472
|
if (!result2.ok) throw new BridgeError("turn_failed");
|
|
1429
|
-
const rows =
|
|
1473
|
+
const rows = z10.array(z10.object({ result_payload: z10.unknown() })).length(1).parse(await result2.json());
|
|
1430
1474
|
if (!isDeepStrictEqual(rows[0].result_payload, turn.result)) throw new BridgeError("turn_failed");
|
|
1431
1475
|
peer.turn = void 0;
|
|
1432
1476
|
reply({ type: "turn.acked", turnId: request.turnId });
|
|
@@ -1538,21 +1582,61 @@ async function startBridge(options) {
|
|
|
1538
1582
|
};
|
|
1539
1583
|
}
|
|
1540
1584
|
|
|
1585
|
+
// src/claudeModels.ts
|
|
1586
|
+
import { mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile4 } from "fs/promises";
|
|
1587
|
+
import { join as join4 } from "path";
|
|
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);
|
|
1590
|
+
function parseModels(raw) {
|
|
1591
|
+
const list = listSchema.safeParse(raw);
|
|
1592
|
+
if (!list.success) return [];
|
|
1593
|
+
return list.data.filter((m) => CLAUDE_MODEL_PATTERN.test(m.value)).slice(0, 40).map((m) => ({
|
|
1594
|
+
value: m.value,
|
|
1595
|
+
displayName: m.displayName.slice(0, 60),
|
|
1596
|
+
...m.description ? { description: m.description.slice(0, 120) } : {}
|
|
1597
|
+
}));
|
|
1598
|
+
}
|
|
1599
|
+
async function listClaudeModels(directory, run3 = runJsonProcess) {
|
|
1600
|
+
const dir = await mkdtemp3(join4(directory, "claude-models-"));
|
|
1601
|
+
let models;
|
|
1602
|
+
try {
|
|
1603
|
+
const config = join4(dir, "mcp.json");
|
|
1604
|
+
await writeFile4(config, JSON.stringify({ mcpServers: {} }), { mode: 384 });
|
|
1605
|
+
await run3({
|
|
1606
|
+
command: "claude",
|
|
1607
|
+
args: [...claudeIsolationArgs(config), "--input-format", "stream-json"],
|
|
1608
|
+
cwd: dir,
|
|
1609
|
+
env: claudeEnvironment(),
|
|
1610
|
+
input: JSON.stringify({ type: "control_request", request_id: "models", request: { subtype: "initialize" } }) + "\n",
|
|
1611
|
+
timeoutMs: 15e3,
|
|
1612
|
+
maxBytes: 1024 * 1024,
|
|
1613
|
+
onEvent(event) {
|
|
1614
|
+
const e = event;
|
|
1615
|
+
if (e.type === "control_response" && e.response?.request_id === "models") models = parseModels(e.response.response?.models);
|
|
1616
|
+
}
|
|
1617
|
+
}).catch(() => {
|
|
1618
|
+
});
|
|
1619
|
+
return models?.length ? models : void 0;
|
|
1620
|
+
} finally {
|
|
1621
|
+
await rm3(dir, { recursive: true, force: true });
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1541
1625
|
// src/autostart.ts
|
|
1542
1626
|
import { execFile as execFile3 } from "child_process";
|
|
1543
|
-
import { access, mkdir as mkdir3, unlink as unlink3, writeFile as
|
|
1627
|
+
import { access, mkdir as mkdir3, unlink as unlink3, writeFile as writeFile5 } from "fs/promises";
|
|
1544
1628
|
import { homedir } from "os";
|
|
1545
|
-
import { dirname as dirname2, join as
|
|
1629
|
+
import { dirname as dirname2, join as join5 } from "path";
|
|
1546
1630
|
import { promisify as promisify3 } from "util";
|
|
1547
1631
|
var run2 = promisify3(execFile3);
|
|
1548
1632
|
var LAUNCH_LABEL = "dev.dicamo.flint-ai-bridge";
|
|
1549
1633
|
var WINDOWS_RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
1550
1634
|
var WINDOWS_VALUE = "FlintAiBridge";
|
|
1551
|
-
var plistPath = () =>
|
|
1635
|
+
var plistPath = () => join5(homedir(), "Library", "LaunchAgents", `${LAUNCH_LABEL}.plist`);
|
|
1552
1636
|
var xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1553
1637
|
var exists = (path) => access(path).then(() => true, () => false);
|
|
1554
1638
|
async function npxPath() {
|
|
1555
|
-
const candidate =
|
|
1639
|
+
const candidate = join5(dirname2(process.execPath), process.platform === "win32" ? "npx.cmd" : "npx");
|
|
1556
1640
|
if (await exists(candidate)) return candidate;
|
|
1557
1641
|
const { stdout } = await run2(process.platform === "win32" ? "where" : "which", ["npx"], { timeout: 5e3 });
|
|
1558
1642
|
const found = stdout.split(/\r?\n/)[0]?.trim();
|
|
@@ -1564,7 +1648,7 @@ function bridgeArgs(version, directory, command) {
|
|
|
1564
1648
|
}
|
|
1565
1649
|
function launchAgentPlist(npx, args, directory, path) {
|
|
1566
1650
|
const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join("\n");
|
|
1567
|
-
const log = xml(
|
|
1651
|
+
const log = xml(join5(directory, "bridge.log"));
|
|
1568
1652
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1569
1653
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1570
1654
|
<plist version="1.0">
|
|
@@ -1591,7 +1675,7 @@ async function installAutostart(directory, version) {
|
|
|
1591
1675
|
const npx = await npxPath();
|
|
1592
1676
|
const path = plistPath();
|
|
1593
1677
|
await mkdir3(dirname2(path), { recursive: true });
|
|
1594
|
-
await
|
|
1678
|
+
await writeFile5(path, launchAgentPlist(npx, bridgeArgs(version, directory, "serve"), directory, process.env.PATH ?? "/usr/bin:/bin"), { mode: 420 });
|
|
1595
1679
|
const domain = `gui/${process.getuid?.()}`;
|
|
1596
1680
|
await run2("launchctl", ["bootout", `${domain}/${LAUNCH_LABEL}`]).catch(() => {
|
|
1597
1681
|
});
|
|
@@ -1643,20 +1727,21 @@ async function main() {
|
|
|
1643
1727
|
help: { type: "boolean", short: "h" }
|
|
1644
1728
|
} });
|
|
1645
1729
|
if (values.help) {
|
|
1646
|
-
console.log(`flint-ai-bridge [setup|uninstall|start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
|
|
1647
|
-
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>.
|
|
1648
1733
|
uninstall: stop starting at login and stop the bridge. Registered servers and remembered browsers are kept.
|
|
1649
1734
|
configure --id <server-id> --server <https-origin> --origin <cms-origin>
|
|
1650
1735
|
start --enable-chat: run in the background; terminal can be closed.
|
|
1651
|
-
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.
|
|
1652
1737
|
serve: loopback connection and pairing. --enable-chat opts into Claude CMS chat after SQL/claim preparation.
|
|
1653
1738
|
While serving, type "pair" to issue a new five-minute pairing code.`);
|
|
1654
1739
|
return;
|
|
1655
1740
|
}
|
|
1656
|
-
const path =
|
|
1657
|
-
const directory = resolve(values["data-dir"] ??
|
|
1658
|
-
const lockPath =
|
|
1659
|
-
const revokePath =
|
|
1741
|
+
const path = join6(resolve(values["data-dir"] ?? join6(homedir2(), ".flint-ai-bridge")), "config.json");
|
|
1742
|
+
const directory = resolve(values["data-dir"] ?? join6(homedir2(), ".flint-ai-bridge"));
|
|
1743
|
+
const lockPath = join6(directory, "instance.lock");
|
|
1744
|
+
const revokePath = join6(directory, "revoke.request");
|
|
1660
1745
|
const running = await instanceLocked(lockPath);
|
|
1661
1746
|
const command = positionals[0] ?? "serve";
|
|
1662
1747
|
if (command === "status") {
|
|
@@ -1664,15 +1749,24 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
|
|
|
1664
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.");
|
|
1665
1750
|
return;
|
|
1666
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
|
+
}
|
|
1667
1758
|
if (command === "stop") {
|
|
1668
1759
|
console.log(await stopBackground(directory) ? "Bridge stopped." : "Bridge is already stopped.");
|
|
1669
1760
|
return;
|
|
1670
1761
|
}
|
|
1671
1762
|
const config = await readConfig(path);
|
|
1672
1763
|
if (command === "setup") {
|
|
1673
|
-
|
|
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);
|
|
1674
1768
|
if (running) await stopBackground(directory);
|
|
1675
|
-
register(config, values.id ?? "flint",
|
|
1769
|
+
register(config, values.id ?? "flint", server, origin2);
|
|
1676
1770
|
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
1677
1771
|
await saveConfig(path, config);
|
|
1678
1772
|
const kind = await installAutostart(directory, BRIDGE_VERSION);
|
|
@@ -1682,7 +1776,7 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
|
|
|
1682
1776
|
await new Promise((resolve2) => setTimeout(resolve2, 500));
|
|
1683
1777
|
state = await backgroundStatus(directory);
|
|
1684
1778
|
}
|
|
1685
|
-
if (!state.running) throw new Error(`Bridge did not start. Check ${
|
|
1779
|
+
if (!state.running) throw new Error(`Bridge did not start. Check ${join6(directory, "bridge.log")}`);
|
|
1686
1780
|
} else state = await startBackground(directory, fileURLToPath2(import.meta.url), true);
|
|
1687
1781
|
console.log(`FLiNT AI bridge is ready: ws://127.0.0.1:${state.port}
|
|
1688
1782
|
Chat: ${state.chat ? "enabled" : `disabled${state.chatReason ? `: ${state.chatReason}` : ""}`}
|
|
@@ -1708,7 +1802,7 @@ You can close this terminal. The bridge will keep running in the background.
|
|
|
1708
1802
|
To stop the bridge, run:
|
|
1709
1803
|
npx @dicamo/flint-ai-bridge stop${dataDirOption}
|
|
1710
1804
|
|
|
1711
|
-
Log: ${
|
|
1805
|
+
Log: ${join6(directory, "bridge.log")}`);
|
|
1712
1806
|
return;
|
|
1713
1807
|
}
|
|
1714
1808
|
switch (command) {
|
|
@@ -1722,7 +1816,7 @@ Log: ${join5(directory, "bridge.log")}`);
|
|
|
1722
1816
|
}
|
|
1723
1817
|
case "unpair":
|
|
1724
1818
|
if (running) {
|
|
1725
|
-
await
|
|
1819
|
+
await writeFile6(revokePath, String(Date.now()), { mode: 384 });
|
|
1726
1820
|
console.log("Revocation requested. The running bridge processes it within one second.");
|
|
1727
1821
|
} else {
|
|
1728
1822
|
config.pairings = [];
|
|
@@ -1764,14 +1858,18 @@ Log: ${join5(directory, "bridge.log")}`);
|
|
|
1764
1858
|
console.warn(`CMS chat unavailable: ${chatReason} Bridge discovery remains available.`);
|
|
1765
1859
|
}
|
|
1766
1860
|
}
|
|
1767
|
-
const bridge = await startBridge({ config, persist, execute, autostart: await autostartInstalled(), approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
|
|
1768
|
-
const
|
|
1861
|
+
const bridge = await startBridge({ config, persist, execute, autostart: await autostartInstalled(), listModels: execute ? () => listClaudeModels(directory) : void 0, approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
|
|
1862
|
+
const issueCode = () => {
|
|
1769
1863
|
try {
|
|
1770
|
-
|
|
1864
|
+
return bridge.pairing.issue();
|
|
1771
1865
|
} catch {
|
|
1772
|
-
|
|
1866
|
+
return void 0;
|
|
1773
1867
|
}
|
|
1774
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
|
+
};
|
|
1775
1873
|
console.log(`FLiNT AI bridge: ws://127.0.0.1:${bridge.port}
|
|
1776
1874
|
${execute ? "CMS chat enabled; server claim and SQL preflight required per turn." : "Chat disabled: isolation and database preflight verification required."}`);
|
|
1777
1875
|
issue();
|
|
@@ -1814,7 +1912,7 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
|
|
|
1814
1912
|
await release();
|
|
1815
1913
|
};
|
|
1816
1914
|
try {
|
|
1817
|
-
closeControl = await serveControl(directory, { port: bridge.port, chat: !!execute, chatReason }, shutdown);
|
|
1915
|
+
closeControl = await serveControl(directory, { port: bridge.port, chat: !!execute, chatReason }, shutdown, issueCode);
|
|
1818
1916
|
} catch (error) {
|
|
1819
1917
|
await shutdown();
|
|
1820
1918
|
throw error;
|
package/dist/protocol.d.ts
CHANGED
|
@@ -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,10 +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.
|
|
27
|
+
declare const BRIDGE_VERSION = "1.1.2";
|
|
28
28
|
declare const PORTS: number[];
|
|
29
|
+
/** The only models bridges up to 1.1.0 accept. Newer bridges report capabilities.anyModel. */
|
|
29
30
|
declare const CLAUDE_MODELS: readonly ["default", "sonnet", "opus", "haiku"];
|
|
30
|
-
|
|
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
|
+
};
|
|
31
40
|
declare const AI_CLAIM = "enable:ai.assistant";
|
|
32
41
|
declare const MAX_MESSAGE_BYTES: number;
|
|
33
42
|
declare const RESOURCES: readonly ["companies", "devices", "studio", "media", "dashboard", "users", "users.login_history", "automations", "holidays", "app_store", "alterra", "media_log"];
|
|
@@ -98,12 +107,14 @@ type ResponseBody = {
|
|
|
98
107
|
connectionId: string;
|
|
99
108
|
paired: boolean;
|
|
100
109
|
clis: CliInfo[];
|
|
110
|
+
models?: ModelInfo[];
|
|
101
111
|
capabilities: {
|
|
102
112
|
localApproval?: boolean;
|
|
103
113
|
modelSelection?: boolean;
|
|
104
114
|
chat: boolean;
|
|
105
115
|
reason: 'preflight_required' | 'ready';
|
|
106
116
|
autostart?: boolean;
|
|
117
|
+
anyModel?: boolean;
|
|
107
118
|
};
|
|
108
119
|
} | {
|
|
109
120
|
type: 'pair.ok';
|
|
@@ -154,4 +165,4 @@ type BridgeResponse = ResponseBody & {
|
|
|
154
165
|
};
|
|
155
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';
|
|
156
167
|
|
|
157
|
-
export { AI_CLAIM, BRIDGE_VERSION, type BridgeRequest, type BridgeResponse, CLAUDE_MODELS, type ClaudeModel, type CliInfo, type ErrorCode, type Identity, MAX_MESSAGE_BYTES, PORTS, PROTOCOL_VERSION, RESOURCES, type RequestBody, type Resource, type ResponseBody };
|
|
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
|
@@ -2,15 +2,17 @@ import {
|
|
|
2
2
|
AI_CLAIM,
|
|
3
3
|
BRIDGE_VERSION,
|
|
4
4
|
CLAUDE_MODELS,
|
|
5
|
+
CLAUDE_MODEL_PATTERN,
|
|
5
6
|
MAX_MESSAGE_BYTES,
|
|
6
7
|
PORTS,
|
|
7
8
|
PROTOCOL_VERSION,
|
|
8
9
|
RESOURCES
|
|
9
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-LWN22TEE.js";
|
|
10
11
|
export {
|
|
11
12
|
AI_CLAIM,
|
|
12
13
|
BRIDGE_VERSION,
|
|
13
14
|
CLAUDE_MODELS,
|
|
15
|
+
CLAUDE_MODEL_PATTERN,
|
|
14
16
|
MAX_MESSAGE_BYTES,
|
|
15
17
|
PORTS,
|
|
16
18
|
PROTOCOL_VERSION,
|