@dicamo/flint-ai-bridge 1.0.5 → 1.0.7

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.
Files changed (3) hide show
  1. package/README.md +5 -3
  2. package/dist/cli.js +58 -13
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -38,7 +38,7 @@ Stop the running bridge before changing these URLs.
38
38
  ### 2. Start the bridge
39
39
 
40
40
  ```sh
41
- npx @dicamo/flint-ai-bridge@1.0.5 start --enable-chat
41
+ npx @dicamo/flint-ai-bridge@latest start --enable-chat
42
42
  ```
43
43
 
44
44
  When chat is requested, startup checks Claude Code in a temporary directory and stops it after inspecting its initialization event. No CMS credentials or data are passed to this check. If the check fails, the bridge stays available for pairing and displays the reason chat is disabled. Retry by stopping and starting the bridge after resolving the issue.
@@ -71,8 +71,8 @@ The bridge does not reconnect automatically or save pairing credentials in the b
71
71
  Check the bridge status or stop it:
72
72
 
73
73
  ```sh
74
- npx @dicamo/flint-ai-bridge@1.0.5 status
75
- npx @dicamo/flint-ai-bridge@1.0.5 stop
74
+ npx @dicamo/flint-ai-bridge@latest status
75
+ npx @dicamo/flint-ai-bridge@latest stop
76
76
  ```
77
77
 
78
78
  Run `start --enable-chat` again after restarting your computer. The bridge does not register itself to start at login. Runtime errors and fallback pairing codes are written to `~/.flint-ai-bridge/bridge.log`. To view output directly in a terminal, use `serve --enable-chat` and press `Ctrl+C` to stop.
@@ -99,3 +99,5 @@ npx @dicamo/flint-ai-bridge@latest --help
99
99
  ```
100
100
 
101
101
  Snapshot metadata is available in device queries. If the server has snapshot analysis enabled, the assistant can filter dark-snapshot candidates across accessible devices. A dark image is not proof of a display failure; capture time and incomplete analysis must be considered.
102
+
103
+ On servers with snapshot image embeddings enabled, the assistant can find visually similar device snapshots using a reference device. Searches respect device permissions and return ranked matches, not a probability of a fault. Vector generation status is available separately; incomplete or stale embeddings are not searched.
package/dist/cli.js CHANGED
@@ -386,7 +386,7 @@ async function authenticate(options) {
386
386
  import { z as z4 } from "zod";
387
387
  var dataset = (name, label, resource, table, fields, scope, order = ["id"]) => ({ name, label, resource, table, fields: fields.split(","), ...scope, order });
388
388
  var CMS_DATASETS = [
389
- 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", { company: "company_id", store: "store_id" }),
389
+ 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" }),
390
390
  dataset("companies", "Companies", "companies", "companies", "id,encrypted_id,parent_id,name,contact,logo,created_at,updated_at", { company: "id" }),
391
391
  dataset("stores", "Stores", "companies", "stores", "id,encrypted_id,company_id,name,address,tz,tz_offset,open_time,close_time,reboot_time,contact,touch_log,media_log,enable_sleep,lat,lng,created_at", { company: "company_id", store: "id" }),
392
392
  dataset("media", "Media", "media", "media", "id,name,folder_id,mime,width,height,size,duration,created_at,created_by,company_id,encode_status,encode_progress,original_size,encoded_at,source_media_id,encode_preset", { company: "company_id" }),
@@ -404,7 +404,8 @@ var CMS_DATASETS = [
404
404
  dataset("holidays", "Store holidays", "holidays", "store_holiday", "store_id,date", { parent: { dataset: "stores", field: "store_id" } }, ["date", "store_id"]),
405
405
  dataset("holiday_overrides", "Store opening exceptions", "holidays", "store_holiday_override", "store_id,date", { parent: { dataset: "stores", field: "store_id" } }, ["date", "store_id"]),
406
406
  dataset("device_apps", "Installed apps across devices", "devices", "rpc/device_app_inventory", "id,device_id,name,package_name,version,version_code,installed_at,updated_at,device_name,company_id,store_id,online,service_version,service_version_code,player_app_version,player_app_version_code", { schema: "ai", company: "company_id", store: "store_id" }),
407
- dataset("device_snapshots", "Snapshot brightness analysis", "devices", "rpc/device_snapshot_status", "device_id,device_name,company_id,store_id,online,snapshot_path,captured_at,analysis_status,black_pixel_ratio,mean_luminance,black_screen_candidate,analyzed_at,sample_width,sample_height,algorithm,error_code", { schema: "ai", company: "company_id", store: "store_id" }, ["device_id"]),
407
+ dataset("device_snapshots", "Snapshot brightness analysis", "devices", "rpc/device_snapshot_status", "device_id,device_name,company_id,store_id,online,snapshot_path,captured_at,analysis_status,black_pixel_ratio,mean_luminance,black_screen_candidate,analyzed_at,sample_width,sample_height,algorithm,error_code,snapshot_url", { schema: "ai", company: "company_id", store: "store_id" }, ["device_id"]),
408
+ dataset("device_snapshot_vectors", "Snapshot vector generation status", "devices", "rpc/device_snapshot_vectors", "device_id,device_name,company_id,store_id,online,captured_at,embedding_status,embedding_model,embedded_at", { schema: "ai", company: "company_id", store: "store_id" }, ["device_id"]),
408
409
  dataset("device_notes", "Device notes", "devices", "device_notes", "id,device_id,body,created_by,created_at,updated_at", { parent: { dataset: "devices", field: "device_id" } }),
409
410
  dataset("scene_history", "Scene history", "studio", "scene_histories", "id,scene_id,action,name,description,changed_by,changed_at", { parent: { dataset: "scenes", field: "scene_id" } }),
410
411
  dataset("scene_time_slots", "Scene time slots", "studio", "v_scene_time_slots", "scene_id,slot,screen_index,screen_id,tv_screen_id,screen_label,width,height,media", { parent: { dataset: "scenes", field: "scene_id" } }, ["slot", "screen_index"]),
@@ -420,13 +421,15 @@ var queryArgs = z4.object({
420
421
  offset: z4.number().int().min(0).max(1e5).default(0),
421
422
  countOnly: z4.boolean().default(false)
422
423
  }).strict();
423
- 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. An image URL alone does not mean you have viewed or visually analysed it.";
424
+ 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 ![device snapshot](snapshot_url) 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.";
424
425
  var CATALOG_TOOLS = [
425
426
  { 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 } },
426
427
  { 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 } }
427
428
  ].map((tool) => ({ ...tool, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } }));
428
429
  var reportArgs = z4.object({ report: z4.enum(["dashboard", "media_log"]), companyIds: z4.array(z4.number().int().nonnegative()).min(1).max(100).optional(), storeId: z4.number().int().nonnegative().optional(), days: z4.number().int().min(1).max(90).default(7) }).strict();
429
430
  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 } };
431
+ var similarSnapshotArgs = z4.object({ deviceId: z4.string().min(1).max(256).regex(/^[^\u0000-\u001f\u007f]+$/), limit: z4.number().int().min(1).max(50).default(10), minSimilarity: z4.number().min(-1).max(1).default(0.8), online: z4.boolean().optional() }).strict();
432
+ 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 } };
430
433
 
431
434
  // src/cmsTools.ts
432
435
  var id = z5.number().int().nonnegative().safe();
@@ -439,9 +442,22 @@ var LEGACY_TOOLS = [
439
442
  { 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 } },
440
443
  { name: "list_companies", description: "Return the names and IDs of companies accessible to the current user.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }
441
444
  ].map((tool) => ({ ...tool, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } }));
442
- var CMS_TOOLS = [...LEGACY_TOOLS, ...CATALOG_TOOLS, REPORT_TOOL];
445
+ var CMS_TOOLS = [...LEGACY_TOOLS, ...CATALOG_TOOLS, REPORT_TOOL, SIMILAR_SNAPSHOT_TOOL];
443
446
  function toolResource(name) {
444
- return name === "list_companies" ? "companies" : name === "list_devices" || name === "get_device_status" ? "devices" : null;
447
+ return name === "list_companies" ? "companies" : name === "list_devices" || name === "get_device_status" || name === "find_similar_snapshots" ? "devices" : null;
448
+ }
449
+ function snapshotUrl(server, path, capturedAt) {
450
+ if (typeof path !== "string" || !path || path.length > 2048 || /^[a-z][a-z0-9+.-]*:/i.test(path) || /[\\\u0000-\u001f\u007f]/.test(path)) return null;
451
+ const parts = path.split("/");
452
+ if (parts.some((part) => !part || part === "." || part === "..")) return null;
453
+ try {
454
+ const url = new URL(`/storage/v1/object/public/device_captures/${parts.map((part) => encodeURIComponent(part).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)).join("/")}`, server);
455
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password) return null;
456
+ if (typeof capturedAt === "string" && capturedAt.length <= 100 && Number.isFinite(Date.parse(capturedAt))) url.searchParams.set("v", capturedAt);
457
+ return url.href;
458
+ } catch {
459
+ return null;
460
+ }
445
461
  }
446
462
  var CmsReadTools = class {
447
463
  options;
@@ -454,7 +470,11 @@ var CmsReadTools = class {
454
470
  async readPage(table, query, count2 = false, payload, schema2) {
455
471
  const o = this.options;
456
472
  o.assertActive();
457
- const response = await (o.fetch ?? fetch)(`${o.credentials.url}/rest/v1/${table}?${query}`, { method: payload ? "POST" : "GET", ...payload ? { body: JSON.stringify(payload) } : {}, headers: { "Content-Type": "application/json", apikey: o.credentials.anonKey, Authorization: `Bearer ${o.credentials.accessToken}`, ...schema2 ? { "Accept-Profile": schema2 } : {}, ...count2 ? { Prefer: "count=exact" } : {} }, redirect: "error", signal: AbortSignal.any([AbortSignal.timeout(8e3), ...o.signal ? [o.signal] : []]) });
473
+ const response = await (o.fetch ?? fetch)(`${o.credentials.url}/rest/v1/${table}?${query}`, { method: payload ? "POST" : "GET", ...payload ? { body: JSON.stringify(payload) } : {}, headers: { "Content-Type": "application/json", apikey: o.credentials.anonKey, Authorization: `Bearer ${o.credentials.accessToken}`, ...schema2 ? { "Accept-Profile": schema2, ...payload ? { "Content-Profile": schema2 } : {} } : {}, ...count2 ? { Prefer: "count=exact" } : {} }, redirect: "error", signal: AbortSignal.any([AbortSignal.timeout(8e3), ...o.signal ? [o.signal] : []]) });
474
+ if (!response.ok && table === "rpc/match_device_snapshots") {
475
+ await response.body?.cancel();
476
+ throw new Error(response.status === 404 ? "cms_snapshot_vectors_not_installed" : "cms_snapshot_similarity_unavailable");
477
+ }
458
478
  if (!response.ok) throw new Error(response.status === 404 && schema2 === "ai" && table === "rpc/device_app_inventory" ? "cms_device_apps_not_installed" : response.status === 404 && schema2 === "ai" && table === "rpc/device_snapshot_status" ? "cms_snapshot_analysis_not_installed" : "cms_query_failed");
459
479
  const reader = response.body?.getReader();
460
480
  if (!reader) throw new Error("cms_invalid_response");
@@ -527,7 +547,7 @@ var CmsReadTools = class {
527
547
  if (!d) throw new Error("cms_unknown_dataset");
528
548
  if (!parentCheck && !this.canRead(user, d.resource)) throw new Error("cms_tool_forbidden");
529
549
  const requested = input.fields ?? d.fields;
530
- if ([...requested, ...input.filters.map((f) => f.field), ...input.order.map((o) => o.field)].some((f) => !d.fields.includes(f))) throw new Error("cms_invalid_field");
550
+ if (requested.some((f) => !d.fields.includes(f)) || [...input.filters.map((f) => f.field), ...input.order.map((o) => o.field)].some((f) => f === "snapshot_url" || !d.fields.includes(f))) throw new Error("cms_invalid_field");
531
551
  const allowed = await this.scope(user);
532
552
  const stores = user.scope.super_user || user.scope.is_owner ? null : user.scope.store_ids;
533
553
  const countUnit = d.name === "device_apps" ? { countUnit: "installed_app_records" } : {};
@@ -539,7 +559,10 @@ var CmsReadTools = class {
539
559
  const parent = await this.queryDataset(queryArgs.parse({ dataset: d.parent.dataset, fields: ["id"], filters: [{ field: "id", op: "eq", value: filter.value }], limit: 1 }), user, true);
540
560
  if (!parent.rows.length) throw new Error("cms_scope_forbidden");
541
561
  }
542
- const checkedFields = [.../* @__PURE__ */ new Set([...requested, ...d.schema ? [...d.order, ...input.order.map((o) => o.field)] : [], ...d.company ? [d.company] : [], ...d.store ? [d.store] : [], ...d.parent ? [d.parent.field] : [], ...input.filters.filter((f) => f.op === "eq").map((f) => f.field)])];
562
+ const withSnapshotUrl = requested.includes("snapshot_url");
563
+ const sourceFields = requested.filter((field) => field !== "snapshot_url");
564
+ if (withSnapshotUrl) sourceFields.push(...d.name === "devices" ? ["device_snapshots"] : ["snapshot_path", "captured_at"]);
565
+ const checkedFields = [.../* @__PURE__ */ new Set([...sourceFields, ...d.schema ? [...d.order, ...input.order.map((o) => o.field)] : [], ...d.company ? [d.company] : [], ...d.store ? [d.store] : [], ...d.parent ? [d.parent.field] : [], ...input.filters.filter((f) => f.op === "eq").map((f) => f.field)])];
543
566
  const order = [...input.order, ...d.order.filter((field) => !input.order.some((o) => o.field === field)).map((field) => ({ field, direction: "asc" }))];
544
567
  const query = new URLSearchParams({ select: checkedFields.join(","), limit: String(input.countOnly ? 0 : input.limit + 1), offset: String(input.countOnly ? 0 : input.offset), order: order.map((o) => `${o.field}.${o.direction}.nullslast`).join(",") });
545
568
  if (d.company && allowed !== null) query.append(d.company, `in.(${[...allowed].join(",")})`);
@@ -559,7 +582,28 @@ var CmsReadTools = class {
559
582
  }
560
583
  }
561
584
  const hasMore = rows.length > input.limit;
562
- return { rows: rows.slice(0, input.limit).map((row) => Object.fromEntries(requested.filter((f) => Object.hasOwn(row, f)).map((f) => [f, row[f]]))), total: page.total, hasMore, nextOffset: hasMore ? input.offset + input.limit : null, ...countUnit };
585
+ return { rows: rows.slice(0, input.limit).map((row) => {
586
+ if (withSnapshotUrl) {
587
+ const metadata = d.name === "devices" ? row.device_snapshots : null;
588
+ const snapshot = metadata && typeof metadata === "object" && !Array.isArray(metadata) ? metadata : null;
589
+ row.snapshot_url = snapshotUrl(this.options.credentials.url, d.name === "devices" ? snapshot?.path : row.snapshot_path, d.name === "devices" ? snapshot?.updated_at : row.captured_at);
590
+ }
591
+ return Object.fromEntries(requested.filter((f) => Object.hasOwn(row, f)).map((f) => [f, row[f]]));
592
+ }), total: page.total, hasMore, nextOffset: hasMore ? input.offset + input.limit : null, ...countUnit };
593
+ }
594
+ async similarSnapshots(input, user) {
595
+ if (!this.canRead(user, "devices")) throw new Error("cms_tool_forbidden");
596
+ const parent = await this.queryDataset(queryArgs.parse({ dataset: "devices", fields: ["id"], filters: [{ field: "id", op: "eq", value: input.deviceId }], limit: 1 }), user, true);
597
+ if (!parent.rows.length) throw new Error("cms_scope_forbidden");
598
+ const allowed = await this.scope(user);
599
+ const stores = user.scope.super_user || user.scope.is_owner ? null : user.scope.store_ids;
600
+ 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");
601
+ const rows = z5.array(z5.object({ device_id: deviceId, device_name: z5.string().nullable(), company_id: id.nullable(), store_id: id.nullable(), online: z5.boolean(), captured_at: z5.string(), similarity: z5.number().finite().min(-1.000001).max(1.000001), embedding_model: z5.string() })).max(input.limit).parse(page.rows);
602
+ for (const row of rows) {
603
+ 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");
604
+ if (row.device_id === input.deviceId || row.similarity < input.minSimilarity || input.online !== void 0 && row.online !== input.online) throw new Error("cms_filter_violation");
605
+ }
606
+ return { referenceDeviceId: input.deviceId, rows, rankedMatches: true, exhaustive: false };
563
607
  }
564
608
  assertRowScope(d, row, allowed, stores) {
565
609
  if (d.company && allowed !== null && (typeof row[d.company] !== "number" || !allowed.has(row[d.company])) || d.store && stores !== null && (typeof row[d.store] !== "number" || !stores.includes(row[d.store]))) throw new Error("cms_scope_violation");
@@ -568,11 +612,12 @@ var CmsReadTools = class {
568
612
  const o = this.options;
569
613
  o.assertActive();
570
614
  if (!CMS_TOOLS.some((tool) => tool.name === name)) throw new Error("cms_unknown_tool");
571
- const parsed = name === "get_cms_report" ? reportArgs.parse(args) : name === "query_cms" ? queryArgs.parse(args) : name === "list_devices" ? listArgs.parse(args) : name === "get_device_status" ? z5.object({ deviceId }).strict().parse(args) : z5.object({}).strict().parse(args);
615
+ 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" ? z5.object({ deviceId }).strict().parse(args) : z5.object({}).strict().parse(args);
572
616
  const user = await (o.verify ?? verifySupabase)(o.credentials);
573
617
  o.assertActive();
574
618
  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");
575
619
  if (permissionsRevision(user) !== o.permissionsRevision) throw new Error("cms_permissions_changed");
620
+ if (name === "find_similar_snapshots") return this.similarSnapshots(parsed, user);
576
621
  if (name === "get_cms_report") return this.report(parsed, user);
577
622
  if (name === "describe_cms_queries") return { reports: ["dashboard", "media_log"].filter((r) => this.canRead(user, r)), deviceQueryGuidance: DEVICE_QUERY_GUIDANCE, datasets: CMS_DATASETS.filter((d) => this.canRead(user, d.resource)).map(({ name: name2, label, fields, parent }) => ({ name: name2, label, fields, ...name2 === "device_apps" ? { countUnit: "installed_app_records", bulkQuery: true } : {}, ...parent ? { requiredFilter: { field: parent.field, op: "eq", description: "Look up the parent resource ID first." } } : {} })), pagination: "Offset-based pagination. Data changes during retrieval may cause duplicates or omissions across pages." };
578
623
  if (name === "query_cms") return this.queryDataset(parsed, user);
@@ -656,7 +701,7 @@ async function startCmsMcp(options) {
656
701
  if (++calls > 64) throw new Error("tool_limit");
657
702
  const args = z6.object({ name: z6.string(), arguments: z6.unknown().optional(), _meta: z6.record(z6.string(), z6.unknown()).optional() }).strict().parse(input.params);
658
703
  if (!tools.some((tool) => tool.name === args.name)) throw new Error("tool_forbidden");
659
- const label = { 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];
704
+ 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];
660
705
  options.onActivity?.(`${label}: querying\u2026`);
661
706
  try {
662
707
  const value = await service.call(args.name, args.arguments ?? {});
@@ -668,7 +713,7 @@ async function startCmsMcp(options) {
668
713
  options.onActivity?.(`${label}: query failed`);
669
714
  const code = error instanceof Error ? error.message : "";
670
715
  const permission = ["cms_auth_changed", "cms_permissions_changed", "cms_tool_forbidden", "cms_scope_forbidden", "cms_scope_violation", "auth_forbidden"].includes(code);
671
- const message = 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 z6.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.";
716
+ 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 z6.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.";
672
717
  result = { isError: true, content: [{ type: "text", text: message + " Do not guess the query results." }] };
673
718
  }
674
719
  } else {
@@ -1206,7 +1251,7 @@ async function startBridge(options) {
1206
1251
  if (request.bridgeToken) throw new BridgeError("pair_required");
1207
1252
  reply({
1208
1253
  type: "hello.ok",
1209
- bridgeVersion: "1.0.5",
1254
+ bridgeVersion: "1.0.7",
1210
1255
  hostId: config.hostId,
1211
1256
  streamId,
1212
1257
  connectionId: peer.id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dicamo/flint-ai-bridge",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "Local CLI connection bridge for FLiNT CMS",
5
5
  "type": "module",
6
6
  "bin": {