@camstack/addon-terminal 0.1.31 → 0.1.33

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/dist/addon.js +657 -397
  2. package/dist/addon.mjs +657 -397
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -5833,6 +5833,13 @@ var BaseAddon = class {
5833
5833
  _readinessGeneration = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2, 14);
5834
5834
  /** Capability names this addon registered at init — used to emit matching `down` events on shutdown. */
5835
5835
  _registeredCapNames = [];
5836
+ /**
5837
+ * True only after `readAddonStore` actually answered. Constructor
5838
+ * defaults look like stored config when the store is down — a forked
5839
+ * addon that auto-starts from those defaults (cloudflare-tunnel quick
5840
+ * mode, 2026-08-25) is not "the operator chose this".
5841
+ */
5842
+ settingsStoreReady = false;
5836
5843
  /** Default config values. Provided via constructor. */
5837
5844
  defaults;
5838
5845
  constructor(defaults) {
@@ -6233,7 +6240,9 @@ var BaseAddon = class {
6233
6240
  ];
6234
6241
  let lastErr;
6235
6242
  for (let attempt = 0; attempt <= delaysMs.length; attempt++) try {
6236
- return await settings.readAddonStore() ?? {};
6243
+ const stored = await settings.readAddonStore() ?? {};
6244
+ this.settingsStoreReady = true;
6245
+ return stored;
6237
6246
  } catch (err) {
6238
6247
  lastErr = err;
6239
6248
  const msg = err instanceof Error ? err.message : String(err);
@@ -6241,6 +6250,7 @@ var BaseAddon = class {
6241
6250
  if (attempt === delaysMs.length) break;
6242
6251
  await new Promise((r) => setTimeout(r, delaysMs[attempt]));
6243
6252
  }
6253
+ this.settingsStoreReady = false;
6244
6254
  this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults", { meta: { error: lastErr instanceof Error ? lastErr.message : String(lastErr) } });
6245
6255
  return {};
6246
6256
  }
@@ -8119,6 +8129,15 @@ var LabelDefinitionSchema = object({
8119
8129
  description: string().optional(),
8120
8130
  icon: string().optional()
8121
8131
  });
8132
+ var ClassMapDefinitionSchema = object({
8133
+ mapping: record(string(), _enum([
8134
+ "person",
8135
+ "vehicle",
8136
+ "animal",
8137
+ "package"
8138
+ ])),
8139
+ preserveOriginal: boolean()
8140
+ });
8122
8141
  var MODEL_FORMATS = [
8123
8142
  "onnx",
8124
8143
  "coreml",
@@ -8202,6 +8221,12 @@ var ModelVariantGroupSchema = object({
8202
8221
  */
8203
8222
  resolution: number().int().positive().optional()
8204
8223
  });
8224
+ var ModelProviderIdSchema = _enum([
8225
+ "camstack",
8226
+ "frigate",
8227
+ "scrypted",
8228
+ "custom"
8229
+ ]);
8205
8230
  var ModelCatalogEntrySchema = object({
8206
8231
  id: string(),
8207
8232
  name: string(),
@@ -8297,7 +8322,19 @@ var ModelCatalogEntrySchema = object({
8297
8322
  * `id` stays the source of truth for resolution/download/persistence; grouping
8298
8323
  * is a presentation overlay resolved back to an `id`.
8299
8324
  */
8300
- group: ModelVariantGroupSchema.optional()
8325
+ group: ModelVariantGroupSchema.optional(),
8326
+ /**
8327
+ * Catalog source for the pipeline stepper's provider-first picker. Absent on
8328
+ * built-in CamStack entries (treated as `camstack`) and on registry rows
8329
+ * persisted before this field existed (`inferModelProvider` fills those).
8330
+ */
8331
+ provider: ModelProviderIdSchema.optional(),
8332
+ /**
8333
+ * Per-MODEL class map override. Absent ⇒ the step's `StepDefinition.classMap`
8334
+ * applies (Frigate / COCO public catalog). Set on a custom model whose raw
8335
+ * labels already ARE the CamStack macros (Scrypted identity map).
8336
+ */
8337
+ classMap: ClassMapDefinitionSchema.optional()
8301
8338
  });
8302
8339
  var ConvertTargetSchema = discriminatedUnion("format", [object({
8303
8340
  format: literal("openvino"),
@@ -8326,7 +8363,8 @@ var ModelConvertMetadataSchema = object({
8326
8363
  "ocr",
8327
8364
  "segmentation"
8328
8365
  ]),
8329
- faceAlignment: boolean().optional()
8366
+ faceAlignment: boolean().optional(),
8367
+ classMap: ClassMapDefinitionSchema.optional()
8330
8368
  });
8331
8369
  var ConvertResultSchema = object({
8332
8370
  entry: ModelCatalogEntrySchema,
@@ -12028,6 +12066,27 @@ var LinkedDeviceSchema = object({
12028
12066
  features: array(string()),
12029
12067
  producesTrackedEvents: boolean().optional()
12030
12068
  });
12069
+ /** One camera's resolved linked set, tagged with the camera it belongs to.
12070
+ * The batch answer needs the tag; the single-device answer already has it
12071
+ * from the input, which is why `getLinkedDevices` keeps the untagged shape. */
12072
+ var LinkedDevicesForDeviceSchema = object({
12073
+ deviceId: number(),
12074
+ mode: LinkedDevicesModeSchema,
12075
+ devices: array(LinkedDeviceSchema)
12076
+ });
12077
+ /** One device's binding map — the shape `getBindings`, `getBindingsBatch` and
12078
+ * `getAllBindings` all answer in. Declared once: three copies of the same
12079
+ * object literal is exactly how the three drift apart. */
12080
+ var DeviceBindingsForDeviceSchema = object({
12081
+ deviceId: number(),
12082
+ entries: array(object({
12083
+ capName: string(),
12084
+ kind: _enum(["native", "wrapped"]),
12085
+ providerAddonId: string(),
12086
+ providerNodeId: string(),
12087
+ nativeAddonId: string()
12088
+ }))
12089
+ });
12031
12090
  var SavedDeviceRowSchema = object({
12032
12091
  /** Numeric id reserved at allocateDeviceId time. */
12033
12092
  id: number(),
@@ -12253,11 +12312,25 @@ method(object({
12253
12312
  projection: _enum(["full", "slim"]).optional(),
12254
12313
  /** Return only camera devices. Filtering server-side instead of
12255
12314
  * shipping 293 rows to find 12. */
12256
- isCamera: boolean().optional()
12315
+ isCamera: boolean().optional(),
12316
+ /**
12317
+ * Return only these device ids. For the caller that already KNOWS the
12318
+ * handful it wants and needs a field the id-bearing answer does not
12319
+ * carry — the viewer's linked-devices panel joins `type` and `online`
12320
+ * onto ~8 linked ids and, unfiltered, dragged the fleet across to do
12321
+ * it: 433 KB slim / 958 KB full for 967 devices, on a query that
12322
+ * refetches on the reconcile interval, on a phone.
12323
+ *
12324
+ * Safe to send at a hub that predates it: Zod STRIPS unknown input
12325
+ * keys rather than rejecting them (verified against the live hub
12326
+ * 2026-08-25 — 967 rows came back), so an old hub answers exactly what
12327
+ * it answers today and the caller filters as it already does.
12328
+ */
12329
+ deviceIds: array(number()).optional()
12257
12330
  }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), DeviceInfoSchema.nullable()), method(object({ parentDeviceId: number() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), object({
12258
12331
  mode: LinkedDevicesModeSchema,
12259
12332
  devices: array(LinkedDeviceSchema)
12260
- })), method(object({ deviceId: number() }), array(StreamSourceEntrySchema$1)), method(object({ deviceId: number() }), array(ConfigEntrySchema)), method(object({ deviceId: number() }), ConfigUISchemaOutput), method(object({
12333
+ })), method(object({ deviceIds: array(number()) }), array(LinkedDevicesForDeviceSchema)), method(object({ deviceId: number() }), array(StreamSourceEntrySchema$1)), method(object({ deviceId: number() }), array(ConfigEntrySchema)), method(object({ deviceId: number() }), ConfigUISchemaOutput), method(object({
12261
12334
  deviceId: number(),
12262
12335
  values: record(string(), unknown())
12263
12336
  }), object({ success: literal(true) }), {
@@ -12284,25 +12357,7 @@ method(object({
12284
12357
  }), method(object({ deviceId: number() }), array(StreamProbeResultSchema), {
12285
12358
  kind: "mutation",
12286
12359
  auth: "admin"
12287
- }), method(object({ deviceId: number() }), object({
12288
- deviceId: number(),
12289
- entries: array(object({
12290
- capName: string(),
12291
- kind: _enum(["native", "wrapped"]),
12292
- providerAddonId: string(),
12293
- providerNodeId: string(),
12294
- nativeAddonId: string()
12295
- }))
12296
- })), method(object({}), array(object({
12297
- deviceId: number(),
12298
- entries: array(object({
12299
- capName: string(),
12300
- kind: _enum(["native", "wrapped"]),
12301
- providerAddonId: string(),
12302
- providerNodeId: string(),
12303
- nativeAddonId: string()
12304
- }))
12305
- }))), method(object({
12360
+ }), method(object({ deviceId: number() }), DeviceBindingsForDeviceSchema), method(object({ deviceIds: array(number()) }), array(DeviceBindingsForDeviceSchema)), method(object({}), array(DeviceBindingsForDeviceSchema)), method(object({
12306
12361
  deviceId: number(),
12307
12362
  capName: string(),
12308
12363
  wrapperAddonId: string(),
@@ -14712,12 +14767,15 @@ var NcOccupancyConditionSchema = object({
14712
14767
  * there is no second switch that can disagree with the first and every rule
14713
14768
  * authored before the decision migrates for free (`audioModeOf`):
14714
14769
  *
14715
- * - **LABEL mode — `labels` present.** The rule fires on the FIRST frame the
14716
- * classifier labels with one of them. No window, no percentage:
14717
- * `hitPercent` and `samplingSeconds` are ignored, and the rule's own
14718
- * `throttle` cooldown is the only brake. The per-label confidence floor is
14719
- * the analyzer's (`classificationMinScore`, per device) a label only
14720
- * reaches this condition if the classifier was already confident enough.
14770
+ * - **LABEL mode — `labels` present.** The rule fires when `confirmHits`
14771
+ * labelled frames land inside `confirmWindowSec` (default 2 in 5 s).
14772
+ * `hitPercent` and `samplingSeconds` are still ignored a percentage of
14773
+ * frames is the wrong question for a classifier that labels 1–3 frames
14774
+ * per episode. The count window is the brake that drops a single-frame
14775
+ * false positive; the rule's own `throttle` cooldown is the other. The
14776
+ * per-label confidence floor is the analyzer's (`classificationMinScore`,
14777
+ * per device) — a label only reaches this condition if the classifier was
14778
+ * already confident enough. `confirmHits: 1` restores first-frame fire.
14721
14779
  * - **LEVEL mode — `dbThreshold` present, no labels.** The sampling window IS
14722
14780
  * the condition: at least `hitPercent`% of the samples over
14723
14781
  * `samplingSeconds` must be at or above `dbThreshold` dBFS (see
@@ -14744,14 +14802,22 @@ var NcOccupancyConditionSchema = object({
14744
14802
  * an operator who typed `dog` mean the same thing.
14745
14803
  */
14746
14804
  var NcAudioConditionSchema = object({
14747
- /** LABEL MODE: audio macro labels. Present ⇒ fires on the first labelled frame. */
14805
+ /** LABEL MODE: audio macro labels. Present ⇒ count-in-window confirm. */
14748
14806
  labels: array(string().min(1)).min(1).optional(),
14749
14807
  /** LEVEL MODE: floor in dBFS (negative-going, `0` = full scale). */
14750
14808
  dbThreshold: number().min(-96).max(0).optional(),
14751
14809
  /** LEVEL MODE ONLY: percentage of the window's samples that must be hits (1–100). */
14752
14810
  hitPercent: number().int().min(1).max(100).default(60),
14753
14811
  /** LEVEL MODE ONLY: length of the sampling window in seconds. */
14754
- samplingSeconds: number().int().min(1).max(300).default(10)
14812
+ samplingSeconds: number().int().min(1).max(300).default(10),
14813
+ /**
14814
+ * LABEL MODE: how many labelled frames must land inside
14815
+ * {@link NcAudioConditionSchema.shape.confirmWindowSec} before dispatch.
14816
+ * Absent ⇒ 2 (the matcher default). `1` is first-frame fire.
14817
+ */
14818
+ confirmHits: number().int().min(1).max(20).optional(),
14819
+ /** LABEL MODE: the window those frames must share, in seconds. Absent ⇒ 5. */
14820
+ confirmWindowSec: number().int().min(1).max(60).optional()
14755
14821
  });
14756
14822
  /**
14757
14823
  * Which zone-crossing DIRECTION a rule accepts (`ObjectEvent.zoneCrossing`).
@@ -17125,6 +17191,46 @@ var RecentTracksPageSchema = object({
17125
17191
  /** Cursor for the next page, or null when this page is the last. */
17126
17192
  nextCursor: string().nullable()
17127
17193
  });
17194
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
17195
+ var LIST_GROUPS_MAX_LIMIT = 100;
17196
+ var AnalyticsGroupRecordSchema = object({
17197
+ id: string(),
17198
+ deviceId: number().int(),
17199
+ openedAt: number().int(),
17200
+ closedAt: number().int(),
17201
+ timestamp: number().int(),
17202
+ memberCount: number().int(),
17203
+ memberTrackIds: array(string()).readonly(),
17204
+ className: string(),
17205
+ classes: array(string()).readonly(),
17206
+ /** Relative event-media path, or null when the group has no picture yet. */
17207
+ mediaUrl: string().nullable(),
17208
+ singleton: boolean()
17209
+ });
17210
+ var AnalyticsGroupMemberSchema = object({
17211
+ trackId: string(),
17212
+ deviceId: number().int(),
17213
+ className: string(),
17214
+ firstSeen: number().int(),
17215
+ lastSeen: number().int(),
17216
+ mediaUrl: string().nullable()
17217
+ });
17218
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17219
+ var ListGroupsQueryInput = object({
17220
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17221
+ deviceIds: array(number()),
17222
+ /** Window lower bound on `closedAt` (inclusive). */
17223
+ since: number().optional(),
17224
+ /** Window upper bound on `openedAt` (inclusive). */
17225
+ until: number().optional(),
17226
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17227
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
17228
+ cursor: string().optional()
17229
+ });
17230
+ var ListGroupsPageSchema = object({
17231
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
17232
+ nextCursor: string().nullable()
17233
+ });
17128
17234
  var KeyEventQueryInput = object({
17129
17235
  deviceId: number(),
17130
17236
  /** Window lower bound (track firstSeen ≥ since). */
@@ -17200,7 +17306,9 @@ var TrackCascadeCountsSchema = object({
17200
17306
  /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
17201
17307
  plates: number().int(),
17202
17308
  /** Per-track CLIP search vectors removed (best-effort). */
17203
- embeddings: number().int()
17309
+ embeddings: number().int(),
17310
+ /** Group membership + group rows removed with their last member (best-effort). */
17311
+ groups: number().int()
17204
17312
  });
17205
17313
  /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
17206
17314
  var DiskReconcileCountsSchema = object({
@@ -17346,7 +17454,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
17346
17454
  * stationary registry). Default false: the timeline lists passages,
17347
17455
  * not parking records (operator decision, 2026-08-15). */
17348
17456
  includeStationary: boolean().optional()
17349
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(object({ deviceId: number() }), _void(), {
17457
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
17458
+ deviceId: number(),
17459
+ groupId: string().min(1)
17460
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
17350
17461
  kind: "mutation",
17351
17462
  auth: "admin"
17352
17463
  }), method(DeviceEventQueryInput, array(MotionEventSchema).readonly()), method(ObjectEventQueryInput, array(ObjectEventSchema).readonly()), method(DeviceEventQueryInput, array(AudioEventSchema).readonly()), method(object({ deviceId: number() }), array(EventKindDescriptorSchema).readonly()), method(object({ deviceIds: array(number()).min(1).max(200) }), array(EventKindsForDeviceSchema).readonly()), method(object({
@@ -17564,6 +17675,33 @@ var NativeCropRefSchema = object({
17564
17675
  h: number()
17565
17676
  })
17566
17677
  });
17678
+ object({
17679
+ crop: object({
17680
+ left: number(),
17681
+ top: number(),
17682
+ width: number().positive(),
17683
+ height: number().positive()
17684
+ }).optional(),
17685
+ content: object({
17686
+ width: number().int().positive(),
17687
+ height: number().int().positive()
17688
+ }),
17689
+ fit: _enum(["stretch", "contain"]),
17690
+ format: _enum([
17691
+ "rgb",
17692
+ "gray",
17693
+ "jpeg"
17694
+ ])
17695
+ });
17696
+ var FrameRefSchema = object({
17697
+ registryId: string().min(1),
17698
+ id: string().min(1),
17699
+ width: number().int().positive(),
17700
+ height: number().int().positive(),
17701
+ format: _enum(["rgb", "gray"]),
17702
+ timestamp: number(),
17703
+ capturedAt: number().optional()
17704
+ });
17567
17705
  var ModelFormatSchema$1 = _enum([
17568
17706
  "onnx",
17569
17707
  "coreml",
@@ -17629,7 +17767,8 @@ var PipelineModelOptionSchema = object({
17629
17767
  sizeMB: number()
17630
17768
  })),
17631
17769
  group: ModelVariantGroupSchema.optional(),
17632
- legacy: boolean().optional()
17770
+ legacy: boolean().optional(),
17771
+ provider: ModelProviderIdSchema.optional()
17633
17772
  });
17634
17773
  var ConfigFieldBridge = custom();
17635
17774
  var PipelineAddonSchemaSchema = object({
@@ -17808,6 +17947,12 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
17808
17947
  steps: array(PipelineStepInputSchema).min(1),
17809
17948
  frame: FrameInputSchema.optional(),
17810
17949
  /**
17950
+ * Process-local lazy frame. Valid only when caller and provider resolve
17951
+ * in the same execution-group process; split/cross-node callers use
17952
+ * `frame`/`image` inline compatibility instead.
17953
+ */
17954
+ frameRef: FrameRefSchema.optional(),
17955
+ /**
17811
17956
  * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
17812
17957
  * the decoded pixels live in. One more member of the one-of
17813
17958
  * frame/frameHandle/image/imageBase64/referenceImage group.
@@ -18103,7 +18248,10 @@ var NativeCropResultSchema = object({
18103
18248
  * Which source served this crop, so a quality-sensitive consumer (the native
18104
18249
  * `keyFrame`) can reject a degraded fallback:
18105
18250
  * - `native` — cut from the decode worker's retained NATIVE surface (the
18106
- * quality path).
18251
+ * quality path). A subject-tile serve is also native-resolution and stays
18252
+ * `native` here: the public enum cannot name `tile` without a breaking cap
18253
+ * change. Runner telemetry distinguishes lease vs tile via `source` on the
18254
+ * internal crop result (`nativeHits` vs `tileHits`).
18107
18255
  * - `ram-fullframe` — the native surface MISSED but the request was full-frame,
18108
18256
  * so the ≤640 RAM `RetainedFrameStore` served it (honest lower-res; legit for
18109
18257
  * the blank-frame guard / 640-snapshot resolve, NOT for the clean keyFrame).
@@ -18594,12 +18742,41 @@ var RunnerLocalLoadSchema = object({
18594
18742
  * legacy `OrchestratorMetricsSchema` shape so existing dashboards keep
18595
18743
  * working unchanged when they switch to reading from the runner cap.
18596
18744
  */
18745
+ var FrameLazyCountersSchema = object({
18746
+ framesDecoded: number(),
18747
+ framesAdmitted: number(),
18748
+ framesDroppedPixelFree: number(),
18749
+ viewsMaterialized: number(),
18750
+ viewsSkipped: number(),
18751
+ workerToRunnerBytes: number(),
18752
+ runnerToPoolRawBytes: number(),
18753
+ runnerToPoolJpegBytes: number(),
18754
+ onDemandFullFrameRequests: number(),
18755
+ onDemandCropRequests: number(),
18756
+ nativeHits: number(),
18757
+ nativeMisses: number(),
18758
+ tileHits: number(),
18759
+ tileMisses: number(),
18760
+ fallbackHits: number(),
18761
+ fallbackMisses: number(),
18762
+ retainedWritesAvoided: number(),
18763
+ residentRefs: number(),
18764
+ residentBytes: number(),
18765
+ releases: number(),
18766
+ evictions: number(),
18767
+ staleMisses: number()
18768
+ });
18769
+ var FrameLazyMetricsSchema = object({
18770
+ node: FrameLazyCountersSchema,
18771
+ cameras: array(FrameLazyCountersSchema.extend({ deviceId: number() }))
18772
+ });
18597
18773
  var RunnerLocalMetricsSchema = object({
18598
18774
  nodeId: string(),
18599
18775
  activeCameras: number(),
18600
18776
  throttledCameras: number(),
18601
18777
  avgInferenceTimeMs: number(),
18602
- queueDepth: number()
18778
+ queueDepth: number(),
18779
+ frameLazy: FrameLazyMetricsSchema.optional()
18603
18780
  });
18604
18781
  method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mutation" }), method(object({ deviceId: number() }), object({ success: literal(true) }), { kind: "mutation" }), method(ReportMotionInputSchema, object({ success: literal(true) }), { kind: "mutation" }), method(_void(), RunnerLocalLoadSchema), method(_void(), RunnerLocalMetricsSchema), method(object({ deviceId: number() }), CameraMetricsSchema.nullable()), method(_void(), array(CameraMetricsWithDeviceIdSchema).readonly()), method(_void(), array(number()).readonly()), method(object({
18605
18782
  handle: FrameHandleSchema,
@@ -24209,6 +24386,17 @@ var NotificationEndpointSchema = object({
24209
24386
  /** What the ranking currently resolves to (null when nothing is reachable). */
24210
24387
  resolved: string().nullable()
24211
24388
  });
24389
+ /**
24390
+ * The URLs the SDK / viewer should race for API access. `baseUrls` empty =
24391
+ * AUTO (every LAN IPv4 + the public tunnel). `resolved` is what that choice
24392
+ * currently expands to, so the UI can show the effective set either way.
24393
+ */
24394
+ var ViewerEndpointsSchema = object({
24395
+ /** The operator's explicit race set, or empty for AUTO. */
24396
+ baseUrls: array(string()).readonly(),
24397
+ /** What the ranking currently resolves to (may be empty if nothing is up). */
24398
+ resolved: array(string()).readonly()
24399
+ });
24212
24400
  var AllowedAddressesSchema = object({
24213
24401
  /**
24214
24402
  * Allowlist of interface addresses operators have explicitly opted
@@ -24240,17 +24428,18 @@ method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(obje
24240
24428
  */
24241
24429
  port: number().int().min(1).max(65535).optional(),
24242
24430
  /** Include `http(s)://127.0.0.1:<port>` as the lowest-priority
24243
- * candidate. Default `true`. */
24431
+ * candidate. Default `false` — loopback is not a client route. */
24244
24432
  includeLoopback: boolean().optional(),
24245
- /** Skip IPv6 entries. Some legacy clients can't parse them.
24246
- * Default `false`. */
24433
+ /** Skip IPv6 entries. Default `false` the palette includes stable
24434
+ * LAN IPv6 (ICE/WebRTC uses dual-stack regardless). Pass `true` to
24435
+ * hide them. The viewer HTTP/WS race is `getViewerEndpoints`. */
24247
24436
  ipv4Only: boolean().optional(),
24248
24437
  /** Scheme to emit for LAN/loopback URLs. Default `'http'`.
24249
24438
  * Pass `'https'` when the caller is itself loaded over HTTPS
24250
24439
  * to avoid mixed-content blocks in the browser. The public
24251
24440
  * tunnel always emits `https://` regardless. */
24252
24441
  scheme: _enum(["http", "https"]).optional()
24253
- }), GetConnectionEndpointsResultSchema), method(_void(), NotificationEndpointSchema), method(object({ baseUrl: string().nullable() }), NotificationEndpointSchema, { kind: "mutation" }), method(_void(), AllowedAddressesSchema), method(AllowedAddressesSchema, object({ success: literal(true) }), { kind: "mutation" }), method(_void(), AllowedAddressesSchema, { kind: "mutation" }), method(_void(), TlsStatusSchema), method(object({ reason: string().optional() }), TlsStatusSchema, {
24442
+ }), GetConnectionEndpointsResultSchema), method(_void(), NotificationEndpointSchema), method(object({ baseUrl: string().nullable() }), NotificationEndpointSchema, { kind: "mutation" }), method(_void(), ViewerEndpointsSchema), method(object({ baseUrls: array(string()).readonly() }), ViewerEndpointsSchema, { kind: "mutation" }), method(_void(), AllowedAddressesSchema), method(AllowedAddressesSchema, object({ success: literal(true) }), { kind: "mutation" }), method(_void(), AllowedAddressesSchema, { kind: "mutation" }), method(_void(), TlsStatusSchema), method(object({ reason: string().optional() }), TlsStatusSchema, {
24254
24443
  kind: "mutation",
24255
24444
  auth: "admin"
24256
24445
  }), method(object({
@@ -25824,7 +26013,12 @@ var PlateInfoSchema = object({
25824
26013
  plateBbox: BoundingBoxSchema.optional(),
25825
26014
  /** keyFrame parity: MediaStore key of the track's native-resolution key frame. */
25826
26015
  keyFrameMediaKey: string().optional(),
25827
- base64: string().optional()
26016
+ base64: string().optional(),
26017
+ /**
26018
+ * Same crop as a data-plane URL. `getPlateByTrack` returns this and
26019
+ * never inlines JPEG; `listPlates` still inlines for the admin-ui.
26020
+ */
26021
+ cropUrl: string().optional()
25828
26022
  });
25829
26023
  var MediaFileLiteSchema = object({
25830
26024
  key: string(),
@@ -31346,6 +31540,12 @@ Object.freeze({
31346
31540
  addonId: null,
31347
31541
  access: "view"
31348
31542
  },
31543
+ "deviceManager.getBindingsBatch": {
31544
+ capName: "device-manager",
31545
+ capScope: "system",
31546
+ addonId: null,
31547
+ access: "view"
31548
+ },
31349
31549
  "deviceManager.getChildren": {
31350
31550
  capName: "device-manager",
31351
31551
  capScope: "system",
@@ -31406,6 +31606,12 @@ Object.freeze({
31406
31606
  addonId: null,
31407
31607
  access: "view"
31408
31608
  },
31609
+ "deviceManager.getLinkedDevicesBatch": {
31610
+ capName: "device-manager",
31611
+ capScope: "system",
31612
+ addonId: null,
31613
+ access: "view"
31614
+ },
31409
31615
  "deviceManager.getRoleDisplayDefaults": {
31410
31616
  capName: "device-manager",
31411
31617
  capScope: "system",
@@ -32324,6 +32530,12 @@ Object.freeze({
32324
32530
  addonId: null,
32325
32531
  access: "view"
32326
32532
  },
32533
+ "localNetwork.getViewerEndpoints": {
32534
+ capName: "local-network",
32535
+ capScope: "system",
32536
+ addonId: null,
32537
+ access: "view"
32538
+ },
32327
32539
  "localNetwork.list": {
32328
32540
  capName: "local-network",
32329
32541
  capScope: "system",
@@ -32360,6 +32572,12 @@ Object.freeze({
32360
32572
  addonId: null,
32361
32573
  access: "create"
32362
32574
  },
32575
+ "localNetwork.setViewerEndpoints": {
32576
+ capName: "local-network",
32577
+ capScope: "system",
32578
+ addonId: null,
32579
+ access: "create"
32580
+ },
32363
32581
  "localNetwork.uploadCertificate": {
32364
32582
  capName: "local-network",
32365
32583
  capScope: "system",
@@ -33164,6 +33382,12 @@ Object.freeze({
33164
33382
  addonId: null,
33165
33383
  access: "view"
33166
33384
  },
33385
+ "pipelineAnalytics.getGroup": {
33386
+ capName: "pipeline-analytics",
33387
+ capScope: "device",
33388
+ addonId: null,
33389
+ access: "view"
33390
+ },
33167
33391
  "pipelineAnalytics.getKeyEvents": {
33168
33392
  capName: "pipeline-analytics",
33169
33393
  capScope: "device",
@@ -33248,6 +33472,12 @@ Object.freeze({
33248
33472
  addonId: null,
33249
33473
  access: "view"
33250
33474
  },
33475
+ "pipelineAnalytics.listGroups": {
33476
+ capName: "pipeline-analytics",
33477
+ capScope: "device",
33478
+ addonId: null,
33479
+ access: "view"
33480
+ },
33251
33481
  "pipelineAnalytics.listOpsLog": {
33252
33482
  capName: "pipeline-analytics",
33253
33483
  capScope: "device",
@@ -36029,6 +36259,11 @@ Object.freeze({
36029
36259
  form: "single",
36030
36260
  optional: false
36031
36261
  }],
36262
+ "deviceManager.getBindingsBatch": [{
36263
+ name: "deviceIds",
36264
+ form: "array",
36265
+ optional: false
36266
+ }],
36032
36267
  "deviceManager.getChildren": [{
36033
36268
  name: "parentDeviceId",
36034
36269
  form: "single",
@@ -36074,6 +36309,11 @@ Object.freeze({
36074
36309
  form: "single",
36075
36310
  optional: false
36076
36311
  }],
36312
+ "deviceManager.getLinkedDevicesBatch": [{
36313
+ name: "deviceIds",
36314
+ form: "array",
36315
+ optional: false
36316
+ }],
36077
36317
  "deviceManager.getSettingsSchema": [{
36078
36318
  name: "deviceId",
36079
36319
  form: "single",
@@ -36094,6 +36334,11 @@ Object.freeze({
36094
36334
  form: "single",
36095
36335
  optional: false
36096
36336
  }],
36337
+ "deviceManager.listAll": [{
36338
+ name: "deviceIds",
36339
+ form: "array",
36340
+ optional: true
36341
+ }],
36097
36342
  "deviceManager.loadConfig": [{
36098
36343
  name: "deviceId",
36099
36344
  form: "single",
@@ -36667,6 +36912,11 @@ Object.freeze({
36667
36912
  form: "single",
36668
36913
  optional: false
36669
36914
  }],
36915
+ "pipelineAnalytics.getGroup": [{
36916
+ name: "deviceId",
36917
+ form: "single",
36918
+ optional: false
36919
+ }],
36670
36920
  "pipelineAnalytics.getKeyEvents": [{
36671
36921
  name: "deviceId",
36672
36922
  form: "single",
@@ -36722,6 +36972,11 @@ Object.freeze({
36722
36972
  form: "array",
36723
36973
  optional: false
36724
36974
  }],
36975
+ "pipelineAnalytics.listGroups": [{
36976
+ name: "deviceIds",
36977
+ form: "array",
36978
+ optional: false
36979
+ }],
36725
36980
  "pipelineAnalytics.listOpsLog": [{
36726
36981
  name: "deviceId",
36727
36982
  form: "single",
@@ -38139,356 +38394,6 @@ async function silenceAnalysisFor(deps, deviceId) {
38139
38394
  if (failures.length > 0) throw new Error(`terminal camera ${deviceId}: could not switch off ${failures.length} analyzer(s) — it will run at full detection cost (${failures.join("; ")})`);
38140
38395
  }
38141
38396
  //#endregion
38142
- //#region src/terminal-camera-declarations.ts
38143
- /**
38144
- * Feed DeclaredDevices every live declaration plus one deterministic orphan
38145
- * batch. The generic sweep intentionally refuses an over-limit set; selecting
38146
- * a batch here drains large historical Terminal orphan sets across convergence
38147
- * passes without weakening that global safety guard.
38148
- */
38149
- function terminalCameraReconciliationIndex(rows, integrationId, declarations, managedStableIds = /* @__PURE__ */ new Set()) {
38150
- if (!integrationId) return [];
38151
- const declared = new Set(declarations.map((camera) => camera.stableId));
38152
- const owned = rows.filter((row) => row.integrationId === integrationId && (declared.has(row.stableId) || managedStableIds.has(row.stableId) || row.stableId.startsWith("terminal-camera-instance-")));
38153
- return [...owned.filter((row) => declared.has(row.stableId)), ...owned.filter((row) => !declared.has(row.stableId)).sort((left, right) => left.id - right.id).slice(0, 32)];
38154
- }
38155
- /** Explicit persisted instances, never the node × profile template matrix. */
38156
- function buildTerminalInstanceCameraDeclarations(instances) {
38157
- return instances.filter((instance) => instance.enabled).map((instance) => ({
38158
- stableId: instance.cameraStableId,
38159
- name: instance.name,
38160
- config: {
38161
- instanceId: instance.id,
38162
- nodeId: instance.nodeId,
38163
- profileId: instance.profileId,
38164
- profileLabel: instance.profileLabel
38165
- }
38166
- }));
38167
- }
38168
- /**
38169
- * `DeviceConfig` materializes schema defaults in memory, so comparing
38170
- * `config.get()` cannot detect a legacy `{ nodeId }` row. Reconciliation must
38171
- * inspect the raw persisted blob to make the profile migration durable.
38172
- */
38173
- function needsTerminalCameraConfigMigration(persistedConfig, declaration) {
38174
- return persistedConfig.instanceId !== declaration.config.instanceId || persistedConfig.nodeId !== declaration.config.nodeId || persistedConfig.profileId !== declaration.config.profileId || persistedConfig.profileLabel !== declaration.config.profileLabel;
38175
- }
38176
- //#endregion
38177
- //#region src/terminal-cell-runs.ts
38178
- var TERMINAL_DEFAULT_FG = "#d7dce2";
38179
- var TERMINAL_DEFAULT_BG = "#0b0d10";
38180
- /**
38181
- * The 16 ANSI colours, in a dark-theme variant chosen to sit with the existing
38182
- * frame (`#0b0d10` ground, `#d7dce2` text) rather than the raw xterm defaults,
38183
- * whose pure `#0000ff` blue and `#008000` green are close to unreadable on a
38184
- * near-black background at 13px. Index 7 IS the default foreground, so plain
38185
- * `CSI 37m` text renders identically to unstyled text.
38186
- */
38187
- var TERMINAL_ANSI_PALETTE = [
38188
- "#282c34",
38189
- "#e06c75",
38190
- "#98c379",
38191
- "#e5c07b",
38192
- "#61afef",
38193
- "#c678dd",
38194
- "#56b6c2",
38195
- TERMINAL_DEFAULT_FG,
38196
- "#5c6370",
38197
- "#ef596f",
38198
- "#89ca78",
38199
- "#f0c674",
38200
- "#6cb6ff",
38201
- "#d55fde",
38202
- "#2bbac5",
38203
- "#ffffff"
38204
- ];
38205
- /** The six levels of the xterm 6×6×6 colour cube (indices 16-231). */
38206
- var TERMINAL_CUBE_LEVELS = [
38207
- 0,
38208
- 95,
38209
- 135,
38210
- 175,
38211
- 215,
38212
- 255
38213
- ];
38214
- var TERMINAL_CUBE_FIRST = 16;
38215
- var TERMINAL_GRAYSCALE_FIRST = 232;
38216
- var TERMINAL_GRAYSCALE_BASE = 8;
38217
- var TERMINAL_GRAYSCALE_STEP = 10;
38218
- /** SGR 2 keeps the foreground legible; it must not become the background. */
38219
- var TERMINAL_DIM_WEIGHT = .6;
38220
- function channel(value) {
38221
- return Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0");
38222
- }
38223
- function hex(red, green, blue) {
38224
- return `#${channel(red)}${channel(green)}${channel(blue)}`;
38225
- }
38226
- function parseHex(color) {
38227
- return [
38228
- Number.parseInt(color.slice(1, 3), 16),
38229
- Number.parseInt(color.slice(3, 5), 16),
38230
- Number.parseInt(color.slice(5, 7), 16)
38231
- ];
38232
- }
38233
- /** Resolve an xterm palette index (0-255) to a hex colour. */
38234
- function terminalPaletteColor(index) {
38235
- const ansi = TERMINAL_ANSI_PALETTE[index];
38236
- if (ansi !== void 0) return ansi;
38237
- if (index >= TERMINAL_GRAYSCALE_FIRST) {
38238
- const level = TERMINAL_GRAYSCALE_BASE + (index - TERMINAL_GRAYSCALE_FIRST) * TERMINAL_GRAYSCALE_STEP;
38239
- return hex(level, level, level);
38240
- }
38241
- if (index >= TERMINAL_CUBE_FIRST) {
38242
- const offset = index - TERMINAL_CUBE_FIRST;
38243
- return hex(TERMINAL_CUBE_LEVELS[Math.floor(offset / 36) % 6] ?? 0, TERMINAL_CUBE_LEVELS[Math.floor(offset / 6) % 6] ?? 0, TERMINAL_CUBE_LEVELS[offset % 6] ?? 0);
38244
- }
38245
- return TERMINAL_DEFAULT_FG;
38246
- }
38247
- /** Resolve a 0xRRGGBB truecolor value to a hex colour. */
38248
- function terminalRgbColor(value) {
38249
- return hex(value >> 16 & 255, value >> 8 & 255, value & 255);
38250
- }
38251
- function blend(color, toward, weight) {
38252
- const [red, green, blue] = parseHex(color);
38253
- const [targetRed, targetGreen, targetBlue] = parseHex(toward);
38254
- return hex(red * weight + targetRed * (1 - weight), green * weight + targetGreen * (1 - weight), blue * weight + targetBlue * (1 - weight));
38255
- }
38256
- function resolveForeground(cell) {
38257
- if (cell.isFgRGB()) return terminalRgbColor(cell.getFgColor());
38258
- if (cell.isFgPalette()) return terminalPaletteColor(cell.getFgColor());
38259
- return TERMINAL_DEFAULT_FG;
38260
- }
38261
- function resolveBackground(cell) {
38262
- if (cell.isBgRGB()) return terminalRgbColor(cell.getBgColor());
38263
- if (cell.isBgPalette()) return terminalPaletteColor(cell.getBgColor());
38264
- return TERMINAL_DEFAULT_BG;
38265
- }
38266
- /**
38267
- * Resolve one cell's attributes into concrete colours.
38268
- *
38269
- * Inverse is applied by SWAPPING the already-resolved pair, so inverse over two
38270
- * defaults is still a visible swap rather than a no-op — that is how a selected
38271
- * or highlighted row in Glances reads. Invisible is then conceal-by-equality
38272
- * (foreground painted in its own background): the cell keeps its columns, which
38273
- * a dropped cell would not, and dropping it would shift the whole rest of the
38274
- * row left.
38275
- */
38276
- function resolveCellStyle(cell) {
38277
- const inverse = cell.isInverse() !== 0;
38278
- const plainFg = resolveForeground(cell);
38279
- const plainBg = resolveBackground(cell);
38280
- const background = inverse ? plainFg : plainBg;
38281
- let foreground = inverse ? plainBg : plainFg;
38282
- if (cell.isDim() !== 0) foreground = blend(foreground, background, TERMINAL_DIM_WEIGHT);
38283
- if (cell.isInvisible() !== 0) foreground = background;
38284
- return {
38285
- fg: foreground === "#d7dce2" ? null : foreground,
38286
- bg: background === "#0b0d10" ? null : background,
38287
- bold: cell.isBold() !== 0
38288
- };
38289
- }
38290
- function sameStyle(left, right) {
38291
- return left.fg === right.fg && left.bg === right.bg && left.bold === right.bold;
38292
- }
38293
- /**
38294
- * Merge adjacent same-style cells into runs, then drop the trailing run of
38295
- * default-styled whitespace so a row costs what it draws — the same trim
38296
- * `translateToString(true)` performs. Whitespace carrying a BACKGROUND is kept:
38297
- * a green bar of spaces out to the right margin is a pixel Glances drew.
38298
- */
38299
- function buildCellRuns(cells) {
38300
- const runs = [];
38301
- let text = "";
38302
- let style = null;
38303
- for (const cell of cells) {
38304
- if (style !== null && sameStyle(style, cell.style)) {
38305
- text += cell.text;
38306
- continue;
38307
- }
38308
- if (style !== null) runs.push({
38309
- text,
38310
- ...style
38311
- });
38312
- text = cell.text;
38313
- style = cell.style;
38314
- }
38315
- if (style !== null) runs.push({
38316
- text,
38317
- ...style
38318
- });
38319
- while (runs.length > 0) {
38320
- const last = runs[runs.length - 1];
38321
- if (last === void 0 || last.bg !== null) break;
38322
- const trimmed = last.text.replace(/\s+$/u, "");
38323
- if (trimmed === last.text) break;
38324
- if (trimmed === "") {
38325
- runs.pop();
38326
- continue;
38327
- }
38328
- runs[runs.length - 1] = {
38329
- ...last,
38330
- text: trimmed
38331
- };
38332
- break;
38333
- }
38334
- return runs;
38335
- }
38336
- /**
38337
- * Monospace families to try, in order — NOT one family and a generic.
38338
- *
38339
- * A terminal screen is mostly box-drawing and block characters, and a font
38340
- * without them renders the frame as noise rather than as missing detail.
38341
- * `DejaVu Sans Mono` covers them and ships in the hub image; macOS has neither
38342
- * DejaVu nor fontconfig, so the Mac agent fell through to a generic whose
38343
- * coverage is not, and its Glances camera came out unreadable while the hub's
38344
- * was pixel-perfect (measured 2026-08-11, same Glances, two nodes).
38345
- *
38346
- * `Menlo` is the fix rather than a guess: it is macOS's default terminal face,
38347
- * present on every install, and derived from DejaVu Sans Mono — the same glyph
38348
- * coverage by ancestry. Monaco and Courier New follow as older fallbacks; the
38349
- * generic stays last so a host with none of them still draws something.
38350
- */
38351
- var TERMINAL_FONT_STACK = "DejaVu Sans Mono,Menlo,Monaco,Courier New,monospace";
38352
- var TERMINAL_FONT_SIZE = 13;
38353
- var TERMINAL_TEXT_MARGIN_X = 8;
38354
- var TERMINAL_ROW_HEIGHT = 15;
38355
- var TERMINAL_BASELINE_Y = 18;
38356
- /**
38357
- * Distance from a row's baseline up to the top of its cell box. Chosen so
38358
- * consecutive rows tile exactly: row N's box runs from `baseline - this` for
38359
- * `TERMINAL_ROW_HEIGHT`, and row N+1's box starts where it ends. A background
38360
- * bar that stopped short would draw as stripes across a `CSI 42m` panel.
38361
- */
38362
- var TERMINAL_CELL_ASCENT = 11.5;
38363
- var TERMINAL_CELL_WIDTH = TERMINAL_FONT_SIZE * (1233 / 2048);
38364
- /** Two decimals is under a tenth of a pixel and keeps the SVG small. */
38365
- function coordinate(value) {
38366
- return String(Number(value.toFixed(2)));
38367
- }
38368
- function escapeXml(value) {
38369
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
38370
- }
38371
- /**
38372
- * Render already-interpreted terminal rows into a compact MJPEG frame.
38373
- *
38374
- * `xml:space="preserve"` is load-bearing, not tidiness. SVG `<text>` collapses
38375
- * runs of whitespace by default, and a terminal's entire column alignment IS
38376
- * runs of whitespace — Glances pads every field with spaces. Without it the
38377
- * frame drew each line at roughly half its true width, crammed into the
38378
- * top-left of a mostly-black image, while the SAME session over `attach`
38379
- * looked perfect — which is exactly how the operator reported it. Measured in
38380
- * the hub's own rasterizer 2026-08-11: `AAA<10 spaces>BBB<3>CCC` drew 92 px
38381
- * collapsed against 178 px preserved.
38382
- *
38383
- * Every run is anchored at its OWN column (`x = margin + startCol * cellW`),
38384
- * never appended to the one before it, so the background rects and the glyphs
38385
- * are placed off the same grid and cannot drift apart. `textLength` is emitted
38386
- * with it because it is the correct declaration and renderers that honour it
38387
- * get an exact grid — but it is not what makes this work: librsvg, which sharp
38388
- * uses, ignores it outright (measured 2026-08-12, a 120-glyph run pinned to
38389
- * 600 px still drew its natural 937 px). The anchoring is the guarantee.
38390
- */
38391
- function renderTerminalSvg(rows) {
38392
- const backgrounds = [];
38393
- const texts = [];
38394
- rows.slice(0, 40).forEach((row, index) => {
38395
- const baseline = TERMINAL_BASELINE_Y + index * TERMINAL_ROW_HEIGHT;
38396
- const top = baseline - TERMINAL_CELL_ASCENT;
38397
- let column = 0;
38398
- for (const run of row) {
38399
- if (column >= 120) break;
38400
- const clipped = clipRun(run, 120 - column);
38401
- const columns = [...clipped].length;
38402
- if (columns === 0) continue;
38403
- const x = TERMINAL_TEXT_MARGIN_X + column * TERMINAL_CELL_WIDTH;
38404
- const width = columns * TERMINAL_CELL_WIDTH;
38405
- if (run.bg !== null) backgrounds.push(`<rect x="${coordinate(x)}" y="${coordinate(top)}" width="${coordinate(width)}" height="${String(TERMINAL_ROW_HEIGHT)}" fill="${run.bg}"/>`);
38406
- if (clipped.trim() !== "") {
38407
- const fill = run.fg === null ? "" : ` fill="${run.fg}"`;
38408
- const weight = run.bold ? " font-weight=\"bold\"" : "";
38409
- texts.push(`<text xml:space="preserve" x="${coordinate(x)}" y="${coordinate(baseline)}" textLength="${coordinate(width)}" lengthAdjust="spacingAndGlyphs"${fill}${weight}>${escapeXml(clipped)}</text>`);
38410
- }
38411
- column += columns;
38412
- }
38413
- });
38414
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${String(960)}" height="${String(640)}"><rect width="100%" height="100%" fill="${TERMINAL_DEFAULT_BG}"/>${backgrounds.join("")}<g fill="${TERMINAL_DEFAULT_FG}" font-family="${TERMINAL_FONT_STACK}" font-size="${String(TERMINAL_FONT_SIZE)}">${texts.join("")}</g></svg>`;
38415
- }
38416
- /** Cut a run to the columns still left in the row, by code point not unit. */
38417
- function clipRun(run, remaining) {
38418
- const points = [...run.text];
38419
- return points.length <= remaining ? run.text : points.slice(0, remaining).join("");
38420
- }
38421
- async function renderTerminalJpeg(rows) {
38422
- return (0, sharp.default)(Buffer.from(renderTerminalSvg(rows))).jpeg({
38423
- quality: 82,
38424
- chromaSubsampling: "4:2:0"
38425
- }).toBuffer();
38426
- }
38427
- //#endregion
38428
- //#region src/terminal-camera-device.ts
38429
- var terminalCameraSchema = object({
38430
- instanceId: string().min(1).optional(),
38431
- nodeId: string().min(1),
38432
- profileId: string().min(1).default("monitor"),
38433
- profileLabel: string().min(1).default("BTM")
38434
- });
38435
- var relay = null;
38436
- function installTerminalCameraRelay(next) {
38437
- relay = next;
38438
- }
38439
- var TerminalCameraDevice = class extends BaseDevice {
38440
- features = [DeviceFeature.NativeSnapshot];
38441
- constructor(ctx) {
38442
- super(ctx, terminalCameraSchema, { type: ctx.deviceMeta.type });
38443
- this.ctx.registerNativeCap(streamCatalogCapability, { getCatalog: async ({ deviceId }) => {
38444
- if (deviceId !== this.id) return [];
38445
- return this.catalog();
38446
- } });
38447
- this.ctx.registerNativeCap(snapshotCapability, {
38448
- getSnapshot: async ({ deviceId }) => {
38449
- if (deviceId !== this.id) throw new Error(`TerminalCameraDevice: deviceId mismatch, expected ${String(this.id)}, got ${String(deviceId)}`);
38450
- const activeRelay = relay;
38451
- if (!activeRelay) throw new Error("terminal camera relay is unavailable");
38452
- return {
38453
- base64: (await activeRelay.snapshot(this.relayInstanceId(), this.config.get("nodeId"), this.config.get("profileId"))).toString("base64"),
38454
- contentType: "image/jpeg"
38455
- };
38456
- },
38457
- invalidateCache: async () => {}
38458
- });
38459
- this.markOnline(true);
38460
- }
38461
- async catalog() {
38462
- const activeRelay = relay;
38463
- if (!activeRelay) throw new Error("terminal camera relay is unavailable");
38464
- const nodeId = this.config.get("nodeId");
38465
- const profileId = this.config.get("profileId");
38466
- const instanceId = this.relayInstanceId();
38467
- return [{
38468
- camStreamId: profileId,
38469
- kind: "pull-http",
38470
- url: activeRelay.streamUrl(instanceId, nodeId, profileId),
38471
- codec: "h264",
38472
- resolution: {
38473
- width: 960,
38474
- height: 640
38475
- },
38476
- fps: 2,
38477
- label: this.config.get("profileLabel")
38478
- }];
38479
- }
38480
- setNodeOnline(online) {
38481
- this.markOnline(online);
38482
- if (!online) relay?.closeInstance(this.relayInstanceId());
38483
- }
38484
- async removeDevice() {
38485
- await relay?.closeInstance(this.relayInstanceId());
38486
- }
38487
- relayInstanceId() {
38488
- return this.config.get("instanceId") ?? `legacy:${this.stableId}`;
38489
- }
38490
- };
38491
- //#endregion
38492
38397
  //#region ../../node_modules/@xterm/addon-serialize/lib/addon-serialize.js
38493
38398
  var require_addon_serialize = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38494
38399
  (function(e, t) {
@@ -43296,11 +43201,176 @@ var require_xterm_headless = /* @__PURE__ */ __commonJSMin(((exports) => {
43296
43201
  })();
43297
43202
  }));
43298
43203
  //#endregion
43299
- //#region src/xterm-screen.ts
43204
+ //#region src/terminal-cell-runs.ts
43300
43205
  var import_addon_serialize = require_addon_serialize();
43301
43206
  var import_xterm_headless = require_xterm_headless();
43207
+ var TERMINAL_DEFAULT_FG = "#d7dce2";
43208
+ var TERMINAL_DEFAULT_BG = "#0b0d10";
43209
+ /**
43210
+ * The 16 ANSI colours, in a dark-theme variant chosen to sit with the existing
43211
+ * frame (`#0b0d10` ground, `#d7dce2` text) rather than the raw xterm defaults,
43212
+ * whose pure `#0000ff` blue and `#008000` green are close to unreadable on a
43213
+ * near-black background at 13px. Index 7 IS the default foreground, so plain
43214
+ * `CSI 37m` text renders identically to unstyled text.
43215
+ */
43216
+ var TERMINAL_ANSI_PALETTE = [
43217
+ "#282c34",
43218
+ "#e06c75",
43219
+ "#98c379",
43220
+ "#e5c07b",
43221
+ "#61afef",
43222
+ "#c678dd",
43223
+ "#56b6c2",
43224
+ TERMINAL_DEFAULT_FG,
43225
+ "#5c6370",
43226
+ "#ef596f",
43227
+ "#89ca78",
43228
+ "#f0c674",
43229
+ "#6cb6ff",
43230
+ "#d55fde",
43231
+ "#2bbac5",
43232
+ "#ffffff"
43233
+ ];
43234
+ /** The six levels of the xterm 6×6×6 colour cube (indices 16-231). */
43235
+ var TERMINAL_CUBE_LEVELS = [
43236
+ 0,
43237
+ 95,
43238
+ 135,
43239
+ 175,
43240
+ 215,
43241
+ 255
43242
+ ];
43243
+ var TERMINAL_CUBE_FIRST = 16;
43244
+ var TERMINAL_GRAYSCALE_FIRST = 232;
43245
+ var TERMINAL_GRAYSCALE_BASE = 8;
43246
+ var TERMINAL_GRAYSCALE_STEP = 10;
43247
+ /** SGR 2 keeps the foreground legible; it must not become the background. */
43248
+ var TERMINAL_DIM_WEIGHT = .6;
43249
+ function channel(value) {
43250
+ return Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0");
43251
+ }
43252
+ function hex(red, green, blue) {
43253
+ return `#${channel(red)}${channel(green)}${channel(blue)}`;
43254
+ }
43255
+ function parseHex(color) {
43256
+ return [
43257
+ Number.parseInt(color.slice(1, 3), 16),
43258
+ Number.parseInt(color.slice(3, 5), 16),
43259
+ Number.parseInt(color.slice(5, 7), 16)
43260
+ ];
43261
+ }
43262
+ /** Resolve an xterm palette index (0-255) to a hex colour. */
43263
+ function terminalPaletteColor(index) {
43264
+ const ansi = TERMINAL_ANSI_PALETTE[index];
43265
+ if (ansi !== void 0) return ansi;
43266
+ if (index >= TERMINAL_GRAYSCALE_FIRST) {
43267
+ const level = TERMINAL_GRAYSCALE_BASE + (index - TERMINAL_GRAYSCALE_FIRST) * TERMINAL_GRAYSCALE_STEP;
43268
+ return hex(level, level, level);
43269
+ }
43270
+ if (index >= TERMINAL_CUBE_FIRST) {
43271
+ const offset = index - TERMINAL_CUBE_FIRST;
43272
+ return hex(TERMINAL_CUBE_LEVELS[Math.floor(offset / 36) % 6] ?? 0, TERMINAL_CUBE_LEVELS[Math.floor(offset / 6) % 6] ?? 0, TERMINAL_CUBE_LEVELS[offset % 6] ?? 0);
43273
+ }
43274
+ return TERMINAL_DEFAULT_FG;
43275
+ }
43276
+ /** Resolve a 0xRRGGBB truecolor value to a hex colour. */
43277
+ function terminalRgbColor(value) {
43278
+ return hex(value >> 16 & 255, value >> 8 & 255, value & 255);
43279
+ }
43280
+ function blend(color, toward, weight) {
43281
+ const [red, green, blue] = parseHex(color);
43282
+ const [targetRed, targetGreen, targetBlue] = parseHex(toward);
43283
+ return hex(red * weight + targetRed * (1 - weight), green * weight + targetGreen * (1 - weight), blue * weight + targetBlue * (1 - weight));
43284
+ }
43285
+ function resolveForeground(cell) {
43286
+ if (cell.isFgRGB()) return terminalRgbColor(cell.getFgColor());
43287
+ if (cell.isFgPalette()) return terminalPaletteColor(cell.getFgColor());
43288
+ return TERMINAL_DEFAULT_FG;
43289
+ }
43290
+ function resolveBackground(cell) {
43291
+ if (cell.isBgRGB()) return terminalRgbColor(cell.getBgColor());
43292
+ if (cell.isBgPalette()) return terminalPaletteColor(cell.getBgColor());
43293
+ return TERMINAL_DEFAULT_BG;
43294
+ }
43295
+ /**
43296
+ * Resolve one cell's attributes into concrete colours.
43297
+ *
43298
+ * Inverse is applied by SWAPPING the already-resolved pair, so inverse over two
43299
+ * defaults is still a visible swap rather than a no-op — that is how a selected
43300
+ * or highlighted row in Glances reads. Invisible is then conceal-by-equality
43301
+ * (foreground painted in its own background): the cell keeps its columns, which
43302
+ * a dropped cell would not, and dropping it would shift the whole rest of the
43303
+ * row left.
43304
+ */
43305
+ function resolveCellStyle(cell) {
43306
+ const inverse = cell.isInverse() !== 0;
43307
+ const plainFg = resolveForeground(cell);
43308
+ const plainBg = resolveBackground(cell);
43309
+ const background = inverse ? plainFg : plainBg;
43310
+ let foreground = inverse ? plainBg : plainFg;
43311
+ if (cell.isDim() !== 0) foreground = blend(foreground, background, TERMINAL_DIM_WEIGHT);
43312
+ if (cell.isInvisible() !== 0) foreground = background;
43313
+ return {
43314
+ fg: foreground === "#d7dce2" ? null : foreground,
43315
+ bg: background === "#0b0d10" ? null : background,
43316
+ bold: cell.isBold() !== 0
43317
+ };
43318
+ }
43319
+ function sameStyle(left, right) {
43320
+ return left.fg === right.fg && left.bg === right.bg && left.bold === right.bold;
43321
+ }
43322
+ /**
43323
+ * Merge adjacent same-style cells into runs, then drop the trailing run of
43324
+ * default-styled whitespace so a row costs what it draws — the same trim
43325
+ * `translateToString(true)` performs. Whitespace carrying a BACKGROUND is kept:
43326
+ * a green bar of spaces out to the right margin is a pixel Glances drew.
43327
+ */
43328
+ function buildCellRuns(cells) {
43329
+ const runs = [];
43330
+ let text = "";
43331
+ let style = null;
43332
+ for (const cell of cells) {
43333
+ if (style !== null && sameStyle(style, cell.style)) {
43334
+ text += cell.text;
43335
+ continue;
43336
+ }
43337
+ if (style !== null) runs.push({
43338
+ text,
43339
+ ...style
43340
+ });
43341
+ text = cell.text;
43342
+ style = cell.style;
43343
+ }
43344
+ if (style !== null) runs.push({
43345
+ text,
43346
+ ...style
43347
+ });
43348
+ while (runs.length > 0) {
43349
+ const last = runs[runs.length - 1];
43350
+ if (last === void 0 || last.bg !== null) break;
43351
+ const trimmed = last.text.replace(/\s+$/u, "");
43352
+ if (trimmed === last.text) break;
43353
+ if (trimmed === "") {
43354
+ runs.pop();
43355
+ continue;
43356
+ }
43357
+ runs[runs.length - 1] = {
43358
+ ...last,
43359
+ text: trimmed
43360
+ };
43361
+ break;
43362
+ }
43363
+ return runs;
43364
+ }
43365
+ //#endregion
43366
+ //#region src/xterm-screen.ts
43367
+ /**
43368
+ * Real {@link ScreenBuffer} backed by `@xterm/headless` — the DOM-less xterm
43369
+ * build — plus the serialize addon, which turns the current buffer into a
43370
+ * self-contained repaint escape sequence for reconnecting clients.
43371
+ */
43302
43372
  var SCROLLBACK_LINES = 2e3;
43303
- function createXtermScreen$1(cols, rows) {
43373
+ function createXtermScreen(cols, rows) {
43304
43374
  const term = new import_xterm_headless.Terminal({
43305
43375
  cols,
43306
43376
  rows,
@@ -43365,6 +43435,196 @@ function createXtermScreen$1(cols, rows) {
43365
43435
  };
43366
43436
  }
43367
43437
  //#endregion
43438
+ //#region src/terminal-camera-declarations.ts
43439
+ /**
43440
+ * Feed DeclaredDevices every live declaration plus one deterministic orphan
43441
+ * batch. The generic sweep intentionally refuses an over-limit set; selecting
43442
+ * a batch here drains large historical Terminal orphan sets across convergence
43443
+ * passes without weakening that global safety guard.
43444
+ */
43445
+ function terminalCameraReconciliationIndex(rows, integrationId, declarations, managedStableIds = /* @__PURE__ */ new Set()) {
43446
+ if (!integrationId) return [];
43447
+ const declared = new Set(declarations.map((camera) => camera.stableId));
43448
+ const owned = rows.filter((row) => row.integrationId === integrationId && (declared.has(row.stableId) || managedStableIds.has(row.stableId) || row.stableId.startsWith("terminal-camera-instance-")));
43449
+ return [...owned.filter((row) => declared.has(row.stableId)), ...owned.filter((row) => !declared.has(row.stableId)).sort((left, right) => left.id - right.id).slice(0, 32)];
43450
+ }
43451
+ /** Explicit persisted instances, never the node × profile template matrix. */
43452
+ function buildTerminalInstanceCameraDeclarations(instances) {
43453
+ return instances.filter((instance) => instance.enabled).map((instance) => ({
43454
+ stableId: instance.cameraStableId,
43455
+ name: instance.name,
43456
+ config: {
43457
+ instanceId: instance.id,
43458
+ nodeId: instance.nodeId,
43459
+ profileId: instance.profileId,
43460
+ profileLabel: instance.profileLabel
43461
+ }
43462
+ }));
43463
+ }
43464
+ /**
43465
+ * `DeviceConfig` materializes schema defaults in memory, so comparing
43466
+ * `config.get()` cannot detect a legacy `{ nodeId }` row. Reconciliation must
43467
+ * inspect the raw persisted blob to make the profile migration durable.
43468
+ */
43469
+ function needsTerminalCameraConfigMigration(persistedConfig, declaration) {
43470
+ return persistedConfig.instanceId !== declaration.config.instanceId || persistedConfig.nodeId !== declaration.config.nodeId || persistedConfig.profileId !== declaration.config.profileId || persistedConfig.profileLabel !== declaration.config.profileLabel;
43471
+ }
43472
+ /**
43473
+ * Monospace families to try, in order — NOT one family and a generic.
43474
+ *
43475
+ * A terminal screen is mostly box-drawing and block characters, and a font
43476
+ * without them renders the frame as noise rather than as missing detail.
43477
+ * `DejaVu Sans Mono` covers them and ships in the hub image; macOS has neither
43478
+ * DejaVu nor fontconfig, so the Mac agent fell through to a generic whose
43479
+ * coverage is not, and its Glances camera came out unreadable while the hub's
43480
+ * was pixel-perfect (measured 2026-08-11, same Glances, two nodes).
43481
+ *
43482
+ * `Menlo` is the fix rather than a guess: it is macOS's default terminal face,
43483
+ * present on every install, and derived from DejaVu Sans Mono — the same glyph
43484
+ * coverage by ancestry. Monaco and Courier New follow as older fallbacks; the
43485
+ * generic stays last so a host with none of them still draws something.
43486
+ */
43487
+ var TERMINAL_FONT_STACK = "DejaVu Sans Mono,Menlo,Monaco,Courier New,monospace";
43488
+ var TERMINAL_FONT_SIZE = 13;
43489
+ var TERMINAL_TEXT_MARGIN_X = 8;
43490
+ var TERMINAL_ROW_HEIGHT = 15;
43491
+ var TERMINAL_BASELINE_Y = 18;
43492
+ /**
43493
+ * Distance from a row's baseline up to the top of its cell box. Chosen so
43494
+ * consecutive rows tile exactly: row N's box runs from `baseline - this` for
43495
+ * `TERMINAL_ROW_HEIGHT`, and row N+1's box starts where it ends. A background
43496
+ * bar that stopped short would draw as stripes across a `CSI 42m` panel.
43497
+ */
43498
+ var TERMINAL_CELL_ASCENT = 11.5;
43499
+ var TERMINAL_CELL_WIDTH = TERMINAL_FONT_SIZE * (1233 / 2048);
43500
+ /** Two decimals is under a tenth of a pixel and keeps the SVG small. */
43501
+ function coordinate(value) {
43502
+ return String(Number(value.toFixed(2)));
43503
+ }
43504
+ function escapeXml(value) {
43505
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
43506
+ }
43507
+ /**
43508
+ * Render already-interpreted terminal rows into a compact MJPEG frame.
43509
+ *
43510
+ * `xml:space="preserve"` is load-bearing, not tidiness. SVG `<text>` collapses
43511
+ * runs of whitespace by default, and a terminal's entire column alignment IS
43512
+ * runs of whitespace — Glances pads every field with spaces. Without it the
43513
+ * frame drew each line at roughly half its true width, crammed into the
43514
+ * top-left of a mostly-black image, while the SAME session over `attach`
43515
+ * looked perfect — which is exactly how the operator reported it. Measured in
43516
+ * the hub's own rasterizer 2026-08-11: `AAA<10 spaces>BBB<3>CCC` drew 92 px
43517
+ * collapsed against 178 px preserved.
43518
+ *
43519
+ * Every run is anchored at its OWN column (`x = margin + startCol * cellW`),
43520
+ * never appended to the one before it, so the background rects and the glyphs
43521
+ * are placed off the same grid and cannot drift apart. `textLength` is emitted
43522
+ * with it because it is the correct declaration and renderers that honour it
43523
+ * get an exact grid — but it is not what makes this work: librsvg, which sharp
43524
+ * uses, ignores it outright (measured 2026-08-12, a 120-glyph run pinned to
43525
+ * 600 px still drew its natural 937 px). The anchoring is the guarantee.
43526
+ */
43527
+ function renderTerminalSvg(rows) {
43528
+ const backgrounds = [];
43529
+ const texts = [];
43530
+ rows.slice(0, 40).forEach((row, index) => {
43531
+ const baseline = TERMINAL_BASELINE_Y + index * TERMINAL_ROW_HEIGHT;
43532
+ const top = baseline - TERMINAL_CELL_ASCENT;
43533
+ let column = 0;
43534
+ for (const run of row) {
43535
+ if (column >= 120) break;
43536
+ const clipped = clipRun(run, 120 - column);
43537
+ const columns = [...clipped].length;
43538
+ if (columns === 0) continue;
43539
+ const x = TERMINAL_TEXT_MARGIN_X + column * TERMINAL_CELL_WIDTH;
43540
+ const width = columns * TERMINAL_CELL_WIDTH;
43541
+ if (run.bg !== null) backgrounds.push(`<rect x="${coordinate(x)}" y="${coordinate(top)}" width="${coordinate(width)}" height="${String(TERMINAL_ROW_HEIGHT)}" fill="${run.bg}"/>`);
43542
+ if (clipped.trim() !== "") {
43543
+ const fill = run.fg === null ? "" : ` fill="${run.fg}"`;
43544
+ const weight = run.bold ? " font-weight=\"bold\"" : "";
43545
+ texts.push(`<text xml:space="preserve" x="${coordinate(x)}" y="${coordinate(baseline)}" textLength="${coordinate(width)}" lengthAdjust="spacingAndGlyphs"${fill}${weight}>${escapeXml(clipped)}</text>`);
43546
+ }
43547
+ column += columns;
43548
+ }
43549
+ });
43550
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${String(960)}" height="${String(640)}"><rect width="100%" height="100%" fill="${TERMINAL_DEFAULT_BG}"/>${backgrounds.join("")}<g fill="${TERMINAL_DEFAULT_FG}" font-family="${TERMINAL_FONT_STACK}" font-size="${String(TERMINAL_FONT_SIZE)}">${texts.join("")}</g></svg>`;
43551
+ }
43552
+ /** Cut a run to the columns still left in the row, by code point not unit. */
43553
+ function clipRun(run, remaining) {
43554
+ const points = [...run.text];
43555
+ return points.length <= remaining ? run.text : points.slice(0, remaining).join("");
43556
+ }
43557
+ async function renderTerminalJpeg(rows) {
43558
+ return (0, sharp.default)(Buffer.from(renderTerminalSvg(rows))).jpeg({
43559
+ quality: 82,
43560
+ chromaSubsampling: "4:2:0"
43561
+ }).toBuffer();
43562
+ }
43563
+ //#endregion
43564
+ //#region src/terminal-camera-device.ts
43565
+ var terminalCameraSchema = object({
43566
+ instanceId: string().min(1).optional(),
43567
+ nodeId: string().min(1),
43568
+ profileId: string().min(1).default("monitor"),
43569
+ profileLabel: string().min(1).default("BTM")
43570
+ });
43571
+ var relay = null;
43572
+ function installTerminalCameraRelay(next) {
43573
+ relay = next;
43574
+ }
43575
+ var TerminalCameraDevice = class extends BaseDevice {
43576
+ features = [DeviceFeature.NativeSnapshot];
43577
+ constructor(ctx) {
43578
+ super(ctx, terminalCameraSchema, { type: ctx.deviceMeta.type });
43579
+ this.ctx.registerNativeCap(streamCatalogCapability, { getCatalog: async ({ deviceId }) => {
43580
+ if (deviceId !== this.id) return [];
43581
+ return this.catalog();
43582
+ } });
43583
+ this.ctx.registerNativeCap(snapshotCapability, {
43584
+ getSnapshot: async ({ deviceId }) => {
43585
+ if (deviceId !== this.id) throw new Error(`TerminalCameraDevice: deviceId mismatch, expected ${String(this.id)}, got ${String(deviceId)}`);
43586
+ const activeRelay = relay;
43587
+ if (!activeRelay) throw new Error("terminal camera relay is unavailable");
43588
+ return {
43589
+ base64: (await activeRelay.snapshot(this.relayInstanceId(), this.config.get("nodeId"), this.config.get("profileId"))).toString("base64"),
43590
+ contentType: "image/jpeg"
43591
+ };
43592
+ },
43593
+ invalidateCache: async () => {}
43594
+ });
43595
+ this.markOnline(true);
43596
+ }
43597
+ async catalog() {
43598
+ const activeRelay = relay;
43599
+ if (!activeRelay) throw new Error("terminal camera relay is unavailable");
43600
+ const nodeId = this.config.get("nodeId");
43601
+ const profileId = this.config.get("profileId");
43602
+ const instanceId = this.relayInstanceId();
43603
+ return [{
43604
+ camStreamId: profileId,
43605
+ kind: "pull-http",
43606
+ url: activeRelay.streamUrl(instanceId, nodeId, profileId),
43607
+ codec: "h264",
43608
+ resolution: {
43609
+ width: 960,
43610
+ height: 640
43611
+ },
43612
+ fps: 2,
43613
+ label: this.config.get("profileLabel")
43614
+ }];
43615
+ }
43616
+ setNodeOnline(online) {
43617
+ this.markOnline(online);
43618
+ if (!online) relay?.closeInstance(this.relayInstanceId());
43619
+ }
43620
+ async removeDevice() {
43621
+ await relay?.closeInstance(this.relayInstanceId());
43622
+ }
43623
+ relayInstanceId() {
43624
+ return this.config.get("instanceId") ?? `legacy:${this.stableId}`;
43625
+ }
43626
+ };
43627
+ //#endregion
43368
43628
  //#region src/terminal-camera-relay.ts
43369
43629
  var MJPEG_BOUNDARY = "camstack-terminal-frame";
43370
43630
  var SESSION_IDLE_MS = 3e4;
@@ -43444,7 +43704,7 @@ var TerminalCameraRelay = class {
43444
43704
  instanceId,
43445
43705
  nodeId,
43446
43706
  profileId,
43447
- screen: createXtermScreen$1(120, 40),
43707
+ screen: createXtermScreen(120, 40),
43448
43708
  sessionId: null,
43449
43709
  cursor: 0,
43450
43710
  clients: 0,
@@ -43501,7 +43761,7 @@ var TerminalCameraRelay = class {
43501
43761
  applyBatch(state, batch) {
43502
43762
  if (batch.reset) {
43503
43763
  state.screen.dispose();
43504
- state.screen = createXtermScreen$1(120, 40);
43764
+ state.screen = createXtermScreen(120, 40);
43505
43765
  if (batch.snapshot) state.screen.write(batch.snapshot);
43506
43766
  }
43507
43767
  let exited = false;
@@ -45267,7 +45527,7 @@ exports.buildCellRuns = buildCellRuns;
45267
45527
  exports.buildProfiles = buildProfiles;
45268
45528
  exports.createNodePtySpawner = createNodePtySpawner;
45269
45529
  exports.createTerminalDataPlaneHandler = createTerminalDataPlaneHandler;
45270
- exports.createXtermScreen = createXtermScreen$1;
45530
+ exports.createXtermScreen = createXtermScreen;
45271
45531
  exports.findProfile = findProfile;
45272
45532
  exports.resolveCellStyle = resolveCellStyle;
45273
45533
  exports.terminalPaletteColor = terminalPaletteColor;