@camstack/server 1.2.735 → 1.2.736

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 (93) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/api/core/cap-providers.js +114 -8
  3. package/dist/api/trpc/generated-cap-mounts.js +17 -1
  4. package/dist/api/trpc/generated-cap-routers.js +1789 -1708
  5. package/dist/core/addon/addon-registry.service.js +2 -0
  6. package/dist/core/addon/addon-settings-provider.js +4 -0
  7. package/dist/core/addon/integration-instances-provider.js +21 -0
  8. package/package.json +4 -4
  9. package/system/dist/{agent-https-DrCbFr4p.js → agent-https-Bi3JY1e0.js} +1 -1
  10. package/system/dist/{agent-https-BVCIU0eH.mjs → agent-https-DiK6iQzW.mjs} +1 -1
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  17. package/system/dist/builtins/autotrack/index.js +1 -1
  18. package/system/dist/builtins/autotrack/index.mjs +1 -1
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  21. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  22. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  23. package/system/dist/builtins/camera-grid/index.js +1 -1
  24. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  25. package/system/dist/builtins/composer/composer.addon.js +3 -3
  26. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  27. package/system/dist/builtins/console-logging/index.js +1 -1
  28. package/system/dist/builtins/console-logging/index.mjs +1 -1
  29. package/system/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  30. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  31. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  32. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  33. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  34. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  35. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  36. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  37. package/system/dist/builtins/keychain/index.js +3 -3
  38. package/system/dist/builtins/keychain/index.mjs +3 -3
  39. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  40. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  41. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  42. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  43. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  44. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  45. package/system/dist/builtins/loki-logging/index.js +440 -25
  46. package/system/dist/builtins/loki-logging/index.mjs +438 -25
  47. package/system/dist/builtins/loki-logging/loki-logging.addon.d.ts +23 -14
  48. package/system/dist/builtins/loki-logging/loki-record-kinds.d.ts +33 -0
  49. package/system/dist/builtins/loki-logging/migrations/connection-to-records.d.ts +47 -0
  50. package/system/dist/builtins/loki-logging/migrations/index.d.ts +8 -0
  51. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  53. package/system/dist/builtins/platform-probe/index.js +1 -1
  54. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  55. package/system/dist/builtins/record-entries/index.js +2 -22
  56. package/system/dist/builtins/record-entries/index.mjs +2 -22
  57. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  59. package/system/dist/builtins/snapshot/index.js +1 -1
  60. package/system/dist/builtins/snapshot/index.mjs +1 -1
  61. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  63. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  65. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  67. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  69. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  70. package/system/dist/builtins/system-config/system-config.addon.mjs +7 -7
  71. package/system/dist/builtins/winston-logging/index.js +1 -1
  72. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  73. package/system/dist/{composition-sources-BV9n2ivT.js → composition-sources-DQLGJMMh.js} +1 -1
  74. package/system/dist/{composition-sources-CI2tZzAo.mjs → composition-sources-lnsR-YuH.mjs} +1 -1
  75. package/system/dist/{constants-Bskr2h1W.mjs → constants-D7I0cM20.mjs} +1 -1
  76. package/system/dist/{constants-dYIQm8ab.js → constants-DA5jgmYT.js} +1 -1
  77. package/system/dist/{device-ca-04o7NByo.mjs → device-ca-Clr2bCe-.mjs} +1 -1
  78. package/system/dist/{device-ca-BF8N9fC6.js → device-ca-GPjZE-Mm.js} +1 -1
  79. package/system/dist/{dist-CnC8-kF6.mjs → dist-Cyj93AvD.mjs} +529 -152
  80. package/system/dist/{dist-B4r3_aYb.js → dist-Xi7ZQ7UI.js} +564 -151
  81. package/system/dist/file-host-worker.js +1 -1
  82. package/system/dist/file-host-worker.mjs +1 -1
  83. package/system/dist/{hub-mdns-ciao-MdXDARI0.js → hub-mdns-ciao-BMgUdxgG.js} +2 -2
  84. package/system/dist/{hub-mdns-ciao-BE1vqriF.mjs → hub-mdns-ciao-ouzCfqVS.mjs} +2 -2
  85. package/system/dist/index.js +7 -7
  86. package/system/dist/index.mjs +7 -7
  87. package/system/dist/{restore-archive-Dx9F-3zV.mjs → restore-archive-BG22FodH.mjs} +5 -5
  88. package/system/dist/{restore-archive-BEUIhG8U.js → restore-archive-CZozfCX-.js} +1 -1
  89. package/system/dist/{retention-fsBjIfxP.mjs → retention-BfC_C1vy.mjs} +1 -1
  90. package/system/dist/{retention-nNCAON-6.js → retention-DCrdPMot.js} +1 -1
  91. package/system/dist/{wal-maintenance-0XhlopB5.mjs → wal-maintenance-C2GNRuvy.mjs} +0 -0
  92. package/system/dist/{wal-maintenance-UKXXEEoS.js → wal-maintenance-PjOoh6-K.js} +0 -0
  93. package/system/package.json +4 -1
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B4r3_aYb.js");
6
+ const require_dist = require("../../dist-Xi7ZQ7UI.js");
7
7
  const require_log_read_filter = require("../../log-read-filter-Bi066jwU.js");
8
8
  let zod = require("zod");
9
9
  //#region src/builtins/loki-logging/loki-payload.ts
@@ -184,7 +184,7 @@ var LokiLineSchema = zod.z.object({
184
184
  tags: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
185
185
  meta: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
186
186
  });
187
- function levelOf(label) {
187
+ function levelOf$1(label) {
188
188
  return label === "debug" || label === "warn" || label === "error" ? label : "info";
189
189
  }
190
190
  /** A query_range body → rows, newest first. Lines that are not ours are dropped. */
@@ -193,7 +193,7 @@ function parseQueryRange(body) {
193
193
  if (!parsed.success) throw new Error("Loki answered with an unexpected query_range shape");
194
194
  const rows = [];
195
195
  for (const stream of parsed.data.data.result) {
196
- const level = levelOf(stream.stream["level"]);
196
+ const level = levelOf$1(stream.stream["level"]);
197
197
  for (const [nsText, text] of stream.values) {
198
198
  let json;
199
199
  try {
@@ -609,6 +609,222 @@ var LokiDestination = class {
609
609
  }
610
610
  };
611
611
  //#endregion
612
+ //#region src/builtins/loki-logging/loki-record-kinds.ts
613
+ /**
614
+ * The Loki connection as a record (D985): one `destinations` row per Loki instance, owned by
615
+ * `loki-logging`, listed on the Integrations page like any other connection. The row id is the
616
+ * `integrations` registry id (`int_NNNN`). The password is a keychain marker bound to the row.
617
+ *
618
+ * The kind name is `destinations` (kind names are lower-case-dashed); the owner is `loki-logging`.
619
+ */
620
+ /** The inclusive bounds of the numeric fields: the schema and the settings migration read ONE copy. */
621
+ var LOKI_BOUNDS = {
622
+ batchIntervalMs: {
623
+ min: 250,
624
+ max: 6e4
625
+ },
626
+ batchSize: {
627
+ min: 1,
628
+ max: 5e3
629
+ },
630
+ timeoutMs: {
631
+ min: 1e3,
632
+ max: 6e4
633
+ }
634
+ };
635
+ /** The schema is checked against the interface by its annotation: a drifted field fails the typecheck. */
636
+ var LokiDestinationBodySchema = zod.z.object({
637
+ name: zod.z.string().min(1),
638
+ url: zod.z.string(),
639
+ level: zod.z.enum([
640
+ "debug",
641
+ "info",
642
+ "warn",
643
+ "error"
644
+ ]),
645
+ job: zod.z.string(),
646
+ extraLabels: zod.z.string(),
647
+ tenantId: zod.z.string(),
648
+ username: zod.z.string(),
649
+ password: zod.z.string().optional().meta({ secret: true }),
650
+ batchIntervalMs: zod.z.number().int().min(LOKI_BOUNDS.batchIntervalMs.min).max(LOKI_BOUNDS.batchIntervalMs.max),
651
+ batchSize: zod.z.number().int().min(LOKI_BOUNDS.batchSize.min).max(LOKI_BOUNDS.batchSize.max),
652
+ timeoutMs: zod.z.number().int().min(LOKI_BOUNDS.timeoutMs.min).max(LOKI_BOUNDS.timeoutMs.max)
653
+ });
654
+ var lokiDestinationsKind = require_dist.defineEntryKind("destinations", {
655
+ title: "Loki destinations",
656
+ nameField: "name",
657
+ schema: LokiDestinationBodySchema
658
+ });
659
+ var LOKI_DEFAULT_BODY = {
660
+ url: "",
661
+ level: "info",
662
+ job: "camstack",
663
+ extraLabels: "",
664
+ tenantId: "",
665
+ username: "",
666
+ batchIntervalMs: 5e3,
667
+ batchSize: 200,
668
+ timeoutMs: 1e4
669
+ };
670
+ //#endregion
671
+ //#region src/builtins/loki-logging/migrations/connection-to-records.ts
672
+ /**
673
+ * The Loki connection moves from the addon's settings into a `destinations` record (D985):
674
+ * an integration row in the registry, a record under that id, and the password re-bound to
675
+ * the record's keychain slot. The old keys are deleted by the second migration of the
676
+ * catalogue (`dropMovedSettings`), only after this one succeeded.
677
+ *
678
+ * Idempotent and ordered so a crash is safe: nothing is written before the old settings are
679
+ * read in full (a password that cannot be resolved aborts the pass); an existing record is
680
+ * never overwritten; the old password is cleared only once the record verifiably holds it.
681
+ */
682
+ /** The settings scope of this addon (`<addonId>:addon-settings`). */
683
+ var LOKI_SETTINGS_SCOPE = "loki-logging:addon-settings";
684
+ /** The connection keys the record now owns. `password` is the secret, cleared separately. */
685
+ var MOVED_PLAIN_KEYS = [
686
+ "url",
687
+ "level",
688
+ "job",
689
+ "extraLabels",
690
+ "tenantId",
691
+ "username",
692
+ "batchIntervalMs",
693
+ "batchSize",
694
+ "timeoutMs"
695
+ ];
696
+ var LOKI_NAME = "Loki";
697
+ function text(stored, key, fallback) {
698
+ const value = stored[key];
699
+ return typeof value === "string" ? value : fallback;
700
+ }
701
+ /**
702
+ * A whole number inside the kind's own bounds (`LOKI_BOUNDS`, the same copy the schema uses): an
703
+ * out-of-range legacy value would make the record write throw and block the owner, so it is
704
+ * clamped, and the clamp is named.
705
+ */
706
+ function bounded(stored, key, fallback, log) {
707
+ const value = stored[key];
708
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
709
+ const { min, max } = LOKI_BOUNDS[key];
710
+ const clamped = Math.min(max, Math.max(min, Math.round(value)));
711
+ if (clamped !== value) log.warn(`Loki migration: the legacy "${key}" is outside ${min}..${max}; clamped to ${clamped}`);
712
+ return clamped;
713
+ }
714
+ function levelOf(stored) {
715
+ const value = stored["level"];
716
+ return value === "debug" || value === "info" || value === "warn" || value === "error" ? value : LOKI_DEFAULT_BODY.level;
717
+ }
718
+ function bodyFrom(stored, log) {
719
+ const password = text(stored, "password", "");
720
+ return {
721
+ name: LOKI_NAME,
722
+ url: text(stored, "url", LOKI_DEFAULT_BODY.url),
723
+ level: levelOf(stored),
724
+ job: text(stored, "job", LOKI_DEFAULT_BODY.job),
725
+ extraLabels: text(stored, "extraLabels", LOKI_DEFAULT_BODY.extraLabels),
726
+ tenantId: text(stored, "tenantId", LOKI_DEFAULT_BODY.tenantId),
727
+ username: text(stored, "username", LOKI_DEFAULT_BODY.username),
728
+ ...password.length > 0 ? { password } : {},
729
+ batchIntervalMs: bounded(stored, "batchIntervalMs", LOKI_DEFAULT_BODY.batchIntervalMs, log),
730
+ batchSize: bounded(stored, "batchSize", LOKI_DEFAULT_BODY.batchSize, log),
731
+ timeoutMs: bounded(stored, "timeoutMs", LOKI_DEFAULT_BODY.timeoutMs, log)
732
+ };
733
+ }
734
+ async function moveConnectionToRecord(ports) {
735
+ const stored = await ports.readStored();
736
+ const url = text(stored, "url", "");
737
+ const hasPassword = text(stored, "password", "").length > 0;
738
+ if (url.length === 0 && !hasPassword) return {
739
+ outcome: "already-done",
740
+ summary: { moved: false }
741
+ };
742
+ const id = await ports.ensureIntegration(LOKI_NAME);
743
+ const put = await ports.putRecord(id, bodyFrom(stored, ports));
744
+ if (hasPassword) if (put === "created" || (await ports.readRecord(id))?.hasPassword === true) await ports.clearOldPassword();
745
+ else ports.warn("Loki migration: the existing record holds no password; the legacy one is kept, not cleared");
746
+ return put === "created" ? {
747
+ outcome: "done",
748
+ summary: {
749
+ moved: true,
750
+ integrationId: id
751
+ }
752
+ } : {
753
+ outcome: "already-done",
754
+ summary: {
755
+ moved: false,
756
+ integrationId: id
757
+ }
758
+ };
759
+ }
760
+ async function planDropMovedSettings(ports) {
761
+ const stored = await ports.readRawStored();
762
+ const present = [...MOVED_PLAIN_KEYS, "password"].filter((key) => key in stored);
763
+ if (present.length === 0) return { edits: [] };
764
+ await confirmRecordHoldsLegacy(ports, stored);
765
+ return { edits: [{
766
+ op: "deleteKeys",
767
+ scope: LOKI_SETTINGS_SCOPE,
768
+ keys: present,
769
+ precondition: require_dist.preconditionOf(Object.fromEntries(present.map((key) => [key, stored[key]])))
770
+ }] };
771
+ }
772
+ /**
773
+ * The keys are deleted only when the record is confirmed to hold what they carried: the url,
774
+ * and the password when the legacy settings still have one. Otherwise the migration fails, the
775
+ * keys stay, and the next boot retries.
776
+ */
777
+ async function confirmRecordHoldsLegacy(ports, stored) {
778
+ const legacyUrl = text(stored, "url", "");
779
+ const legacyPassword = "password" in stored;
780
+ if (legacyUrl.length === 0 && !legacyPassword) return;
781
+ const refuse = (reason) => {
782
+ ports.warn(`Loki migration: the legacy keys are kept: ${reason}`);
783
+ throw new Error(`the legacy Loki keys are not deleted: ${reason}`);
784
+ };
785
+ const id = await ports.findIntegration();
786
+ if (id === null) return refuse("no integration row exists");
787
+ const record = await ports.readRecord(id);
788
+ if (record === null) return refuse("the destinations record does not exist");
789
+ if (legacyUrl.length > 0 && record.url.length === 0) return refuse("the record holds no url");
790
+ if (legacyPassword && !record.hasPassword) return refuse("the record holds no password");
791
+ }
792
+ //#endregion
793
+ //#region src/builtins/loki-logging/migrations/index.ts
794
+ var CONNECTION_TO_RECORDS_ID = "loki-logging/2026-11-02-connection-to-records";
795
+ /** The `loki-logging` catalogue (D987): offered to the engine when the hub-resident addon initialises. */
796
+ var ADDON_MIGRATIONS = [{
797
+ meta: {
798
+ id: CONNECTION_TO_RECORDS_ID,
799
+ owner: "loki-logging",
800
+ level: "addon-state",
801
+ seq: 1,
802
+ dependsOn: [],
803
+ store: "settings",
804
+ scope: "cluster",
805
+ onFailure: "block-owner",
806
+ bodyKind: "procedure",
807
+ description: "Move the Loki connection (url, credentials, labels, batching) from the addon settings into a destinations record under an integrations row",
808
+ fixtureMark: "the D777 retirement marker the migration does not know"
809
+ },
810
+ procedure: moveConnectionToRecord
811
+ }, {
812
+ meta: {
813
+ id: "loki-logging/2026-11-02-drop-moved-settings",
814
+ owner: "loki-logging",
815
+ level: "addon-state",
816
+ seq: 2,
817
+ dependsOn: [CONNECTION_TO_RECORDS_ID],
818
+ store: "settings",
819
+ scope: "cluster",
820
+ onFailure: "block-owner",
821
+ bodyKind: "plan",
822
+ description: "Delete the connection keys that moved into the destinations record",
823
+ fixtureMark: "the D777 retirement marker the migration does not know"
824
+ },
825
+ plan: planDropMovedSettings
826
+ }];
827
+ //#endregion
612
828
  //#region src/builtins/loki-logging/retire-enabled-flag.ts
613
829
  /** The retired settings key. */
614
830
  var RETIRED_ENABLED_KEY = "enabled";
@@ -654,35 +870,220 @@ var RETIREMENT_RETRY_DELAYS_MS = [
654
870
  3e4,
655
871
  6e4
656
872
  ];
657
- var DEFAULTS = {
658
- url: "",
659
- job: "camstack",
660
- level: "info",
661
- batchIntervalMs: 5e3,
662
- batchSize: 200,
663
- extraLabels: "",
664
- tenantId: "",
665
- username: "",
666
- password: "",
667
- timeoutMs: 1e4
668
- };
873
+ /** An agent re-reads the record on this period; the hub applies a change at once (`onChanged`). */
874
+ var AGENT_REFRESH_MS = 3e4;
875
+ /** The headers the destination itself sends: tenant and basic auth. */
876
+ function probeHeaders(auth) {
877
+ const headers = {};
878
+ if (auth.tenantId.trim().length > 0) headers["X-Scope-OrgID"] = auth.tenantId.trim();
879
+ if (auth.username.length > 0) headers["authorization"] = `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}`;
880
+ return headers;
881
+ }
882
+ /** A failure message with the userinfo of any URL in it (and the typed URL's own) removed. */
883
+ function stripUserinfo(message, typedUrl) {
884
+ let out = message.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]*@/gi, "$1");
885
+ try {
886
+ const parsed = new URL(typedUrl);
887
+ for (const secret of [parsed.username, parsed.password]) if (secret.length > 0) out = out.split(decodeURIComponent(secret)).join("***");
888
+ } catch {}
889
+ return out;
890
+ }
891
+ /** Where the connection probe asks: Loki answers `ready` once its ring is up. */
892
+ var READY_PATH = "/ready";
669
893
  var LokiLoggingAddon = class extends require_dist.BaseAddon {
670
894
  destination = null;
895
+ instances = null;
896
+ current = null;
897
+ refreshTimer = null;
671
898
  retirementTimer = null;
672
899
  shuttingDown = false;
900
+ declared = false;
901
+ secretsWarned = false;
673
902
  constructor() {
674
- super({ ...DEFAULTS });
903
+ super({});
904
+ }
905
+ isHub() {
906
+ return (this.ctx.kernel.localNodeId ?? "hub") === "hub";
675
907
  }
676
908
  async onInitialize() {
677
909
  this.destination = new LokiDestination();
678
- await this.destination.initialize(this.destinationConfig());
679
- this.ctx.logger.info(this.config.url.length > 0 ? `Loki logging initialized → ${this.config.url}` : "Loki logging registered but inactive (no URL set)");
680
910
  this.shuttingDown = false;
681
- this.attemptEnabledFlagRetirement(0);
682
- return [{
911
+ const registrations = [{
683
912
  capability: require_dist.logDestinationCapability,
684
913
  provider: this.destination
685
914
  }];
915
+ const records = this.ctx.records;
916
+ if (records !== void 0) {
917
+ const hub = this.isHub();
918
+ if (hub) await this.ensureDeclared();
919
+ else await this.ensureDeclaredQuietly();
920
+ this.instances = new require_dist.RecordIntegrationInstances(records, lokiDestinationsKind, {
921
+ description: {
922
+ instanceMode: "single",
923
+ kind: "destination",
924
+ canTest: true
925
+ },
926
+ formSchema: () => this.connectionForm(),
927
+ initialBody: (name) => ({
928
+ ...LOKI_DEFAULT_BODY,
929
+ name
930
+ }),
931
+ configured: (body) => body.url.length > 0,
932
+ onChanged: async () => {
933
+ await this.refreshFromRecord();
934
+ },
935
+ test: (input) => this.probe(input.id, input.values)
936
+ });
937
+ if (hub) {
938
+ await this.runMigrations(require_dist.defineAddonMigrations(ADDON_MIGRATIONS, this.migrationPorts()));
939
+ registrations.push({
940
+ capability: require_dist.integrationInstancesCapability,
941
+ provider: this.instances.toProvider()
942
+ });
943
+ } else {
944
+ this.refreshTimer = setInterval(() => void this.refreshFromRecord(), AGENT_REFRESH_MS);
945
+ this.refreshTimer.unref?.();
946
+ }
947
+ await this.refreshFromRecord();
948
+ }
949
+ await this.destination.initialize(this.destinationConfig());
950
+ const url = this.current?.url ?? "";
951
+ this.ctx.logger.info(url.length > 0 ? `Loki logging initialized → ${url}` : "Loki logging registered but inactive (no URL set)");
952
+ this.attemptEnabledFlagRetirement(0);
953
+ return registrations;
954
+ }
955
+ async ensureDeclared() {
956
+ const records = this.ctx.records;
957
+ if (records === void 0 || this.declared) return;
958
+ await records.declare({ destinations: lokiDestinationsKind });
959
+ this.declared = true;
960
+ }
961
+ async ensureDeclaredQuietly() {
962
+ try {
963
+ await this.ensureDeclared();
964
+ } catch (err) {
965
+ this.ctx.logger.warn("Loki logging: the connection kind could not be declared yet", { meta: { error: err instanceof Error ? err.message : String(err) } });
966
+ }
967
+ }
968
+ /** Re-read the connection record and apply it to the live destination. */
969
+ async refreshFromRecord() {
970
+ if (this.instances === null || this.shuttingDown) return;
971
+ let first;
972
+ try {
973
+ if (!this.declared) await this.ensureDeclared();
974
+ [first] = await this.instances.listResolved();
975
+ } catch (err) {
976
+ this.ctx.logger.warn("Loki logging: the connection record could not be read", { meta: { error: err instanceof Error ? err.message : String(err) } });
977
+ return;
978
+ }
979
+ if (first?.secrets === "unavailable") {
980
+ if (!this.secretsWarned) {
981
+ this.secretsWarned = true;
982
+ this.ctx.logger.warn("Loki logging: the keychain is locked; the destination keeps its previous configuration");
983
+ }
984
+ return;
985
+ }
986
+ this.secretsWarned = false;
987
+ this.current = first?.body ?? null;
988
+ await this.destination?.reconfigure(this.destinationConfig());
989
+ }
990
+ /** The ports of the connection migrations: the old settings in, the record out. */
991
+ migrationPorts() {
992
+ const records = this.ctx.records;
993
+ const instances = this.instances;
994
+ if (records === void 0 || instances === null) throw new Error("records are not available");
995
+ const handle = records.kind(lokiDestinationsKind);
996
+ return {
997
+ readStored: async () => {
998
+ const stored = await this.resolveGlobalStore();
999
+ const password = stored["password"];
1000
+ if (require_dist.isSecretMarker(password)) throw new Error("the old Loki password could not be resolved");
1001
+ return stored;
1002
+ },
1003
+ readRawStored: async () => this.resolveGlobalStore(),
1004
+ warn: (message) => {
1005
+ this.ctx.logger.warn(message);
1006
+ },
1007
+ findIntegration: async () => {
1008
+ return (await this.ctx.api.integrations.getByAddonId.query({ addonId: this.ctx.id }))?.id ?? null;
1009
+ },
1010
+ readRecord: async (id) => {
1011
+ const row = await handle.getResolved(id);
1012
+ if (row === null) return null;
1013
+ return {
1014
+ url: row.data.url,
1015
+ hasPassword: (row.data.password ?? "").length > 0
1016
+ };
1017
+ },
1018
+ ensureIntegration: async (name) => {
1019
+ const existing = await this.ctx.api.integrations.getByAddonId.query({ addonId: this.ctx.id });
1020
+ if (existing !== null && existing !== void 0) return existing.id;
1021
+ return (await this.ctx.api.integrations.create.mutate({
1022
+ addonId: this.ctx.id,
1023
+ name,
1024
+ skipRestart: true
1025
+ })).id;
1026
+ },
1027
+ putRecord: async (id, body) => {
1028
+ if (await handle.get(id) !== null) return "exists";
1029
+ try {
1030
+ await handle.put({
1031
+ id,
1032
+ data: body
1033
+ }, { ifRev: 0 });
1034
+ } catch (err) {
1035
+ if (err instanceof require_dist.RevConflictError) return "exists";
1036
+ throw err;
1037
+ }
1038
+ return "created";
1039
+ },
1040
+ clearOldPassword: async () => {
1041
+ await this.clearSecrets(["password"]);
1042
+ }
1043
+ };
1044
+ }
1045
+ /** Probe a Loki instance (`/ready`) with the form's values, falling back to the stored ones. */
1046
+ async probe(id, values) {
1047
+ const stored = id !== null && this.instances !== null ? await this.instances.getResolved(id) : null;
1048
+ const typed = (key) => {
1049
+ const value = values[key];
1050
+ return typeof value === "string" && value.length > 0 ? value : stored?.[key] ?? "";
1051
+ };
1052
+ const url = typed("url");
1053
+ if (url.length === 0) return {
1054
+ success: false,
1055
+ status: "rejected",
1056
+ error: "No Loki URL set"
1057
+ };
1058
+ const password = values["password"];
1059
+ const fresh = typeof password === "string" && password.length > 0 && password !== "__camstack_redacted__" && !require_dist.isSecretFieldView(password);
1060
+ const headers = probeHeaders({
1061
+ username: typed("username"),
1062
+ tenantId: typed("tenantId"),
1063
+ password: fresh ? password : stored?.password ?? ""
1064
+ });
1065
+ const started = Date.now();
1066
+ try {
1067
+ const res = await fetch(new URL(READY_PATH, url), {
1068
+ headers,
1069
+ signal: AbortSignal.timeout(stored?.timeoutMs ?? LOKI_DEFAULT_BODY.timeoutMs)
1070
+ });
1071
+ return res.ok ? {
1072
+ success: true,
1073
+ status: "validated",
1074
+ latencyMs: Date.now() - started
1075
+ } : {
1076
+ success: false,
1077
+ status: "rejected",
1078
+ error: `Loki answered HTTP ${res.status}`
1079
+ };
1080
+ } catch (err) {
1081
+ return {
1082
+ success: false,
1083
+ status: "inconclusive",
1084
+ error: stripUserinfo(err instanceof Error ? err.message : String(err), url)
1085
+ };
1086
+ }
686
1087
  }
687
1088
  /** One attempt of the D777 carry-over; reschedules itself while deferred. */
688
1089
  async attemptEnabledFlagRetirement(attempt) {
@@ -734,6 +1135,8 @@ var LokiLoggingAddon = class extends require_dist.BaseAddon {
734
1135
  this.shuttingDown = true;
735
1136
  if (this.retirementTimer !== null) clearTimeout(this.retirementTimer);
736
1137
  this.retirementTimer = null;
1138
+ if (this.refreshTimer !== null) clearInterval(this.refreshTimer);
1139
+ this.refreshTimer = null;
737
1140
  await this.destination?.shutdown();
738
1141
  this.destination = null;
739
1142
  }
@@ -745,8 +1148,7 @@ var LokiLoggingAddon = class extends require_dist.BaseAddon {
745
1148
  * pushing. Without this the destination keeps its boot-time config forever.
746
1149
  */
747
1150
  async onConfigChanged() {
748
- await this.destination?.reconfigure(this.destinationConfig());
749
- this.ctx.logger.info(this.config.url.length > 0 ? `Loki logging reconfigured → ${this.config.url}` : "Loki logging now inactive (no URL)");
1151
+ await this.refreshFromRecord();
750
1152
  }
751
1153
  /**
752
1154
  * `node` is a Loki LABEL, so it must be the node's real identity and must not
@@ -760,17 +1162,30 @@ var LokiLoggingAddon = class extends require_dist.BaseAddon {
760
1162
  * would have broken this addon's settings reload.
761
1163
  */
762
1164
  destinationConfig() {
1165
+ const body = this.current ?? {
1166
+ ...LOKI_DEFAULT_BODY,
1167
+ name: ""
1168
+ };
763
1169
  return {
764
- ...this.config,
765
1170
  enabled: true,
766
- node: this.ctx.kernel.localNodeId ?? "hub"
1171
+ url: body.url,
1172
+ job: body.job,
1173
+ node: this.ctx.kernel.localNodeId ?? "hub",
1174
+ level: body.level,
1175
+ batchIntervalMs: body.batchIntervalMs,
1176
+ batchSize: body.batchSize,
1177
+ extraLabels: body.extraLabels,
1178
+ tenantId: body.tenantId,
1179
+ username: body.username,
1180
+ password: body.password ?? "",
1181
+ timeoutMs: body.timeoutMs
767
1182
  };
768
1183
  }
769
1184
  getDestination() {
770
1185
  if (!this.destination) throw new Error("Loki logging not initialized");
771
1186
  return this.destination;
772
1187
  }
773
- globalSettingsSchema() {
1188
+ connectionForm() {
774
1189
  return this.schema({ sections: [{
775
1190
  id: "loki-logging",
776
1191
  title: "Loki",