@camstack/addon-terminal 0.1.30 → 0.1.32

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 +608 -375
  2. package/dist/addon.mjs +608 -375
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -8096,6 +8096,15 @@ var LabelDefinitionSchema = object({
8096
8096
  description: string().optional(),
8097
8097
  icon: string().optional()
8098
8098
  });
8099
+ var ClassMapDefinitionSchema = object({
8100
+ mapping: record(string(), _enum([
8101
+ "person",
8102
+ "vehicle",
8103
+ "animal",
8104
+ "package"
8105
+ ])),
8106
+ preserveOriginal: boolean()
8107
+ });
8099
8108
  var MODEL_FORMATS = [
8100
8109
  "onnx",
8101
8110
  "coreml",
@@ -8274,7 +8283,13 @@ var ModelCatalogEntrySchema = object({
8274
8283
  * `id` stays the source of truth for resolution/download/persistence; grouping
8275
8284
  * is a presentation overlay resolved back to an `id`.
8276
8285
  */
8277
- group: ModelVariantGroupSchema.optional()
8286
+ group: ModelVariantGroupSchema.optional(),
8287
+ /**
8288
+ * Per-MODEL class map override. Absent ⇒ the step's `StepDefinition.classMap`
8289
+ * applies (Frigate / COCO public catalog). Set on a custom model whose raw
8290
+ * labels already ARE the CamStack macros (Scrypted identity map).
8291
+ */
8292
+ classMap: ClassMapDefinitionSchema.optional()
8278
8293
  });
8279
8294
  var ConvertTargetSchema = discriminatedUnion("format", [object({
8280
8295
  format: literal("openvino"),
@@ -8303,7 +8318,8 @@ var ModelConvertMetadataSchema = object({
8303
8318
  "ocr",
8304
8319
  "segmentation"
8305
8320
  ]),
8306
- faceAlignment: boolean().optional()
8321
+ faceAlignment: boolean().optional(),
8322
+ classMap: ClassMapDefinitionSchema.optional()
8307
8323
  });
8308
8324
  var ConvertResultSchema = object({
8309
8325
  entry: ModelCatalogEntrySchema,
@@ -17541,6 +17557,33 @@ var NativeCropRefSchema = object({
17541
17557
  h: number()
17542
17558
  })
17543
17559
  });
17560
+ object({
17561
+ crop: object({
17562
+ left: number(),
17563
+ top: number(),
17564
+ width: number().positive(),
17565
+ height: number().positive()
17566
+ }).optional(),
17567
+ content: object({
17568
+ width: number().int().positive(),
17569
+ height: number().int().positive()
17570
+ }),
17571
+ fit: _enum(["stretch", "contain"]),
17572
+ format: _enum([
17573
+ "rgb",
17574
+ "gray",
17575
+ "jpeg"
17576
+ ])
17577
+ });
17578
+ var FrameRefSchema = object({
17579
+ registryId: string().min(1),
17580
+ id: string().min(1),
17581
+ width: number().int().positive(),
17582
+ height: number().int().positive(),
17583
+ format: _enum(["rgb", "gray"]),
17584
+ timestamp: number(),
17585
+ capturedAt: number().optional()
17586
+ });
17544
17587
  var ModelFormatSchema$1 = _enum([
17545
17588
  "onnx",
17546
17589
  "coreml",
@@ -17785,6 +17828,12 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
17785
17828
  steps: array(PipelineStepInputSchema).min(1),
17786
17829
  frame: FrameInputSchema.optional(),
17787
17830
  /**
17831
+ * Process-local lazy frame. Valid only when caller and provider resolve
17832
+ * in the same execution-group process; split/cross-node callers use
17833
+ * `frame`/`image` inline compatibility instead.
17834
+ */
17835
+ frameRef: FrameRefSchema.optional(),
17836
+ /**
17788
17837
  * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
17789
17838
  * the decoded pixels live in. One more member of the one-of
17790
17839
  * frame/frameHandle/image/imageBase64/referenceImage group.
@@ -18080,7 +18129,10 @@ var NativeCropResultSchema = object({
18080
18129
  * Which source served this crop, so a quality-sensitive consumer (the native
18081
18130
  * `keyFrame`) can reject a degraded fallback:
18082
18131
  * - `native` — cut from the decode worker's retained NATIVE surface (the
18083
- * quality path).
18132
+ * quality path). A subject-tile serve is also native-resolution and stays
18133
+ * `native` here: the public enum cannot name `tile` without a breaking cap
18134
+ * change. Runner telemetry distinguishes lease vs tile via `source` on the
18135
+ * internal crop result (`nativeHits` vs `tileHits`).
18084
18136
  * - `ram-fullframe` — the native surface MISSED but the request was full-frame,
18085
18137
  * so the ≤640 RAM `RetainedFrameStore` served it (honest lower-res; legit for
18086
18138
  * the blank-frame guard / 640-snapshot resolve, NOT for the clean keyFrame).
@@ -18571,12 +18623,41 @@ var RunnerLocalLoadSchema = object({
18571
18623
  * legacy `OrchestratorMetricsSchema` shape so existing dashboards keep
18572
18624
  * working unchanged when they switch to reading from the runner cap.
18573
18625
  */
18626
+ var FrameLazyCountersSchema = object({
18627
+ framesDecoded: number(),
18628
+ framesAdmitted: number(),
18629
+ framesDroppedPixelFree: number(),
18630
+ viewsMaterialized: number(),
18631
+ viewsSkipped: number(),
18632
+ workerToRunnerBytes: number(),
18633
+ runnerToPoolRawBytes: number(),
18634
+ runnerToPoolJpegBytes: number(),
18635
+ onDemandFullFrameRequests: number(),
18636
+ onDemandCropRequests: number(),
18637
+ nativeHits: number(),
18638
+ nativeMisses: number(),
18639
+ tileHits: number(),
18640
+ tileMisses: number(),
18641
+ fallbackHits: number(),
18642
+ fallbackMisses: number(),
18643
+ retainedWritesAvoided: number(),
18644
+ residentRefs: number(),
18645
+ residentBytes: number(),
18646
+ releases: number(),
18647
+ evictions: number(),
18648
+ staleMisses: number()
18649
+ });
18650
+ var FrameLazyMetricsSchema = object({
18651
+ node: FrameLazyCountersSchema,
18652
+ cameras: array(FrameLazyCountersSchema.extend({ deviceId: number() }))
18653
+ });
18574
18654
  var RunnerLocalMetricsSchema = object({
18575
18655
  nodeId: string(),
18576
18656
  activeCameras: number(),
18577
18657
  throttledCameras: number(),
18578
18658
  avgInferenceTimeMs: number(),
18579
- queueDepth: number()
18659
+ queueDepth: number(),
18660
+ frameLazy: FrameLazyMetricsSchema.optional()
18580
18661
  });
18581
18662
  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({
18582
18663
  handle: FrameHandleSchema,
@@ -19980,6 +20061,9 @@ method(_void(), ProviderInfoSchema), method(object({ config: record(string(), un
19980
20061
  location: StorageLocationSchema,
19981
20062
  relativePath: string()
19982
20063
  }), _void(), { kind: "mutation" }), method(object({ location: StorageLocationSchema }), number().nullable()), method(BeginUploadInputSchema, BeginUploadResultSchema, { kind: "mutation" }), method(WriteChunkInputSchema, _void(), { kind: "mutation" }), method(FinalizeUploadInputSchema, _void(), { kind: "mutation" }), method(AbortUploadInputSchema, _void(), { kind: "mutation" }), method(BeginDownloadInputSchema, BeginDownloadResultSchema, { kind: "mutation" }), method(ReadChunkInputSchema, _instanceof(Uint8Array)), method(EndDownloadInputSchema, _void(), { kind: "mutation" });
20064
+ /** Profile-exported FormBuilder schema. Shape is ConfigUISchema at the UI. */
20065
+ var ProfileSettingsSchemaBridge = unknown().nullable();
20066
+ var ProfileSettingsBagSchema = record(string(), unknown());
19983
20067
  /**
19984
20068
  * A live terminal session hosted by the provider addon. Output and input do
19985
20069
  * NOT flow through the capability — they use the addon data plane
@@ -20014,7 +20098,9 @@ var TerminalProfileInfoSchema = object({
20014
20098
  executable: string().optional(),
20015
20099
  args: array(string()).readonly().optional(),
20016
20100
  cwd: string().optional(),
20017
- environment: array(string()).readonly().optional()
20101
+ environment: array(string()).readonly().optional(),
20102
+ /** ConfigUISchema for instance knobs, or null when the profile has none. */
20103
+ settingsSchema: ProfileSettingsSchemaBridge.optional()
20018
20104
  });
20019
20105
  /**
20020
20106
  * A durable operator-created Terminal instance. Profiles are templates; only
@@ -20031,7 +20117,8 @@ var TerminalInstanceInfoSchema = object({
20031
20117
  executable: string(),
20032
20118
  args: array(string()).readonly(),
20033
20119
  cwd: string(),
20034
- environment: array(string()).readonly()
20120
+ environment: array(string()).readonly(),
20121
+ profileSettings: ProfileSettingsBagSchema
20035
20122
  });
20036
20123
  var TerminalLegacyCameraSchema = object({
20037
20124
  stableId: string(),
@@ -20081,7 +20168,8 @@ var terminalSessionCapability = {
20081
20168
  executable: string().max(1024).optional(),
20082
20169
  args: array(string().max(2048)).max(64).optional(),
20083
20170
  cwd: string().max(1024).optional(),
20084
- environment: array(string().max(4096)).max(64).optional()
20171
+ environment: array(string().max(4096)).max(64).optional(),
20172
+ profileSettings: ProfileSettingsBagSchema.optional()
20085
20173
  }), TerminalInstanceInfoSchema, {
20086
20174
  kind: "mutation",
20087
20175
  auth: "admin"
@@ -20092,7 +20180,8 @@ var terminalSessionCapability = {
20092
20180
  executable: string().max(1024).optional(),
20093
20181
  args: array(string().max(2048)).max(64).optional(),
20094
20182
  cwd: string().max(1024).optional(),
20095
- environment: array(string().max(4096)).max(64).optional()
20183
+ environment: array(string().max(4096)).max(64).optional(),
20184
+ profileSettings: ProfileSettingsBagSchema.optional()
20096
20185
  }), TerminalInstanceInfoSchema, {
20097
20186
  kind: "mutation",
20098
20187
  auth: "admin"
@@ -24020,10 +24109,10 @@ var lawnMowerControlCapability = {
24020
24109
  *
24021
24110
  * • The SDK (mobile / web client) consumes `getConnectionEndpoints()`
24022
24111
  * to receive an ordered list of candidate base URLs it should race
24023
- * on connect — LAN IPv4 first (lowest latency when on same network),
24024
- * then public hostname (if a tunnel is up), then IPv6. The SDK can
24025
- * race them with short timeouts and stick with the winner for the
24026
- * session.
24112
+ * on connect — LAN IPv4 and stable LAN IPv6 first (lowest latency
24113
+ * when on the same network), then public hostname (if a tunnel is
24114
+ * up). The SDK can race them with short timeouts and stick with the
24115
+ * winner for the session.
24027
24116
  *
24028
24117
  * Why hub-only: agents are not directly addressable by the operator's
24029
24118
  * clients — they reverse-connect to the hub. Exposing their interfaces
@@ -24178,6 +24267,17 @@ var NotificationEndpointSchema = object({
24178
24267
  /** What the ranking currently resolves to (null when nothing is reachable). */
24179
24268
  resolved: string().nullable()
24180
24269
  });
24270
+ /**
24271
+ * The URLs the SDK / viewer should race for API access. `baseUrls` empty =
24272
+ * AUTO (every LAN IPv4 + the public tunnel). `resolved` is what that choice
24273
+ * currently expands to, so the UI can show the effective set either way.
24274
+ */
24275
+ var ViewerEndpointsSchema = object({
24276
+ /** The operator's explicit race set, or empty for AUTO. */
24277
+ baseUrls: array(string()).readonly(),
24278
+ /** What the ranking currently resolves to (may be empty if nothing is up). */
24279
+ resolved: array(string()).readonly()
24280
+ });
24181
24281
  var AllowedAddressesSchema = object({
24182
24282
  /**
24183
24283
  * Allowlist of interface addresses operators have explicitly opted
@@ -24209,17 +24309,18 @@ method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(obje
24209
24309
  */
24210
24310
  port: number().int().min(1).max(65535).optional(),
24211
24311
  /** Include `http(s)://127.0.0.1:<port>` as the lowest-priority
24212
- * candidate. Default `true`. */
24312
+ * candidate. Default `false` — loopback is not a client route. */
24213
24313
  includeLoopback: boolean().optional(),
24214
- /** Skip IPv6 entries. Some legacy clients can't parse them.
24215
- * Default `false`. */
24314
+ /** Skip IPv6 entries. Default `false` the palette includes stable
24315
+ * LAN IPv6 (ICE/WebRTC uses dual-stack regardless). Pass `true` to
24316
+ * hide them. The viewer HTTP/WS race is `getViewerEndpoints`. */
24216
24317
  ipv4Only: boolean().optional(),
24217
24318
  /** Scheme to emit for LAN/loopback URLs. Default `'http'`.
24218
24319
  * Pass `'https'` when the caller is itself loaded over HTTPS
24219
24320
  * to avoid mixed-content blocks in the browser. The public
24220
24321
  * tunnel always emits `https://` regardless. */
24221
24322
  scheme: _enum(["http", "https"]).optional()
24222
- }), 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, {
24323
+ }), 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, {
24223
24324
  kind: "mutation",
24224
24325
  auth: "admin"
24225
24326
  }), method(object({
@@ -32293,6 +32394,12 @@ Object.freeze({
32293
32394
  addonId: null,
32294
32395
  access: "view"
32295
32396
  },
32397
+ "localNetwork.getViewerEndpoints": {
32398
+ capName: "local-network",
32399
+ capScope: "system",
32400
+ addonId: null,
32401
+ access: "view"
32402
+ },
32296
32403
  "localNetwork.list": {
32297
32404
  capName: "local-network",
32298
32405
  capScope: "system",
@@ -32329,6 +32436,12 @@ Object.freeze({
32329
32436
  addonId: null,
32330
32437
  access: "create"
32331
32438
  },
32439
+ "localNetwork.setViewerEndpoints": {
32440
+ capName: "local-network",
32441
+ capScope: "system",
32442
+ addonId: null,
32443
+ access: "create"
32444
+ },
32332
32445
  "localNetwork.uploadCertificate": {
32333
32446
  capName: "local-network",
32334
32447
  capScope: "system",
@@ -38108,356 +38221,6 @@ async function silenceAnalysisFor(deps, deviceId) {
38108
38221
  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("; ")})`);
38109
38222
  }
38110
38223
  //#endregion
38111
- //#region src/terminal-camera-declarations.ts
38112
- /**
38113
- * Feed DeclaredDevices every live declaration plus one deterministic orphan
38114
- * batch. The generic sweep intentionally refuses an over-limit set; selecting
38115
- * a batch here drains large historical Terminal orphan sets across convergence
38116
- * passes without weakening that global safety guard.
38117
- */
38118
- function terminalCameraReconciliationIndex(rows, integrationId, declarations, managedStableIds = /* @__PURE__ */ new Set()) {
38119
- if (!integrationId) return [];
38120
- const declared = new Set(declarations.map((camera) => camera.stableId));
38121
- const owned = rows.filter((row) => row.integrationId === integrationId && (declared.has(row.stableId) || managedStableIds.has(row.stableId) || row.stableId.startsWith("terminal-camera-instance-")));
38122
- 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)];
38123
- }
38124
- /** Explicit persisted instances, never the node × profile template matrix. */
38125
- function buildTerminalInstanceCameraDeclarations(instances) {
38126
- return instances.filter((instance) => instance.enabled).map((instance) => ({
38127
- stableId: instance.cameraStableId,
38128
- name: instance.name,
38129
- config: {
38130
- instanceId: instance.id,
38131
- nodeId: instance.nodeId,
38132
- profileId: instance.profileId,
38133
- profileLabel: instance.profileLabel
38134
- }
38135
- }));
38136
- }
38137
- /**
38138
- * `DeviceConfig` materializes schema defaults in memory, so comparing
38139
- * `config.get()` cannot detect a legacy `{ nodeId }` row. Reconciliation must
38140
- * inspect the raw persisted blob to make the profile migration durable.
38141
- */
38142
- function needsTerminalCameraConfigMigration(persistedConfig, declaration) {
38143
- return persistedConfig.instanceId !== declaration.config.instanceId || persistedConfig.nodeId !== declaration.config.nodeId || persistedConfig.profileId !== declaration.config.profileId || persistedConfig.profileLabel !== declaration.config.profileLabel;
38144
- }
38145
- //#endregion
38146
- //#region src/terminal-cell-runs.ts
38147
- var TERMINAL_DEFAULT_FG = "#d7dce2";
38148
- var TERMINAL_DEFAULT_BG = "#0b0d10";
38149
- /**
38150
- * The 16 ANSI colours, in a dark-theme variant chosen to sit with the existing
38151
- * frame (`#0b0d10` ground, `#d7dce2` text) rather than the raw xterm defaults,
38152
- * whose pure `#0000ff` blue and `#008000` green are close to unreadable on a
38153
- * near-black background at 13px. Index 7 IS the default foreground, so plain
38154
- * `CSI 37m` text renders identically to unstyled text.
38155
- */
38156
- var TERMINAL_ANSI_PALETTE = [
38157
- "#282c34",
38158
- "#e06c75",
38159
- "#98c379",
38160
- "#e5c07b",
38161
- "#61afef",
38162
- "#c678dd",
38163
- "#56b6c2",
38164
- TERMINAL_DEFAULT_FG,
38165
- "#5c6370",
38166
- "#ef596f",
38167
- "#89ca78",
38168
- "#f0c674",
38169
- "#6cb6ff",
38170
- "#d55fde",
38171
- "#2bbac5",
38172
- "#ffffff"
38173
- ];
38174
- /** The six levels of the xterm 6×6×6 colour cube (indices 16-231). */
38175
- var TERMINAL_CUBE_LEVELS = [
38176
- 0,
38177
- 95,
38178
- 135,
38179
- 175,
38180
- 215,
38181
- 255
38182
- ];
38183
- var TERMINAL_CUBE_FIRST = 16;
38184
- var TERMINAL_GRAYSCALE_FIRST = 232;
38185
- var TERMINAL_GRAYSCALE_BASE = 8;
38186
- var TERMINAL_GRAYSCALE_STEP = 10;
38187
- /** SGR 2 keeps the foreground legible; it must not become the background. */
38188
- var TERMINAL_DIM_WEIGHT = .6;
38189
- function channel(value) {
38190
- return Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0");
38191
- }
38192
- function hex(red, green, blue) {
38193
- return `#${channel(red)}${channel(green)}${channel(blue)}`;
38194
- }
38195
- function parseHex(color) {
38196
- return [
38197
- Number.parseInt(color.slice(1, 3), 16),
38198
- Number.parseInt(color.slice(3, 5), 16),
38199
- Number.parseInt(color.slice(5, 7), 16)
38200
- ];
38201
- }
38202
- /** Resolve an xterm palette index (0-255) to a hex colour. */
38203
- function terminalPaletteColor(index) {
38204
- const ansi = TERMINAL_ANSI_PALETTE[index];
38205
- if (ansi !== void 0) return ansi;
38206
- if (index >= TERMINAL_GRAYSCALE_FIRST) {
38207
- const level = TERMINAL_GRAYSCALE_BASE + (index - TERMINAL_GRAYSCALE_FIRST) * TERMINAL_GRAYSCALE_STEP;
38208
- return hex(level, level, level);
38209
- }
38210
- if (index >= TERMINAL_CUBE_FIRST) {
38211
- const offset = index - TERMINAL_CUBE_FIRST;
38212
- 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);
38213
- }
38214
- return TERMINAL_DEFAULT_FG;
38215
- }
38216
- /** Resolve a 0xRRGGBB truecolor value to a hex colour. */
38217
- function terminalRgbColor(value) {
38218
- return hex(value >> 16 & 255, value >> 8 & 255, value & 255);
38219
- }
38220
- function blend(color, toward, weight) {
38221
- const [red, green, blue] = parseHex(color);
38222
- const [targetRed, targetGreen, targetBlue] = parseHex(toward);
38223
- return hex(red * weight + targetRed * (1 - weight), green * weight + targetGreen * (1 - weight), blue * weight + targetBlue * (1 - weight));
38224
- }
38225
- function resolveForeground(cell) {
38226
- if (cell.isFgRGB()) return terminalRgbColor(cell.getFgColor());
38227
- if (cell.isFgPalette()) return terminalPaletteColor(cell.getFgColor());
38228
- return TERMINAL_DEFAULT_FG;
38229
- }
38230
- function resolveBackground(cell) {
38231
- if (cell.isBgRGB()) return terminalRgbColor(cell.getBgColor());
38232
- if (cell.isBgPalette()) return terminalPaletteColor(cell.getBgColor());
38233
- return TERMINAL_DEFAULT_BG;
38234
- }
38235
- /**
38236
- * Resolve one cell's attributes into concrete colours.
38237
- *
38238
- * Inverse is applied by SWAPPING the already-resolved pair, so inverse over two
38239
- * defaults is still a visible swap rather than a no-op — that is how a selected
38240
- * or highlighted row in Glances reads. Invisible is then conceal-by-equality
38241
- * (foreground painted in its own background): the cell keeps its columns, which
38242
- * a dropped cell would not, and dropping it would shift the whole rest of the
38243
- * row left.
38244
- */
38245
- function resolveCellStyle(cell) {
38246
- const inverse = cell.isInverse() !== 0;
38247
- const plainFg = resolveForeground(cell);
38248
- const plainBg = resolveBackground(cell);
38249
- const background = inverse ? plainFg : plainBg;
38250
- let foreground = inverse ? plainBg : plainFg;
38251
- if (cell.isDim() !== 0) foreground = blend(foreground, background, TERMINAL_DIM_WEIGHT);
38252
- if (cell.isInvisible() !== 0) foreground = background;
38253
- return {
38254
- fg: foreground === "#d7dce2" ? null : foreground,
38255
- bg: background === "#0b0d10" ? null : background,
38256
- bold: cell.isBold() !== 0
38257
- };
38258
- }
38259
- function sameStyle(left, right) {
38260
- return left.fg === right.fg && left.bg === right.bg && left.bold === right.bold;
38261
- }
38262
- /**
38263
- * Merge adjacent same-style cells into runs, then drop the trailing run of
38264
- * default-styled whitespace so a row costs what it draws — the same trim
38265
- * `translateToString(true)` performs. Whitespace carrying a BACKGROUND is kept:
38266
- * a green bar of spaces out to the right margin is a pixel Glances drew.
38267
- */
38268
- function buildCellRuns(cells) {
38269
- const runs = [];
38270
- let text = "";
38271
- let style = null;
38272
- for (const cell of cells) {
38273
- if (style !== null && sameStyle(style, cell.style)) {
38274
- text += cell.text;
38275
- continue;
38276
- }
38277
- if (style !== null) runs.push({
38278
- text,
38279
- ...style
38280
- });
38281
- text = cell.text;
38282
- style = cell.style;
38283
- }
38284
- if (style !== null) runs.push({
38285
- text,
38286
- ...style
38287
- });
38288
- while (runs.length > 0) {
38289
- const last = runs[runs.length - 1];
38290
- if (last === void 0 || last.bg !== null) break;
38291
- const trimmed = last.text.replace(/\s+$/u, "");
38292
- if (trimmed === last.text) break;
38293
- if (trimmed === "") {
38294
- runs.pop();
38295
- continue;
38296
- }
38297
- runs[runs.length - 1] = {
38298
- ...last,
38299
- text: trimmed
38300
- };
38301
- break;
38302
- }
38303
- return runs;
38304
- }
38305
- /**
38306
- * Monospace families to try, in order — NOT one family and a generic.
38307
- *
38308
- * A terminal screen is mostly box-drawing and block characters, and a font
38309
- * without them renders the frame as noise rather than as missing detail.
38310
- * `DejaVu Sans Mono` covers them and ships in the hub image; macOS has neither
38311
- * DejaVu nor fontconfig, so the Mac agent fell through to a generic whose
38312
- * coverage is not, and its Glances camera came out unreadable while the hub's
38313
- * was pixel-perfect (measured 2026-08-11, same Glances, two nodes).
38314
- *
38315
- * `Menlo` is the fix rather than a guess: it is macOS's default terminal face,
38316
- * present on every install, and derived from DejaVu Sans Mono — the same glyph
38317
- * coverage by ancestry. Monaco and Courier New follow as older fallbacks; the
38318
- * generic stays last so a host with none of them still draws something.
38319
- */
38320
- var TERMINAL_FONT_STACK = "DejaVu Sans Mono,Menlo,Monaco,Courier New,monospace";
38321
- var TERMINAL_FONT_SIZE = 13;
38322
- var TERMINAL_TEXT_MARGIN_X = 8;
38323
- var TERMINAL_ROW_HEIGHT = 15;
38324
- var TERMINAL_BASELINE_Y = 18;
38325
- /**
38326
- * Distance from a row's baseline up to the top of its cell box. Chosen so
38327
- * consecutive rows tile exactly: row N's box runs from `baseline - this` for
38328
- * `TERMINAL_ROW_HEIGHT`, and row N+1's box starts where it ends. A background
38329
- * bar that stopped short would draw as stripes across a `CSI 42m` panel.
38330
- */
38331
- var TERMINAL_CELL_ASCENT = 11.5;
38332
- var TERMINAL_CELL_WIDTH = TERMINAL_FONT_SIZE * (1233 / 2048);
38333
- /** Two decimals is under a tenth of a pixel and keeps the SVG small. */
38334
- function coordinate(value) {
38335
- return String(Number(value.toFixed(2)));
38336
- }
38337
- function escapeXml(value) {
38338
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
38339
- }
38340
- /**
38341
- * Render already-interpreted terminal rows into a compact MJPEG frame.
38342
- *
38343
- * `xml:space="preserve"` is load-bearing, not tidiness. SVG `<text>` collapses
38344
- * runs of whitespace by default, and a terminal's entire column alignment IS
38345
- * runs of whitespace — Glances pads every field with spaces. Without it the
38346
- * frame drew each line at roughly half its true width, crammed into the
38347
- * top-left of a mostly-black image, while the SAME session over `attach`
38348
- * looked perfect — which is exactly how the operator reported it. Measured in
38349
- * the hub's own rasterizer 2026-08-11: `AAA<10 spaces>BBB<3>CCC` drew 92 px
38350
- * collapsed against 178 px preserved.
38351
- *
38352
- * Every run is anchored at its OWN column (`x = margin + startCol * cellW`),
38353
- * never appended to the one before it, so the background rects and the glyphs
38354
- * are placed off the same grid and cannot drift apart. `textLength` is emitted
38355
- * with it because it is the correct declaration and renderers that honour it
38356
- * get an exact grid — but it is not what makes this work: librsvg, which sharp
38357
- * uses, ignores it outright (measured 2026-08-12, a 120-glyph run pinned to
38358
- * 600 px still drew its natural 937 px). The anchoring is the guarantee.
38359
- */
38360
- function renderTerminalSvg(rows) {
38361
- const backgrounds = [];
38362
- const texts = [];
38363
- rows.slice(0, 40).forEach((row, index) => {
38364
- const baseline = TERMINAL_BASELINE_Y + index * TERMINAL_ROW_HEIGHT;
38365
- const top = baseline - TERMINAL_CELL_ASCENT;
38366
- let column = 0;
38367
- for (const run of row) {
38368
- if (column >= 120) break;
38369
- const clipped = clipRun(run, 120 - column);
38370
- const columns = [...clipped].length;
38371
- if (columns === 0) continue;
38372
- const x = TERMINAL_TEXT_MARGIN_X + column * TERMINAL_CELL_WIDTH;
38373
- const width = columns * TERMINAL_CELL_WIDTH;
38374
- if (run.bg !== null) backgrounds.push(`<rect x="${coordinate(x)}" y="${coordinate(top)}" width="${coordinate(width)}" height="${String(TERMINAL_ROW_HEIGHT)}" fill="${run.bg}"/>`);
38375
- if (clipped.trim() !== "") {
38376
- const fill = run.fg === null ? "" : ` fill="${run.fg}"`;
38377
- const weight = run.bold ? " font-weight=\"bold\"" : "";
38378
- texts.push(`<text xml:space="preserve" x="${coordinate(x)}" y="${coordinate(baseline)}" textLength="${coordinate(width)}" lengthAdjust="spacingAndGlyphs"${fill}${weight}>${escapeXml(clipped)}</text>`);
38379
- }
38380
- column += columns;
38381
- }
38382
- });
38383
- 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>`;
38384
- }
38385
- /** Cut a run to the columns still left in the row, by code point not unit. */
38386
- function clipRun(run, remaining) {
38387
- const points = [...run.text];
38388
- return points.length <= remaining ? run.text : points.slice(0, remaining).join("");
38389
- }
38390
- async function renderTerminalJpeg(rows) {
38391
- return sharp(Buffer.from(renderTerminalSvg(rows))).jpeg({
38392
- quality: 82,
38393
- chromaSubsampling: "4:2:0"
38394
- }).toBuffer();
38395
- }
38396
- //#endregion
38397
- //#region src/terminal-camera-device.ts
38398
- var terminalCameraSchema = object({
38399
- instanceId: string().min(1).optional(),
38400
- nodeId: string().min(1),
38401
- profileId: string().min(1).default("monitor"),
38402
- profileLabel: string().min(1).default("BTM")
38403
- });
38404
- var relay = null;
38405
- function installTerminalCameraRelay(next) {
38406
- relay = next;
38407
- }
38408
- var TerminalCameraDevice = class extends BaseDevice {
38409
- features = [DeviceFeature.NativeSnapshot];
38410
- constructor(ctx) {
38411
- super(ctx, terminalCameraSchema, { type: ctx.deviceMeta.type });
38412
- this.ctx.registerNativeCap(streamCatalogCapability, { getCatalog: async ({ deviceId }) => {
38413
- if (deviceId !== this.id) return [];
38414
- return this.catalog();
38415
- } });
38416
- this.ctx.registerNativeCap(snapshotCapability, {
38417
- getSnapshot: async ({ deviceId }) => {
38418
- if (deviceId !== this.id) throw new Error(`TerminalCameraDevice: deviceId mismatch, expected ${String(this.id)}, got ${String(deviceId)}`);
38419
- const activeRelay = relay;
38420
- if (!activeRelay) throw new Error("terminal camera relay is unavailable");
38421
- return {
38422
- base64: (await activeRelay.snapshot(this.relayInstanceId(), this.config.get("nodeId"), this.config.get("profileId"))).toString("base64"),
38423
- contentType: "image/jpeg"
38424
- };
38425
- },
38426
- invalidateCache: async () => {}
38427
- });
38428
- this.markOnline(true);
38429
- }
38430
- async catalog() {
38431
- const activeRelay = relay;
38432
- if (!activeRelay) throw new Error("terminal camera relay is unavailable");
38433
- const nodeId = this.config.get("nodeId");
38434
- const profileId = this.config.get("profileId");
38435
- const instanceId = this.relayInstanceId();
38436
- return [{
38437
- camStreamId: profileId,
38438
- kind: "pull-http",
38439
- url: activeRelay.streamUrl(instanceId, nodeId, profileId),
38440
- codec: "h264",
38441
- resolution: {
38442
- width: 960,
38443
- height: 640
38444
- },
38445
- fps: 2,
38446
- label: this.config.get("profileLabel")
38447
- }];
38448
- }
38449
- setNodeOnline(online) {
38450
- this.markOnline(online);
38451
- if (!online) relay?.closeInstance(this.relayInstanceId());
38452
- }
38453
- async removeDevice() {
38454
- await relay?.closeInstance(this.relayInstanceId());
38455
- }
38456
- relayInstanceId() {
38457
- return this.config.get("instanceId") ?? `legacy:${this.stableId}`;
38458
- }
38459
- };
38460
- //#endregion
38461
38224
  //#region ../../node_modules/@xterm/addon-serialize/lib/addon-serialize.js
38462
38225
  var require_addon_serialize = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38463
38226
  (function(e, t) {
@@ -43265,9 +43028,174 @@ var require_xterm_headless = /* @__PURE__ */ __commonJSMin(((exports) => {
43265
43028
  })();
43266
43029
  }));
43267
43030
  //#endregion
43268
- //#region src/xterm-screen.ts
43031
+ //#region src/terminal-cell-runs.ts
43269
43032
  var import_addon_serialize = require_addon_serialize();
43270
43033
  var import_xterm_headless = require_xterm_headless();
43034
+ var TERMINAL_DEFAULT_FG = "#d7dce2";
43035
+ var TERMINAL_DEFAULT_BG = "#0b0d10";
43036
+ /**
43037
+ * The 16 ANSI colours, in a dark-theme variant chosen to sit with the existing
43038
+ * frame (`#0b0d10` ground, `#d7dce2` text) rather than the raw xterm defaults,
43039
+ * whose pure `#0000ff` blue and `#008000` green are close to unreadable on a
43040
+ * near-black background at 13px. Index 7 IS the default foreground, so plain
43041
+ * `CSI 37m` text renders identically to unstyled text.
43042
+ */
43043
+ var TERMINAL_ANSI_PALETTE = [
43044
+ "#282c34",
43045
+ "#e06c75",
43046
+ "#98c379",
43047
+ "#e5c07b",
43048
+ "#61afef",
43049
+ "#c678dd",
43050
+ "#56b6c2",
43051
+ TERMINAL_DEFAULT_FG,
43052
+ "#5c6370",
43053
+ "#ef596f",
43054
+ "#89ca78",
43055
+ "#f0c674",
43056
+ "#6cb6ff",
43057
+ "#d55fde",
43058
+ "#2bbac5",
43059
+ "#ffffff"
43060
+ ];
43061
+ /** The six levels of the xterm 6×6×6 colour cube (indices 16-231). */
43062
+ var TERMINAL_CUBE_LEVELS = [
43063
+ 0,
43064
+ 95,
43065
+ 135,
43066
+ 175,
43067
+ 215,
43068
+ 255
43069
+ ];
43070
+ var TERMINAL_CUBE_FIRST = 16;
43071
+ var TERMINAL_GRAYSCALE_FIRST = 232;
43072
+ var TERMINAL_GRAYSCALE_BASE = 8;
43073
+ var TERMINAL_GRAYSCALE_STEP = 10;
43074
+ /** SGR 2 keeps the foreground legible; it must not become the background. */
43075
+ var TERMINAL_DIM_WEIGHT = .6;
43076
+ function channel(value) {
43077
+ return Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0");
43078
+ }
43079
+ function hex(red, green, blue) {
43080
+ return `#${channel(red)}${channel(green)}${channel(blue)}`;
43081
+ }
43082
+ function parseHex(color) {
43083
+ return [
43084
+ Number.parseInt(color.slice(1, 3), 16),
43085
+ Number.parseInt(color.slice(3, 5), 16),
43086
+ Number.parseInt(color.slice(5, 7), 16)
43087
+ ];
43088
+ }
43089
+ /** Resolve an xterm palette index (0-255) to a hex colour. */
43090
+ function terminalPaletteColor(index) {
43091
+ const ansi = TERMINAL_ANSI_PALETTE[index];
43092
+ if (ansi !== void 0) return ansi;
43093
+ if (index >= TERMINAL_GRAYSCALE_FIRST) {
43094
+ const level = TERMINAL_GRAYSCALE_BASE + (index - TERMINAL_GRAYSCALE_FIRST) * TERMINAL_GRAYSCALE_STEP;
43095
+ return hex(level, level, level);
43096
+ }
43097
+ if (index >= TERMINAL_CUBE_FIRST) {
43098
+ const offset = index - TERMINAL_CUBE_FIRST;
43099
+ 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);
43100
+ }
43101
+ return TERMINAL_DEFAULT_FG;
43102
+ }
43103
+ /** Resolve a 0xRRGGBB truecolor value to a hex colour. */
43104
+ function terminalRgbColor(value) {
43105
+ return hex(value >> 16 & 255, value >> 8 & 255, value & 255);
43106
+ }
43107
+ function blend(color, toward, weight) {
43108
+ const [red, green, blue] = parseHex(color);
43109
+ const [targetRed, targetGreen, targetBlue] = parseHex(toward);
43110
+ return hex(red * weight + targetRed * (1 - weight), green * weight + targetGreen * (1 - weight), blue * weight + targetBlue * (1 - weight));
43111
+ }
43112
+ function resolveForeground(cell) {
43113
+ if (cell.isFgRGB()) return terminalRgbColor(cell.getFgColor());
43114
+ if (cell.isFgPalette()) return terminalPaletteColor(cell.getFgColor());
43115
+ return TERMINAL_DEFAULT_FG;
43116
+ }
43117
+ function resolveBackground(cell) {
43118
+ if (cell.isBgRGB()) return terminalRgbColor(cell.getBgColor());
43119
+ if (cell.isBgPalette()) return terminalPaletteColor(cell.getBgColor());
43120
+ return TERMINAL_DEFAULT_BG;
43121
+ }
43122
+ /**
43123
+ * Resolve one cell's attributes into concrete colours.
43124
+ *
43125
+ * Inverse is applied by SWAPPING the already-resolved pair, so inverse over two
43126
+ * defaults is still a visible swap rather than a no-op — that is how a selected
43127
+ * or highlighted row in Glances reads. Invisible is then conceal-by-equality
43128
+ * (foreground painted in its own background): the cell keeps its columns, which
43129
+ * a dropped cell would not, and dropping it would shift the whole rest of the
43130
+ * row left.
43131
+ */
43132
+ function resolveCellStyle(cell) {
43133
+ const inverse = cell.isInverse() !== 0;
43134
+ const plainFg = resolveForeground(cell);
43135
+ const plainBg = resolveBackground(cell);
43136
+ const background = inverse ? plainFg : plainBg;
43137
+ let foreground = inverse ? plainBg : plainFg;
43138
+ if (cell.isDim() !== 0) foreground = blend(foreground, background, TERMINAL_DIM_WEIGHT);
43139
+ if (cell.isInvisible() !== 0) foreground = background;
43140
+ return {
43141
+ fg: foreground === "#d7dce2" ? null : foreground,
43142
+ bg: background === "#0b0d10" ? null : background,
43143
+ bold: cell.isBold() !== 0
43144
+ };
43145
+ }
43146
+ function sameStyle(left, right) {
43147
+ return left.fg === right.fg && left.bg === right.bg && left.bold === right.bold;
43148
+ }
43149
+ /**
43150
+ * Merge adjacent same-style cells into runs, then drop the trailing run of
43151
+ * default-styled whitespace so a row costs what it draws — the same trim
43152
+ * `translateToString(true)` performs. Whitespace carrying a BACKGROUND is kept:
43153
+ * a green bar of spaces out to the right margin is a pixel Glances drew.
43154
+ */
43155
+ function buildCellRuns(cells) {
43156
+ const runs = [];
43157
+ let text = "";
43158
+ let style = null;
43159
+ for (const cell of cells) {
43160
+ if (style !== null && sameStyle(style, cell.style)) {
43161
+ text += cell.text;
43162
+ continue;
43163
+ }
43164
+ if (style !== null) runs.push({
43165
+ text,
43166
+ ...style
43167
+ });
43168
+ text = cell.text;
43169
+ style = cell.style;
43170
+ }
43171
+ if (style !== null) runs.push({
43172
+ text,
43173
+ ...style
43174
+ });
43175
+ while (runs.length > 0) {
43176
+ const last = runs[runs.length - 1];
43177
+ if (last === void 0 || last.bg !== null) break;
43178
+ const trimmed = last.text.replace(/\s+$/u, "");
43179
+ if (trimmed === last.text) break;
43180
+ if (trimmed === "") {
43181
+ runs.pop();
43182
+ continue;
43183
+ }
43184
+ runs[runs.length - 1] = {
43185
+ ...last,
43186
+ text: trimmed
43187
+ };
43188
+ break;
43189
+ }
43190
+ return runs;
43191
+ }
43192
+ //#endregion
43193
+ //#region src/xterm-screen.ts
43194
+ /**
43195
+ * Real {@link ScreenBuffer} backed by `@xterm/headless` — the DOM-less xterm
43196
+ * build — plus the serialize addon, which turns the current buffer into a
43197
+ * self-contained repaint escape sequence for reconnecting clients.
43198
+ */
43271
43199
  var SCROLLBACK_LINES = 2e3;
43272
43200
  function createXtermScreen(cols, rows) {
43273
43201
  const term = new import_xterm_headless.Terminal({
@@ -43334,6 +43262,196 @@ function createXtermScreen(cols, rows) {
43334
43262
  };
43335
43263
  }
43336
43264
  //#endregion
43265
+ //#region src/terminal-camera-declarations.ts
43266
+ /**
43267
+ * Feed DeclaredDevices every live declaration plus one deterministic orphan
43268
+ * batch. The generic sweep intentionally refuses an over-limit set; selecting
43269
+ * a batch here drains large historical Terminal orphan sets across convergence
43270
+ * passes without weakening that global safety guard.
43271
+ */
43272
+ function terminalCameraReconciliationIndex(rows, integrationId, declarations, managedStableIds = /* @__PURE__ */ new Set()) {
43273
+ if (!integrationId) return [];
43274
+ const declared = new Set(declarations.map((camera) => camera.stableId));
43275
+ const owned = rows.filter((row) => row.integrationId === integrationId && (declared.has(row.stableId) || managedStableIds.has(row.stableId) || row.stableId.startsWith("terminal-camera-instance-")));
43276
+ 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)];
43277
+ }
43278
+ /** Explicit persisted instances, never the node × profile template matrix. */
43279
+ function buildTerminalInstanceCameraDeclarations(instances) {
43280
+ return instances.filter((instance) => instance.enabled).map((instance) => ({
43281
+ stableId: instance.cameraStableId,
43282
+ name: instance.name,
43283
+ config: {
43284
+ instanceId: instance.id,
43285
+ nodeId: instance.nodeId,
43286
+ profileId: instance.profileId,
43287
+ profileLabel: instance.profileLabel
43288
+ }
43289
+ }));
43290
+ }
43291
+ /**
43292
+ * `DeviceConfig` materializes schema defaults in memory, so comparing
43293
+ * `config.get()` cannot detect a legacy `{ nodeId }` row. Reconciliation must
43294
+ * inspect the raw persisted blob to make the profile migration durable.
43295
+ */
43296
+ function needsTerminalCameraConfigMigration(persistedConfig, declaration) {
43297
+ return persistedConfig.instanceId !== declaration.config.instanceId || persistedConfig.nodeId !== declaration.config.nodeId || persistedConfig.profileId !== declaration.config.profileId || persistedConfig.profileLabel !== declaration.config.profileLabel;
43298
+ }
43299
+ /**
43300
+ * Monospace families to try, in order — NOT one family and a generic.
43301
+ *
43302
+ * A terminal screen is mostly box-drawing and block characters, and a font
43303
+ * without them renders the frame as noise rather than as missing detail.
43304
+ * `DejaVu Sans Mono` covers them and ships in the hub image; macOS has neither
43305
+ * DejaVu nor fontconfig, so the Mac agent fell through to a generic whose
43306
+ * coverage is not, and its Glances camera came out unreadable while the hub's
43307
+ * was pixel-perfect (measured 2026-08-11, same Glances, two nodes).
43308
+ *
43309
+ * `Menlo` is the fix rather than a guess: it is macOS's default terminal face,
43310
+ * present on every install, and derived from DejaVu Sans Mono — the same glyph
43311
+ * coverage by ancestry. Monaco and Courier New follow as older fallbacks; the
43312
+ * generic stays last so a host with none of them still draws something.
43313
+ */
43314
+ var TERMINAL_FONT_STACK = "DejaVu Sans Mono,Menlo,Monaco,Courier New,monospace";
43315
+ var TERMINAL_FONT_SIZE = 13;
43316
+ var TERMINAL_TEXT_MARGIN_X = 8;
43317
+ var TERMINAL_ROW_HEIGHT = 15;
43318
+ var TERMINAL_BASELINE_Y = 18;
43319
+ /**
43320
+ * Distance from a row's baseline up to the top of its cell box. Chosen so
43321
+ * consecutive rows tile exactly: row N's box runs from `baseline - this` for
43322
+ * `TERMINAL_ROW_HEIGHT`, and row N+1's box starts where it ends. A background
43323
+ * bar that stopped short would draw as stripes across a `CSI 42m` panel.
43324
+ */
43325
+ var TERMINAL_CELL_ASCENT = 11.5;
43326
+ var TERMINAL_CELL_WIDTH = TERMINAL_FONT_SIZE * (1233 / 2048);
43327
+ /** Two decimals is under a tenth of a pixel and keeps the SVG small. */
43328
+ function coordinate(value) {
43329
+ return String(Number(value.toFixed(2)));
43330
+ }
43331
+ function escapeXml(value) {
43332
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
43333
+ }
43334
+ /**
43335
+ * Render already-interpreted terminal rows into a compact MJPEG frame.
43336
+ *
43337
+ * `xml:space="preserve"` is load-bearing, not tidiness. SVG `<text>` collapses
43338
+ * runs of whitespace by default, and a terminal's entire column alignment IS
43339
+ * runs of whitespace — Glances pads every field with spaces. Without it the
43340
+ * frame drew each line at roughly half its true width, crammed into the
43341
+ * top-left of a mostly-black image, while the SAME session over `attach`
43342
+ * looked perfect — which is exactly how the operator reported it. Measured in
43343
+ * the hub's own rasterizer 2026-08-11: `AAA<10 spaces>BBB<3>CCC` drew 92 px
43344
+ * collapsed against 178 px preserved.
43345
+ *
43346
+ * Every run is anchored at its OWN column (`x = margin + startCol * cellW`),
43347
+ * never appended to the one before it, so the background rects and the glyphs
43348
+ * are placed off the same grid and cannot drift apart. `textLength` is emitted
43349
+ * with it because it is the correct declaration and renderers that honour it
43350
+ * get an exact grid — but it is not what makes this work: librsvg, which sharp
43351
+ * uses, ignores it outright (measured 2026-08-12, a 120-glyph run pinned to
43352
+ * 600 px still drew its natural 937 px). The anchoring is the guarantee.
43353
+ */
43354
+ function renderTerminalSvg(rows) {
43355
+ const backgrounds = [];
43356
+ const texts = [];
43357
+ rows.slice(0, 40).forEach((row, index) => {
43358
+ const baseline = TERMINAL_BASELINE_Y + index * TERMINAL_ROW_HEIGHT;
43359
+ const top = baseline - TERMINAL_CELL_ASCENT;
43360
+ let column = 0;
43361
+ for (const run of row) {
43362
+ if (column >= 120) break;
43363
+ const clipped = clipRun(run, 120 - column);
43364
+ const columns = [...clipped].length;
43365
+ if (columns === 0) continue;
43366
+ const x = TERMINAL_TEXT_MARGIN_X + column * TERMINAL_CELL_WIDTH;
43367
+ const width = columns * TERMINAL_CELL_WIDTH;
43368
+ if (run.bg !== null) backgrounds.push(`<rect x="${coordinate(x)}" y="${coordinate(top)}" width="${coordinate(width)}" height="${String(TERMINAL_ROW_HEIGHT)}" fill="${run.bg}"/>`);
43369
+ if (clipped.trim() !== "") {
43370
+ const fill = run.fg === null ? "" : ` fill="${run.fg}"`;
43371
+ const weight = run.bold ? " font-weight=\"bold\"" : "";
43372
+ texts.push(`<text xml:space="preserve" x="${coordinate(x)}" y="${coordinate(baseline)}" textLength="${coordinate(width)}" lengthAdjust="spacingAndGlyphs"${fill}${weight}>${escapeXml(clipped)}</text>`);
43373
+ }
43374
+ column += columns;
43375
+ }
43376
+ });
43377
+ 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>`;
43378
+ }
43379
+ /** Cut a run to the columns still left in the row, by code point not unit. */
43380
+ function clipRun(run, remaining) {
43381
+ const points = [...run.text];
43382
+ return points.length <= remaining ? run.text : points.slice(0, remaining).join("");
43383
+ }
43384
+ async function renderTerminalJpeg(rows) {
43385
+ return sharp(Buffer.from(renderTerminalSvg(rows))).jpeg({
43386
+ quality: 82,
43387
+ chromaSubsampling: "4:2:0"
43388
+ }).toBuffer();
43389
+ }
43390
+ //#endregion
43391
+ //#region src/terminal-camera-device.ts
43392
+ var terminalCameraSchema = object({
43393
+ instanceId: string().min(1).optional(),
43394
+ nodeId: string().min(1),
43395
+ profileId: string().min(1).default("monitor"),
43396
+ profileLabel: string().min(1).default("BTM")
43397
+ });
43398
+ var relay = null;
43399
+ function installTerminalCameraRelay(next) {
43400
+ relay = next;
43401
+ }
43402
+ var TerminalCameraDevice = class extends BaseDevice {
43403
+ features = [DeviceFeature.NativeSnapshot];
43404
+ constructor(ctx) {
43405
+ super(ctx, terminalCameraSchema, { type: ctx.deviceMeta.type });
43406
+ this.ctx.registerNativeCap(streamCatalogCapability, { getCatalog: async ({ deviceId }) => {
43407
+ if (deviceId !== this.id) return [];
43408
+ return this.catalog();
43409
+ } });
43410
+ this.ctx.registerNativeCap(snapshotCapability, {
43411
+ getSnapshot: async ({ deviceId }) => {
43412
+ if (deviceId !== this.id) throw new Error(`TerminalCameraDevice: deviceId mismatch, expected ${String(this.id)}, got ${String(deviceId)}`);
43413
+ const activeRelay = relay;
43414
+ if (!activeRelay) throw new Error("terminal camera relay is unavailable");
43415
+ return {
43416
+ base64: (await activeRelay.snapshot(this.relayInstanceId(), this.config.get("nodeId"), this.config.get("profileId"))).toString("base64"),
43417
+ contentType: "image/jpeg"
43418
+ };
43419
+ },
43420
+ invalidateCache: async () => {}
43421
+ });
43422
+ this.markOnline(true);
43423
+ }
43424
+ async catalog() {
43425
+ const activeRelay = relay;
43426
+ if (!activeRelay) throw new Error("terminal camera relay is unavailable");
43427
+ const nodeId = this.config.get("nodeId");
43428
+ const profileId = this.config.get("profileId");
43429
+ const instanceId = this.relayInstanceId();
43430
+ return [{
43431
+ camStreamId: profileId,
43432
+ kind: "pull-http",
43433
+ url: activeRelay.streamUrl(instanceId, nodeId, profileId),
43434
+ codec: "h264",
43435
+ resolution: {
43436
+ width: 960,
43437
+ height: 640
43438
+ },
43439
+ fps: 2,
43440
+ label: this.config.get("profileLabel")
43441
+ }];
43442
+ }
43443
+ setNodeOnline(online) {
43444
+ this.markOnline(online);
43445
+ if (!online) relay?.closeInstance(this.relayInstanceId());
43446
+ }
43447
+ async removeDevice() {
43448
+ await relay?.closeInstance(this.relayInstanceId());
43449
+ }
43450
+ relayInstanceId() {
43451
+ return this.config.get("instanceId") ?? `legacy:${this.stableId}`;
43452
+ }
43453
+ };
43454
+ //#endregion
43337
43455
  //#region src/terminal-camera-relay.ts
43338
43456
  var MJPEG_BOUNDARY = "camstack-terminal-frame";
43339
43457
  var SESSION_IDLE_MS = 3e4;
@@ -43836,7 +43954,8 @@ var TerminalInstanceSchema = object({
43836
43954
  executable: string().max(1024).default(""),
43837
43955
  args: array(string().max(2048)).max(64).default([]),
43838
43956
  cwd: string().max(1024).default(""),
43839
- environment: array(string().max(4096)).max(64).default([])
43957
+ environment: array(string().max(4096)).max(64).default([]),
43958
+ profileSettings: record(string(), unknown()).default({})
43840
43959
  });
43841
43960
  function environmentEntriesToRecord(entries) {
43842
43961
  const out = {};
@@ -44050,6 +44169,108 @@ function findProfile(profiles, profileId) {
44050
44169
  return profiles.find((p) => p.profileId === profileId);
44051
44170
  }
44052
44171
  //#endregion
44172
+ //#region src/profile-settings.ts
44173
+ var GLANCES_PLUGINS = [
44174
+ {
44175
+ key: "showCpu",
44176
+ plugin: "cpu",
44177
+ label: "CPU"
44178
+ },
44179
+ {
44180
+ key: "showMem",
44181
+ plugin: "mem",
44182
+ label: "Memory"
44183
+ },
44184
+ {
44185
+ key: "showLoad",
44186
+ plugin: "load",
44187
+ label: "Load"
44188
+ },
44189
+ {
44190
+ key: "showNetwork",
44191
+ plugin: "network",
44192
+ label: "Network"
44193
+ },
44194
+ {
44195
+ key: "showDiskIo",
44196
+ plugin: "diskio",
44197
+ label: "Disk I/O"
44198
+ },
44199
+ {
44200
+ key: "showFs",
44201
+ plugin: "fs",
44202
+ label: "Filesystems"
44203
+ },
44204
+ {
44205
+ key: "showProcessList",
44206
+ plugin: "processlist",
44207
+ label: "Process list"
44208
+ },
44209
+ {
44210
+ key: "showContainers",
44211
+ plugin: "containers",
44212
+ label: "Containers"
44213
+ },
44214
+ {
44215
+ key: "showSensors",
44216
+ plugin: "sensors",
44217
+ label: "Sensors"
44218
+ }
44219
+ ];
44220
+ function glancesBooleanField(key, label) {
44221
+ return {
44222
+ type: "boolean",
44223
+ key,
44224
+ label,
44225
+ default: true,
44226
+ style: "switch"
44227
+ };
44228
+ }
44229
+ function glancesSettingsSchema() {
44230
+ return { sections: [{
44231
+ id: "glances-panels",
44232
+ title: "Glances panels",
44233
+ description: "Turn off a panel to pass --disable-plugin to this Terminal only. All on is the measured default (~1% of one core at the camera grid).",
44234
+ columns: 2,
44235
+ fields: GLANCES_PLUGINS.map((plugin) => glancesBooleanField(plugin.key, plugin.label))
44236
+ }] };
44237
+ }
44238
+ function settingsSchemaForProfile(profileId) {
44239
+ if (profileId === "glances") return glancesSettingsSchema();
44240
+ return null;
44241
+ }
44242
+ function glancesSettingsToArgs(settings) {
44243
+ const disabled = GLANCES_PLUGINS.filter((plugin) => settings[plugin.key] === false).map((plugin) => plugin.plugin);
44244
+ if (disabled.length === 0) return [];
44245
+ return ["--disable-plugin", disabled.join(",")];
44246
+ }
44247
+ function sanitizeProfileSettings(profileId, raw) {
44248
+ if (profileId !== "glances") return {};
44249
+ const bag = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
44250
+ const out = {
44251
+ showCpu: true,
44252
+ showMem: true,
44253
+ showLoad: true,
44254
+ showNetwork: true,
44255
+ showDiskIo: true,
44256
+ showFs: true,
44257
+ showProcessList: true,
44258
+ showContainers: true,
44259
+ showSensors: true
44260
+ };
44261
+ for (const plugin of GLANCES_PLUGINS) if (typeof bag[plugin.key] === "boolean") out[plugin.key] = bag[plugin.key];
44262
+ return out;
44263
+ }
44264
+ function profileSettingsToArgs(profileId, settings) {
44265
+ if (profileId !== "glances") return [];
44266
+ return glancesSettingsToArgs(sanitizeProfileSettings(profileId, settings));
44267
+ }
44268
+ function spawnArgsForInstance(input) {
44269
+ const extra = profileSettingsToArgs(input.profileId, input.profileSettings);
44270
+ if (input.instanceArgs.length > 0) return [...input.instanceArgs, ...extra];
44271
+ if (extra.length > 0) return [...input.profileArgs, ...extra];
44272
+ }
44273
+ //#endregion
44053
44274
  //#region src/terminal-session-manager.ts
44054
44275
  var MIN_GRID = 1;
44055
44276
  var MAX_COLS = 1e3;
@@ -44118,7 +44339,8 @@ var TerminalSessionManager = class {
44118
44339
  executable: p.file,
44119
44340
  args: [...p.args],
44120
44341
  cwd: p.cwd ?? "",
44121
- environment: environmentRecordToEntries(p.env)
44342
+ environment: environmentRecordToEntries(p.env),
44343
+ settingsSchema: settingsSchemaForProfile(p.profileId)
44122
44344
  }));
44123
44345
  }
44124
44346
  setInstanceControl(control) {
@@ -44519,15 +44741,22 @@ var TerminalAddon = class extends BaseAddon {
44519
44741
  const localNodeId = declarationOwnerNodeId(this.ctx.kernel.localNodeId);
44520
44742
  const cameraRelay = new TerminalCameraRelay({
44521
44743
  listProfiles: (nodeId) => nodeId === localNodeId ? manager.listProfiles() : this.ctx.api.terminalSession.listProfiles.query(void 0, nodePin(nodeId)),
44522
- openSession: (nodeId, input) => {
44744
+ openSession: async (nodeId, input) => {
44523
44745
  const instance = input.instanceId ? this.terminalInstances().find((row) => row.id === input.instanceId) : void 0;
44746
+ const profile = (nodeId === localNodeId ? await manager.listProfiles() : await this.ctx.api.terminalSession.listProfiles.query(void 0, nodePin(nodeId))).find((candidate) => candidate.profileId === (instance?.profileId ?? input.profileId));
44747
+ const args = instance ? spawnArgsForInstance({
44748
+ profileId: instance.profileId,
44749
+ instanceArgs: instance.args,
44750
+ profileArgs: profile?.args ?? [],
44751
+ profileSettings: instance.profileSettings
44752
+ }) : void 0;
44524
44753
  const payload = {
44525
44754
  profileId: input.profileId,
44526
44755
  cols: input.cols,
44527
44756
  rows: input.rows,
44528
44757
  ...instance ? {
44529
44758
  ...instance.executable ? { executable: instance.executable } : {},
44530
- ...instance.args.length > 0 ? { args: [...instance.args] } : {},
44759
+ ...args !== void 0 ? { args: [...args] } : {},
44531
44760
  ...instance.cwd ? { cwd: instance.cwd } : {},
44532
44761
  ...instance.environment.length > 0 ? { environment: [...instance.environment] } : {}
44533
44762
  } : {}
@@ -44762,7 +44991,8 @@ var TerminalAddon = class extends BaseAddon {
44762
44991
  executable: instance.executable,
44763
44992
  args: instance.args,
44764
44993
  cwd: instance.cwd,
44765
- environment: instance.environment
44994
+ environment: instance.environment,
44995
+ profileSettings: instance.profileSettings
44766
44996
  };
44767
44997
  }
44768
44998
  replaceTerminalCameraTombstones(stableIds) {
@@ -44794,7 +45024,8 @@ var TerminalAddon = class extends BaseAddon {
44794
45024
  executable: input.executable?.trim() || profile.executable || "",
44795
45025
  args: input.args ? [...input.args] : [...profile.args ?? []],
44796
45026
  cwd: input.cwd?.trim() || profile.cwd || "",
44797
- environment: input.environment ? [...input.environment] : [...profile.environment ?? []]
45027
+ environment: input.environment ? [...input.environment] : [...profile.environment ?? []],
45028
+ profileSettings: sanitizeProfileSettings(profile.profileId, input.profileSettings)
44798
45029
  };
44799
45030
  await this.updateGlobalSettings({ terminalInstances: [...this.config.terminalInstances, instance] });
44800
45031
  return this.instanceInfo(instance);
@@ -44814,7 +45045,8 @@ var TerminalAddon = class extends BaseAddon {
44814
45045
  ...input.executable !== void 0 ? { executable: input.executable.trim() } : {},
44815
45046
  ...input.args !== void 0 ? { args: [...input.args] } : {},
44816
45047
  ...input.cwd !== void 0 ? { cwd: input.cwd.trim() } : {},
44817
- ...input.environment !== void 0 ? { environment: [...input.environment] } : {}
45048
+ ...input.environment !== void 0 ? { environment: [...input.environment] } : {},
45049
+ ...input.profileSettings !== void 0 ? { profileSettings: sanitizeProfileSettings(instance.profileId, input.profileSettings) } : {}
44818
45050
  };
44819
45051
  await this.updateGlobalSettings({ terminalInstances: this.config.terminalInstances.map((candidate) => candidate.id === input.instanceId ? updated : candidate) });
44820
45052
  return this.instanceInfo(updated);
@@ -44882,7 +45114,8 @@ var TerminalAddon = class extends BaseAddon {
44882
45114
  executable: "",
44883
45115
  args: [],
44884
45116
  cwd: "",
44885
- environment: []
45117
+ environment: [],
45118
+ profileSettings: {}
44886
45119
  };
44887
45120
  await this.updateGlobalSettings({ terminalInstances: [...this.config.terminalInstances, instance] });
44888
45121
  return this.instanceInfo(instance);