@camstack/server 1.2.812 → 1.2.813

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 (95) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/api/core/cap-providers.js +50 -343
  3. package/dist/api/trpc/generated-cap-routers.js +9 -0
  4. package/dist/core/addon/addon-registry.service.js +31 -1
  5. package/dist/core/addon/addon-settings-provider.js +7 -1
  6. package/dist/core/addon/instance-lifecycle.js +454 -0
  7. package/dist/core/addon/instance-links.service.js +22 -14
  8. package/dist/core/moleculer/moleculer.service.js +15 -1
  9. package/package.json +11 -10
  10. package/system/dist/{agent-https-a3mE4PW4.js → agent-https-D9QbrCJe.js} +1 -1
  11. package/system/dist/{agent-https-CyEBY3RB.mjs → agent-https-D9rppK7L.mjs} +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  13. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  15. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  17. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  18. package/system/dist/builtins/autotrack/index.js +1 -1
  19. package/system/dist/builtins/autotrack/index.mjs +1 -1
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  21. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  22. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  23. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  24. package/system/dist/builtins/camera-grid/index.js +1 -1
  25. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  26. package/system/dist/builtins/composer/composer.addon.js +3 -3
  27. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  28. package/system/dist/builtins/console-logging/index.js +1 -1
  29. package/system/dist/builtins/console-logging/index.mjs +1 -1
  30. package/system/dist/builtins/core-blocks/blocks-instances.d.ts +22 -0
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.js +87 -4
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +77 -4
  34. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +7 -0
  35. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  36. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  37. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  38. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  39. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  40. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  41. package/system/dist/builtins/keychain/index.js +4 -4
  42. package/system/dist/builtins/keychain/index.mjs +4 -4
  43. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  45. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  46. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  47. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  48. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  49. package/system/dist/builtins/loki-logging/index.js +1 -1
  50. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  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 +1 -1
  56. package/system/dist/builtins/record-entries/index.mjs +1 -1
  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 +3 -3
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  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 +284 -284
  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/{capture-engine-ByF-6AFH.mjs → capture-engine-BI6Z09IS.mjs} +1 -1
  74. package/system/dist/{capture-engine-BO9mSlY-.js → capture-engine-Ba49uIhh.js} +1 -1
  75. package/system/dist/{composition-sources-AziMFo7T.mjs → composition-sources-BYhi_QpF.mjs} +1 -1
  76. package/system/dist/{composition-sources-BMJUPUh2.js → composition-sources-zbe-WMDR.js} +1 -1
  77. package/system/dist/{constants-CjRlgRlu.js → constants-Cz0UABmc.js} +1 -1
  78. package/system/dist/{constants-CTikgsC_.mjs → constants-ZS2PeV26.mjs} +1 -1
  79. package/system/dist/{device-ca-CNRlFqFC.mjs → device-ca-B0vxd075.mjs} +1 -1
  80. package/system/dist/{device-ca-Dxl6kVcJ.js → device-ca-BR52z--E.js} +1 -1
  81. package/system/dist/{dist-CkJnelZr.js → dist-Cjomt5bM.js} +526 -25
  82. package/system/dist/{dist-BPq13Y8j.mjs → dist-fY4FYIt2.mjs} +509 -26
  83. package/system/dist/file-host-worker.js +1 -1
  84. package/system/dist/file-host-worker.mjs +1 -1
  85. package/system/dist/{hub-mdns-ciao-Cx6yJBl9.js → hub-mdns-ciao-BIyx3H2u.js} +2 -2
  86. package/system/dist/{hub-mdns-ciao-CrjItezp.mjs → hub-mdns-ciao-CYUWFhn7.mjs} +2 -2
  87. package/system/dist/index.js +8 -8
  88. package/system/dist/index.mjs +8 -8
  89. package/system/dist/{legacy-integration-rows-door-CKM-LxvL.js → legacy-integration-rows-door-CoUG5oxu.js} +1 -1
  90. package/system/dist/{legacy-integration-rows-door-Dxcqwc-w.mjs → legacy-integration-rows-door-is18rCsc.mjs} +1 -1
  91. package/system/dist/{restore-archive-r3zTdLKr.mjs → restore-archive-Ce8tTRv4.mjs} +82 -82
  92. package/system/dist/{restore-archive-BQWOdGAB.js → restore-archive-ScKSg4cI.js} +1 -1
  93. package/system/dist/{wal-maintenance-zJ4-ORo6.mjs → wal-maintenance-gY_QtcBe.mjs} +0 -0
  94. package/system/dist/{wal-maintenance-CiCgL4Hp.js → wal-maintenance-oyAWwOGI.js} +0 -0
  95. package/system/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.813] - 2026-11-08
11
+
12
+ ### Changed
13
+
14
+ - Creating an instance that brings devices now writes the integration row, applies the connection-test gate (a kind that declares its own test is tested by it; a create without a kind takes the provider's default kind) and rolls back on failure; deleting one removes its devices, row and announces it
15
+ - The Blocks and Notification Center integrations now keep an instance record, and a fixed builtin keeps its on/off switch in the registry
16
+ - Generated cap routers gain heroLayout.getRowModels
17
+
10
18
  ## [1.2.812] - 2026-11-08
11
19
 
12
20
  ### Changed
@@ -78,7 +78,8 @@ const os = __importStar(require("node:os"));
78
78
  const system_1 = require("@camstack/server/system");
79
79
  const types_1 = require("@camstack/types");
80
80
  const server_1 = require("@trpc/server");
81
- const integration_id_backfill_1 = require("../../boot/integration-id-backfill");
81
+ const instance_lifecycle_1 = require("../../core/addon/instance-lifecycle");
82
+ const instance_links_service_1 = require("../../core/addon/instance-links.service");
82
83
  const addon_package_service_js_1 = require("../../core/addon/addon-package.service.js");
83
84
  const addon_uninstall_js_1 = require("../../core/addon/addon-uninstall.js");
84
85
  const agent_desired_set_1 = require("../../core/agent/agent-desired-set");
@@ -768,132 +769,6 @@ function getDeviceProvider(ar, addonId) {
768
769
  const provider = ar.getCapabilityRegistry().getProviderByAddon('device-provider', addonId);
769
770
  return isDeviceProvider(provider) ? provider : null;
770
771
  }
771
- // ── pre-creation connection test ────────────────────────────────────
772
- //
773
- // `integrations.create` gates on the instance's own test (D1016): an integration whose instances
774
- // declare a Test (`describe().canTest`) is asked through `integration-instances.testInstance`
775
- // with the draft values; one that declares none is a KNOWN `unsupported`, never a silent pass.
776
- // There is no default branch and the framework never guesses a test from the shape of the
777
- // settings.
778
- /** The addon that keeps the MQTT brokers: the instance a `brokerId` names lives there, not in the consumer. */
779
- const BROKER_OWNER_ADDON_ID = 'mqtt-broker';
780
- /**
781
- * The instances provider that owns the broker a settings blob NAMES. The consumer (`addonId`) holds a
782
- * link to a broker, not the broker, so the broker addon is asked first and the consumer's own provider
783
- * only when it lists that id itself.
784
- */
785
- async function findBrokerOwner(ar, addonId, brokerId) {
786
- for (const candidateId of [BROKER_OWNER_ADDON_ID, addonId]) {
787
- const candidate = getInstancesProvider(ar, candidateId);
788
- if (candidate === null || candidate.testInstance === undefined)
789
- continue;
790
- const rows = await candidate.listInstances();
791
- if (rows.some((row) => row.id === brokerId))
792
- return { addonId: candidateId, provider: candidate };
793
- }
794
- return null;
795
- }
796
- /**
797
- * Run the pre-creation test for `(addonId, settings)` through `testInstance`, the one test method.
798
- *
799
- * Never throws: a test that blows up is `inconclusive`, which is emphatically
800
- * NOT `rejected`. A timeout must not read as a refusal — it would block a
801
- * perfectly good create on a flaky network, and the operator would have no way
802
- * to tell the two apart.
803
- */
804
- async function testBeforeCreate(ar, addonId, settings, logger, kind) {
805
- // 0. An addon that keeps its connection as typed instances tests it there.
806
- const instances = getInstancesProvider(ar, addonId);
807
- let declaresTest = false;
808
- if (instances !== null && instances.testInstance !== undefined) {
809
- try {
810
- declaresTest = (await instances.describe()).canTest;
811
- }
812
- catch (err) {
813
- logger.warn('could not read whether the integration declares a test', {
814
- tags: { addonId },
815
- meta: { phase: 'test', error: (0, types_1.errMsg)(err) },
816
- });
817
- }
818
- }
819
- if (instances !== null && instances.testInstance !== undefined && declaresTest) {
820
- try {
821
- const result = await instances.testInstance({
822
- id: null,
823
- values: settings,
824
- ...(kind !== undefined ? { kind } : {}),
825
- });
826
- const status = result.status ?? (result.success ? 'validated' : 'rejected');
827
- return {
828
- status,
829
- testedBy: addonId,
830
- ...(result.error !== undefined ? { error: result.error } : {}),
831
- ...(result.latencyMs !== undefined ? { latencyMs: result.latencyMs } : {}),
832
- ...(result.detail !== undefined ? { detail: result.detail } : {}),
833
- };
834
- }
835
- catch (err) {
836
- logger.warn('connection test could not run', {
837
- tags: { addonId },
838
- meta: { phase: 'test', error: (0, types_1.errMsg)(err) },
839
- });
840
- return {
841
- status: 'inconclusive',
842
- error: `Connection test could not run: ${(0, types_1.errMsg)(err)}`,
843
- testedBy: addonId,
844
- };
845
- }
846
- }
847
- // 1. Broker-backed integrations carry their connection identity as a
848
- // `brokerId`; the broker already owns the real semantic check (HA opens a
849
- // temporary WS handshake, MQTT pings the bridge). Reached because the
850
- // settings NAME a broker, not because nothing else matched.
851
- const brokerId = settings['brokerId'];
852
- if (typeof brokerId === 'string' && brokerId.length > 0) {
853
- try {
854
- const owner = await findBrokerOwner(ar, addonId, brokerId);
855
- if (owner === null || owner.provider.testInstance === undefined) {
856
- logger.warn('no instances provider owns the broker a create names', {
857
- tags: { addonId },
858
- meta: { phase: 'test', brokerId },
859
- });
860
- return {
861
- status: 'inconclusive',
862
- error: `No instances provider that owns broker '${brokerId}' is available`,
863
- testedBy: null,
864
- };
865
- }
866
- const result = await owner.provider.testInstance({ id: brokerId, values: {} });
867
- const status = result.status ?? (result.success ? 'validated' : 'rejected');
868
- return {
869
- status,
870
- testedBy: owner.addonId,
871
- ...(result.error !== undefined ? { error: result.error } : {}),
872
- ...(result.latencyMs !== undefined ? { latencyMs: result.latencyMs } : {}),
873
- ...(result.detail !== undefined ? { detail: result.detail } : {}),
874
- };
875
- }
876
- catch (err) {
877
- logger.warn('broker connection test could not run', {
878
- tags: { addonId },
879
- meta: { phase: 'test', brokerId, error: (0, types_1.errMsg)(err) },
880
- });
881
- return {
882
- status: 'inconclusive',
883
- error: `Broker test could not run: ${(0, types_1.errMsg)(err)}`,
884
- testedBy: addonId,
885
- };
886
- }
887
- }
888
- // 2. Nothing declared. Say so plainly — this must never render as a pass,
889
- // and must never render as a failure we did not observe.
890
- return {
891
- status: 'unsupported',
892
- error: `Integration '${addonId}' declares no connection test, ` +
893
- `so these settings cannot be validated before it is created.`,
894
- testedBy: null,
895
- };
896
- }
897
772
  /**
898
773
  * Marker caps that flag an addon as a creatable integration type:
899
774
  * - `device-provider` — classic providers (Reolink/ONVIF)
@@ -955,10 +830,14 @@ function getInstancesProvider(ar, addonId) {
955
830
  * addon answers every row of it. An addon whose provider is not up, that keeps no instance for the
956
831
  * row, or that fails to answer keeps the registry's stored flag for that row, and a failure is
957
832
  * logged: a listing never fails because one addon did not answer.
833
+ *
834
+ * A FIXED builtin is the exception: its switch is the registry flag, the one store
835
+ * (`integrations.update`), and the name-only record it is seeded with carries no flag, which a
836
+ * body reads as "on". Its row is never projected.
958
837
  */
959
838
  async function projectSwitches(ar, logger, integrations) {
960
839
  const byAddon = new Map();
961
- for (const addonId of new Set(integrations.map((i) => i.addonId))) {
840
+ for (const addonId of new Set(integrations.filter((i) => !isFixedBuiltin(i)).map((i) => i.addonId))) {
962
841
  const provider = getInstancesProvider(ar, addonId);
963
842
  if (provider === null)
964
843
  continue;
@@ -974,12 +853,27 @@ async function projectSwitches(ar, logger, integrations) {
974
853
  }
975
854
  }
976
855
  return integrations.map((i) => {
856
+ if (isFixedBuiltin(i))
857
+ return i;
977
858
  const enabled = byAddon.get(i.addonId)?.get(i.id);
978
859
  return enabled === undefined ? i : { ...i, enabled };
979
860
  });
980
861
  }
862
+ /** A builtin the hub itself declared (`DeclaredDevices` marks it `fixed`); its switch is the registry flag. */
863
+ function isFixedBuiltin(integration) {
864
+ return integration.info['fixed'] === true;
865
+ }
981
866
  function buildIntegrationsProvider(ar, eb, loggingService, capabilityRegistry) {
982
867
  const logger = loggingService.createLogger('integrations');
868
+ const lifecycleDeps = {
869
+ logger,
870
+ integrations: () => requireIntegrationRegistry(ar),
871
+ deviceManager: () => capabilityRegistry?.getSingleton('device-manager') ?? null,
872
+ eventBus: eb,
873
+ providerFor: (addonId) => getInstancesProvider(ar, addonId),
874
+ holders: () => (0, instance_links_service_1.holdersOf)(ar.getCapabilityRegistry()),
875
+ manifestRole: () => undefined,
876
+ };
983
877
  const withProcessState = (i) => ({
984
878
  ...i,
985
879
  processState: ar.listAddons().find((a) => a.manifest.id === i.addonId)?.process?.state ?? 'unknown',
@@ -1009,131 +903,41 @@ function buildIntegrationsProvider(ar, eb, loggingService, capabilityRegistry) {
1009
903
  return projected ?? integration;
1010
904
  },
1011
905
  create: async (input) => {
1012
- const { settings, ...rest } = input;
1013
- const payload = rest;
906
+ const { settings } = input;
1014
907
  const reg = requireIntegrationRegistry(ar);
1015
908
  logger.info('request', {
1016
909
  tags: { addonId: input.addonId },
1017
910
  meta: { phase: 'create', name: input.name },
1018
911
  });
1019
- const addon = ar.listAddons().find((a) => a.manifest.id === input.addonId);
912
+ // The hub half is shared with the registered `integration-instances` provider
913
+ // (`instance-lifecycle.ts`): unique check, the D1016 gate, the row, the record, rollback.
1020
914
  const instances = getInstancesProvider(ar, input.addonId);
1021
- const instanceMode = instances !== null
1022
- ? (await instances.describe()).instanceMode === 'single'
1023
- ? 'unique'
1024
- : 'multiple'
1025
- : (addon?.declaration?.instanceMode ?? addon?.manifest?.instanceMode ?? 'multiple');
1026
- if (instanceMode === 'unique') {
1027
- const existing = (await reg.listIntegrations()).filter((i) => i.addonId === input.addonId);
1028
- if (existing.length > 0) {
1029
- logger.warn('rejected duplicate unique', {
1030
- tags: { addonId: input.addonId, integrationId: existing[0].id },
1031
- meta: { phase: 'create' },
1032
- });
1033
- throw new server_1.TRPCError({
1034
- code: 'CONFLICT',
1035
- message: `Addon "${input.addonId}" is unique-instance and already has an integration (${existing[0].id})`,
1036
- });
1037
- }
1038
- }
1039
- // ── the gate ────────────────────────────────────────────────────
1040
- //
1041
- // "Next" must validate and create ONLY on success. `rejected` is the one
1042
- // status that blocks: it means the remote was asked and said no. An
1043
- // `unsupported` (no test declared) or `inconclusive` (declared test could
1044
- // not complete) observed NOTHING about the credentials — refusing on
1045
- // those would make every integration lacking the hook uncreatable, and
1046
- // would fail a good create on a flaky network. They pass, and they SAY SO
1047
- // in the log: silence here would read as "validated".
1048
- const verdict = await testBeforeCreate(ar, input.addonId, settings ?? {}, logger, input.kind);
1049
- if (verdict.status === 'rejected') {
1050
- logger.warn('rejected — connection test refused the settings', {
1051
- tags: { addonId: input.addonId },
1052
- meta: {
1053
- phase: 'create',
1054
- status: verdict.status,
1055
- testedBy: verdict.testedBy,
1056
- },
1057
- });
1058
- throw new server_1.TRPCError({
1059
- code: 'BAD_REQUEST',
1060
- message: verdict.error ?? `Connection test failed for '${input.addonId}'`,
1061
- });
1062
- }
1063
- if (verdict.status === 'validated') {
1064
- logger.info('connection test validated — proceeding', {
1065
- tags: { addonId: input.addonId },
1066
- meta: { phase: 'create', latencyMs: verdict.latencyMs },
1067
- });
1068
- }
1069
- else {
1070
- logger.warn('creating without validation — the settings were not validated', {
1071
- tags: { addonId: input.addonId },
1072
- meta: {
1073
- phase: 'create',
1074
- status: verdict.status,
1075
- reason: verdict.error,
1076
- },
1077
- });
1078
- }
1079
- const integration = await reg.createIntegration(payload);
1080
- if (instances !== null) {
1081
- // The connection is a typed record keyed by the registry id. A refusal
1082
- // deletes the row: a registry entry with no record is an orphan.
1083
- try {
1084
- await instances.createInstance({
1085
- id: integration.id,
1086
- name: integration.name,
1087
- ...(input.kind !== undefined ? { kind: input.kind } : {}),
1088
- });
1089
- if (settings !== undefined && Object.keys(settings).length > 0) {
1090
- await instances.updateInstance({
1091
- id: integration.id,
1092
- values: settings,
915
+ const raw = instances === null ? null : (0, instance_lifecycle_1.rawInstancesProvider)(instances);
916
+ const addon = ar.listAddons().find((a) => a.manifest.id === input.addonId);
917
+ if (raw === null) {
918
+ const legacyMode = addon?.declaration?.instanceMode ?? addon?.manifest?.instanceMode ?? 'multiple';
919
+ if (legacyMode === 'unique') {
920
+ const existing = (await reg.listIntegrations()).filter((i) => i.addonId === input.addonId);
921
+ if (existing.length > 0) {
922
+ logger.warn('rejected duplicate unique', {
923
+ tags: { addonId: input.addonId, integrationId: existing[0].id },
924
+ meta: { phase: 'create' },
1093
925
  });
1094
- }
1095
- }
1096
- catch (err) {
1097
- await instances.deleteInstance({ id: integration.id }).catch(() => undefined);
1098
- try {
1099
- await reg.deleteIntegration(integration.id);
1100
- }
1101
- catch (rollbackErr) {
1102
- // The rollback failing must not hide WHY the create was refused.
1103
- logger.warn('instance record refused — registry row could not be removed', {
1104
- tags: {
1105
- integrationId: integration.id,
1106
- addonId: integration.addonId,
1107
- },
1108
- meta: { phase: 'create-rollback', error: (0, types_1.errMsg)(rollbackErr) },
926
+ throw new server_1.TRPCError({
927
+ code: 'CONFLICT',
928
+ message: `Addon "${input.addonId}" is unique-instance and already has an integration (${existing[0].id})`,
1109
929
  });
1110
930
  }
1111
- logger.warn('instance record refused — registry row removed', {
1112
- tags: {
1113
- integrationId: integration.id,
1114
- addonId: integration.addonId,
1115
- },
1116
- meta: { phase: 'create', error: (0, types_1.errMsg)(err) },
1117
- });
1118
- throw err;
1119
931
  }
1120
- logger.info('persisted as an instance record (no restart)', {
1121
- tags: { integrationId: integration.id, addonId: integration.addonId },
1122
- meta: { phase: 'create' },
1123
- });
1124
- return integration;
1125
- }
1126
- if (settings !== undefined && Object.keys(settings).length > 0) {
1127
- logger.warn('settings dropped — the addon has no instance record to store them', {
1128
- tags: { integrationId: integration.id, addonId: integration.addonId },
1129
- meta: { phase: 'create', keys: Object.keys(settings) },
1130
- });
1131
932
  }
1132
- logger.info('persisted', {
1133
- tags: { integrationId: integration.id, addonId: integration.addonId },
1134
- meta: { phase: 'create' },
933
+ return (0, instance_lifecycle_1.createRegisteredInstance)(lifecycleDeps, raw, {
934
+ addonId: input.addonId,
935
+ name: input.name,
936
+ ...(input.info !== undefined ? { info: input.info } : {}),
937
+ ...(input.originStableId !== undefined ? { originStableId: input.originStableId } : {}),
938
+ ...(input.kind !== undefined ? { kind: input.kind } : {}),
939
+ ...(settings !== undefined ? { settings } : {}),
1135
940
  });
1136
- return integration;
1137
941
  },
1138
942
  update: async (input) => {
1139
943
  const reg = requireIntegrationRegistry(ar);
@@ -1215,108 +1019,11 @@ function buildIntegrationsProvider(ar, eb, loggingService, capabilityRegistry) {
1215
1019
  });
1216
1020
  throw new Error(`Integration "${input.id}" not found`);
1217
1021
  }
1218
- // REFUSE BEFORE MUTATING ANYTHING.
1219
- //
1220
- // The registry enforces this too, but it is the LAST step here — and the
1221
- // device cascade below is deliberately best-effort, so a refusal that
1222
- // arrives afterwards has already destroyed every device the integration
1223
- // owned. That is not theoretical: it deleted the Notification Center's
1224
- // alarm panel (835) one second before the registry answered "is fixed",
1225
- // and the panel came back with a new id and no state, silently breaking
1226
- // every rule that named it.
1227
- if (system_1.IntegrationRegistry.isFixed(integration)) {
1228
- throw new Error(`integration "${input.id}" is fixed — it belongs to the addon that declared it and cannot be deleted`);
1229
- }
1230
- logger.info('removing', {
1231
- tags: { integrationId: input.id, addonId: integration.addonId },
1232
- meta: { phase: 'delete', name: integration.name },
1233
- });
1234
- // Cascade-delete every live device whose integrationId matches.
1235
- // Best-effort: a device-removal hiccup must not abort the integration
1236
- // delete — log a warning and continue so the record + event always fire.
1237
- const dm = capabilityRegistry?.getSingleton('device-manager') ?? null;
1238
- // Claim legacy un-tagged devices BEFORE the cascade. Devices created
1239
- // before stamping (or whose provider never stamps, e.g. `provider-rtsp`)
1240
- // carry no integrationId, so `removeByIntegration` (which matches on
1241
- // integrationId) would leave them orphaned forever once their integration
1242
- // is gone. While the integration record still exists, stamp the
1243
- // unambiguous ones (addons hosting exactly one integration) so the cascade
1244
- // below removes them too. Best-effort: never abort the delete.
1245
- if (dm?.listAll && dm?.setIntegrationId) {
1246
- try {
1247
- const [integrations, devices] = await Promise.all([
1248
- reg.listIntegrations(),
1249
- dm.listAll({}),
1250
- ]);
1251
- const stamps = (0, integration_id_backfill_1.planDeleteTimeStamps)(input.id, integrations.map((i) => ({ id: i.id, addonId: i.addonId })), devices.map((d) => ({
1252
- id: d.id,
1253
- addonId: d.addonId,
1254
- parentDeviceId: d.parentDeviceId,
1255
- ...(d.integrationId !== undefined ? { integrationId: d.integrationId } : {}),
1256
- })));
1257
- for (const stamp of stamps) {
1258
- await dm.setIntegrationId({
1259
- deviceId: stamp.deviceId,
1260
- integrationId: stamp.integrationId,
1261
- });
1262
- }
1263
- if (stamps.length > 0) {
1264
- logger.info('claimed legacy un-tagged devices for cascade', {
1265
- tags: { integrationId: input.id, addonId: integration.addonId },
1266
- meta: { phase: 'delete', claimed: stamps.length },
1267
- });
1268
- }
1269
- }
1270
- catch (err) {
1271
- logger.warn('legacy device claim failed (best-effort — continuing)', {
1272
- tags: { integrationId: input.id },
1273
- meta: { phase: 'delete', error: (0, types_1.errMsg)(err) },
1274
- });
1275
- }
1276
- }
1277
- if (dm?.removeByIntegration) {
1278
- try {
1279
- const result = await dm.removeByIntegration({
1280
- integrationId: input.id,
1281
- });
1282
- logger.info('cascade-removed devices', {
1283
- tags: { integrationId: input.id },
1284
- meta: { phase: 'delete', removed: result.removed },
1285
- });
1286
- }
1287
- catch (err) {
1288
- logger.warn('device cascade-remove failed (best-effort — continuing)', {
1289
- tags: { integrationId: input.id },
1290
- meta: { phase: 'delete', error: (0, types_1.errMsg)(err) },
1291
- });
1292
- }
1293
- }
1294
- else {
1295
- logger.warn('device-manager not available — skipping cascade device removal', {
1296
- tags: { integrationId: input.id },
1297
- meta: { phase: 'delete' },
1298
- });
1299
- }
1300
- // The record and its keychain refs go first; a refusal stops here, with
1301
- // the registry row still naming what was not removed.
1302
- await getInstancesProvider(ar, integration.addonId)?.deleteInstance({
1303
- id: input.id,
1304
- });
1305
- await reg.deleteIntegration(input.id);
1306
- eb.emit({
1307
- id: `integration-deleted-${Date.now()}`,
1308
- timestamp: new Date(),
1309
- source: { type: 'integration', id: input.id },
1310
- category: types_1.EventCategory.IntegrationDeleted,
1311
- data: {
1312
- integrationId: input.id,
1313
- addonId: integration.addonId,
1314
- },
1315
- });
1316
- logger.info('completed (no restart)', {
1317
- tags: { integrationId: input.id },
1318
- meta: { phase: 'delete' },
1319
- });
1022
+ // The hub half is shared with the registered `integration-instances` provider
1023
+ // (`instance-lifecycle.ts`): a fixed builtin and a linked instance are refused BEFORE the
1024
+ // first mutation, then the devices, the record, the row and the event.
1025
+ const instances = getInstancesProvider(ar, integration.addonId);
1026
+ await (0, instance_lifecycle_1.deleteRegisteredInstance)(lifecycleDeps, instances === null ? null : (0, instance_lifecycle_1.rawInstancesProvider)(instances), integration);
1320
1027
  return { success: true, deletedId: input.id };
1321
1028
  },
1322
1029
  getAvailableTypes: async () => {
@@ -5307,6 +5307,15 @@ function createCapRouter_heroLayout(getProvider, createRemoteProxy) {
5307
5307
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
5308
5308
  return p.getHeroModel(methodInput);
5309
5309
  }),
5310
+ getRowModels: trpc_middleware_js_1.protectedProcedure
5311
+ .input(types_69.heroLayoutCapability.methods.getRowModels.input.loose())
5312
+ .output(types_69.heroLayoutCapability.methods.getRowModels.output)
5313
+ .query(async ({ input, ctx }) => {
5314
+ const { nodeId, ...methodInput } = input;
5315
+ const p = resolveProvider('hero-layout', nodeId, () => getProvider(ctx), createRemoteProxy);
5316
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
5317
+ return p.getRowModels(methodInput);
5318
+ }),
5310
5319
  getLayout: trpc_middleware_js_1.protectedProcedure
5311
5320
  .input(types_69.heroLayoutCapability.methods.getLayout.input.loose())
5312
5321
  .output(types_69.heroLayoutCapability.methods.getLayout.output)
@@ -68,6 +68,7 @@ const runner_serialization_1 = require("./runner-serialization");
68
68
  const runner_spawn_fanout_js_1 = require("./runner-spawn-fanout.js");
69
69
  const integration_instances_provider_js_1 = require("./integration-instances-provider.js");
70
70
  const instance_links_service_js_1 = require("./instance-links.service.js");
71
+ const instance_lifecycle_js_1 = require("./instance-lifecycle.js");
71
72
  const settings_door_wiring_js_1 = require("./settings-door-wiring.js");
72
73
  /**
73
74
  * Decide whether an in-memory addon entry should be evicted because it is no
@@ -568,6 +569,7 @@ class AddonRegistryService {
568
569
  // active-singleton preference can select a grouped addon (whose child id
569
570
  // is its `execution.group`, not its own id). Identity for ungrouped addons.
570
571
  this.moleculer.setRunnerIdResolver((addonId) => this.childIdForAddon(addonId));
572
+ this.moleculer.setInstanceLifecycleWrap(this.instanceLifecycleWrap);
571
573
  const settingsProvider = (0, addon_settings_provider_js_1.createAddonSettingsProvider)({
572
574
  getAddon: (addonId) => {
573
575
  const entry = this.addonEntries.get(addonId);
@@ -1303,6 +1305,31 @@ class AddonRegistryService {
1303
1305
  async setAppRouter(_router) {
1304
1306
  this.logger.debug('setAppRouter called — broker-routed addon API in use, no direct caller needed');
1305
1307
  }
1308
+ /**
1309
+ * What the hub half of an `integration-instances` create and delete reads (epic #440, H3).
1310
+ * Every member is read when used, so a not-yet-wired registry fails the call, not the boot.
1311
+ */
1312
+ instanceLifecycleDeps() {
1313
+ return {
1314
+ logger: this.loggingService.createLogger('integrations'),
1315
+ integrations: () => {
1316
+ if (this.integrationRegistry === null) {
1317
+ throw new Error(`IntegrationRegistry not available: ${this.integrationRegistryUnavailable ?? 'its records are still being wired'}`);
1318
+ }
1319
+ return this.integrationRegistry;
1320
+ },
1321
+ deviceManager: () => this.capabilityRegistry.getSingleton('device-manager'),
1322
+ eventBus: this.eventBusService,
1323
+ providerFor: (addonId) => (0, integration_instances_provider_js_1.findInstancesProvider)(this.capabilityRegistry, addonId),
1324
+ holders: () => (0, instance_links_service_js_1.holdersOf)(this.capabilityRegistry),
1325
+ manifestRole: (addonId) => {
1326
+ const addon = this.listAddons().find((a) => a.manifest.id === addonId);
1327
+ return addon?.declaration?.integrationRole ?? addon?.manifest.integrationRole;
1328
+ },
1329
+ };
1330
+ }
1331
+ /** Registers an `integration-instances` provider with the hub half of create and delete around it. */
1332
+ instanceLifecycleWrap = (addonId, provider) => (0, instance_lifecycle_js_1.withInstanceLifecycle)(addonId, provider, this.instanceLifecycleDeps());
1306
1333
  /** Get the CapabilityRegistry for external consumers to register */
1307
1334
  getCapabilityRegistry() {
1308
1335
  return this.capabilityRegistry;
@@ -3037,7 +3064,10 @@ class AddonRegistryService {
3037
3064
  const nodeDataDir = path.resolve(process.env.CAMSTACK_DATA ?? 'camstack-data');
3038
3065
  const registerProvider = (capabilityName, provider) => {
3039
3066
  // An `integration-instances` holder is registered with its delete guarded by the link index (D1013).
3040
- this.capabilityRegistry.registerProvider(capabilityName, addonId, (0, instance_links_service_js_1.registeredProviderFor)(capabilityName, provider, this.capabilityRegistry));
3067
+ this.capabilityRegistry.registerProvider(capabilityName, addonId, (0, instance_links_service_js_1.registeredProviderFor)(capabilityName, provider, this.capabilityRegistry, {
3068
+ addonId,
3069
+ wrap: this.instanceLifecycleWrap,
3070
+ }));
3041
3071
  logger.info('Registered provider via context.registerProvider()', {
3042
3072
  meta: { capabilityName },
3043
3073
  });
@@ -155,7 +155,13 @@ function createAddonSettingsProvider(deps) {
155
155
  async getIntegrationFormSchema(input) {
156
156
  const instances = deps.instancesFor?.(input.addonId) ?? null;
157
157
  if (instances !== null) {
158
- return reshapeForOutput(await instances.instanceFormSchema({ id: input.instance.integrationId }));
158
+ return reshapeForOutput(await instances.instanceFormSchema({
159
+ id: input.instance.integrationId,
160
+ mode: input.instance.mode,
161
+ ...(input.instance.candidateStableId !== undefined
162
+ ? { candidateStableId: input.instance.candidateStableId }
163
+ : {}),
164
+ }));
159
165
  }
160
166
  if (gateway.isInProcess(input.addonId, input.nodeId)) {
161
167
  const addon = getAddon(input.addonId);