@camstack/types 1.2.601 → 1.2.603

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.
@@ -158,6 +158,116 @@ function findMigrationsBlocked(err) {
158
158
  return null;
159
159
  }
160
160
  //#endregion
161
+ //#region src/addon/instance-switches.ts
162
+ var SWITCHES = /* @__PURE__ */ new Map();
163
+ /** The ids the registry is known to hold a row for (hydrated, or told by the hub). */
164
+ var ROWS = /* @__PURE__ */ new Set();
165
+ /** The owner addon of an id, learned from its rows and from the helper that serves it. */
166
+ var OWNER_OF = /* @__PURE__ */ new Map();
167
+ /** The addons whose registry read answered at least once. */
168
+ var ANSWERED = /* @__PURE__ */ new Set();
169
+ /** The addons whose boot has begun reading the registry: only they can be held back. */
170
+ var HYDRATING = /* @__PURE__ */ new Set();
171
+ /**
172
+ * The addons that serve an instance kind and have not been answered by the registry yet. Scoped
173
+ * per owner: one addon's failed read never turns off another addon's instances, and an addon that
174
+ * serves no instance kind never enters it.
175
+ */
176
+ var PENDING = /* @__PURE__ */ new Set();
177
+ /**
178
+ * An addon's boot is about to read the registry for its rows. From now on, until the registry
179
+ * answers, its served instance kinds (already built or built later in its boot) fail closed. A
180
+ * helper used with no addon boot around it (a spec, a tool) is never held back.
181
+ */
182
+ function beginHydration(ownerId) {
183
+ if (ANSWERED.has(ownerId)) return;
184
+ HYDRATING.add(ownerId);
185
+ if (KINDS.has(ownerId)) PENDING.add(ownerId);
186
+ }
187
+ /** The helper of `ownerId` serves `id`: its fail-closed window is that owner's, not the process's. */
188
+ function claimInstance(ownerId, id) {
189
+ OWNER_OF.set(id, ownerId);
190
+ }
191
+ /** Whether `ownerId` still waits for the registry to answer (it serves a kind and has no rows yet). */
192
+ function isHydrationPending(ownerId) {
193
+ return PENDING.has(ownerId);
194
+ }
195
+ /** The owners still waiting for the registry. */
196
+ function pendingHydrationOwners() {
197
+ return [...PENDING];
198
+ }
199
+ /**
200
+ * The switch of `id` as this process knows it. An id nobody stated reads off while ITS owner waits
201
+ * for the registry, on afterwards (a fresh instance). An id with no known owner reads off while any
202
+ * owner waits.
203
+ */
204
+ function isInstanceOn(id) {
205
+ const stated = SWITCHES.get(id);
206
+ if (stated !== void 0) return stated;
207
+ const owner = OWNER_OF.get(id);
208
+ return owner === void 0 ? PENDING.size === 0 : !PENDING.has(owner);
209
+ }
210
+ /** Record a state this process holds for `id` (a local mirror; the registry may not have a row yet). */
211
+ function recordInstanceSwitch(id, enabled) {
212
+ SWITCHES.set(id, enabled);
213
+ }
214
+ /** Record what the hub told: the registry holds a row of `id` in this state. */
215
+ function recordRegistrySwitch(id, enabled) {
216
+ SWITCHES.set(id, enabled);
217
+ ROWS.add(id);
218
+ }
219
+ /** Whether the registry is known to hold a row for `id`. */
220
+ function hasRegistryRow(id) {
221
+ return ROWS.has(id);
222
+ }
223
+ /** The state this process holds for `id`, or undefined when it holds none. */
224
+ function statedInstanceSwitch(id) {
225
+ return SWITCHES.get(id);
226
+ }
227
+ /** Forget `id` (the instance was deleted). */
228
+ function forgetInstanceSwitch(id) {
229
+ SWITCHES.delete(id);
230
+ ROWS.delete(id);
231
+ OWNER_OF.delete(id);
232
+ }
233
+ /** Seed the store from the registry rows of `ownerId`; the registry answered, so the owner is known. */
234
+ function hydrateInstanceSwitches(ownerId, rows) {
235
+ ANSWERED.add(ownerId);
236
+ for (const row of rows) {
237
+ recordRegistrySwitch(row.id, row.enabled);
238
+ OWNER_OF.set(row.id, ownerId);
239
+ }
240
+ }
241
+ /** The addon's boot has built every instance kind and read the registry: unknown ids now read on. */
242
+ function settleHydration(ownerId) {
243
+ PENDING.delete(ownerId);
244
+ }
245
+ /** Spec seam: start from an empty store. */
246
+ function clearInstanceSwitches() {
247
+ SWITCHES.clear();
248
+ ROWS.clear();
249
+ OWNER_OF.clear();
250
+ ANSWERED.clear();
251
+ HYDRATING.clear();
252
+ PENDING.clear();
253
+ }
254
+ var KINDS = /* @__PURE__ */ new Map();
255
+ /**
256
+ * A helper announces the kind it serves, by owner addon. The one-time body-to-registry move
257
+ * (D1066) walks exactly these kinds, so an addon needs no list of its own: a record kind IS an
258
+ * instance kind precisely when a helper wraps it.
259
+ */
260
+ function registerServedInstanceKind(ownerId, served) {
261
+ const owned = KINDS.get(ownerId) ?? /* @__PURE__ */ new Map();
262
+ owned.set(served.kind.name, served);
263
+ KINDS.set(ownerId, owned);
264
+ if (HYDRATING.has(ownerId) && !ANSWERED.has(ownerId)) PENDING.add(ownerId);
265
+ }
266
+ /** The instance kinds announced for `ownerId` so far. */
267
+ function servedInstanceKindsOf(ownerId) {
268
+ return [...KINDS.get(ownerId)?.values() ?? []];
269
+ }
270
+ //#endregion
161
271
  //#region src/interfaces/config-ui-secrets.ts
162
272
  /**
163
273
  * The value a redacted secret is replaced with on every read surface.
@@ -1048,6 +1158,32 @@ function switchRecordsOverMigrationApi(api) {
1048
1158
  };
1049
1159
  } };
1050
1160
  }
1161
+ /** The record calls the body-to-registry switch migration makes, over the migration API. */
1162
+ function bodySwitchRecordsOverMigrationApi(api) {
1163
+ return { kind: (definition) => {
1164
+ const handle = api.records.kind(definition);
1165
+ return {
1166
+ query: async () => {
1167
+ const rows = [];
1168
+ let cursor;
1169
+ do {
1170
+ const page = await handle.query({
1171
+ limit: 500,
1172
+ ...cursor === void 0 ? {} : { cursor }
1173
+ });
1174
+ rows.push(...page.records);
1175
+ cursor = page.nextCursor ?? void 0;
1176
+ } while (cursor !== void 0);
1177
+ return { records: rows };
1178
+ },
1179
+ get: (id) => handle.get({ id }),
1180
+ put: (input, opts) => handle.put({
1181
+ ...input,
1182
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
1183
+ })
1184
+ };
1185
+ } };
1186
+ }
1051
1187
  /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
1052
1188
  function recordsOverMigrationApi(api) {
1053
1189
  return { kind: (definition) => {
@@ -1743,13 +1879,9 @@ function secretViewsOf(owner, kind, id, decl, data) {
1743
1879
  /** The most instances one addon lists (an integrations page, not a table). */
1744
1880
  var INSTANCES_LIST_MAX = 1e3;
1745
1881
  /**
1746
- * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
1747
- * before the field existed needs no migration. Every consumer of an instance body asks this.
1882
+ * The body key the switch USED to live under (D1007, D1015). Nothing writes or reads it any more;
1883
+ * the migrations that move it between the body and the registry name it.
1748
1884
  */
1749
- function isInstanceEnabled(body) {
1750
- return body.enabled !== false;
1751
- }
1752
- /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
1753
1885
  var SWITCH_KEY = "enabled";
1754
1886
  /**
1755
1887
  * The "Add device" mode an instance gets when its provider states none, from how the provider's
@@ -1791,6 +1923,20 @@ var RecordIntegrationInstances = class {
1791
1923
  secretKeys;
1792
1924
  secretMaps;
1793
1925
  nameField;
1926
+ /** The state each instance had when the addon last read it or was told it: {@link reapply} announces only a change. */
1927
+ knownSwitches = /* @__PURE__ */ new Map();
1928
+ /** What the addon reads for `id`: the switch as this process holds it, remembered as known. */
1929
+ knownSwitchOf(id) {
1930
+ claimInstance(this.records.owner, id);
1931
+ const enabled = isInstanceOn(id);
1932
+ this.knownSwitches.set(id, enabled);
1933
+ return enabled;
1934
+ }
1935
+ /** What a view of `id` shows; the addon did not read it, so nothing is remembered as known. */
1936
+ viewSwitchOf(id) {
1937
+ claimInstance(this.records.owner, id);
1938
+ return isInstanceOn(id);
1939
+ }
1794
1940
  switchListeners = /* @__PURE__ */ new Set();
1795
1941
  constructor(records, kind, hooks) {
1796
1942
  this.records = records;
@@ -1800,6 +1946,11 @@ var RecordIntegrationInstances = class {
1800
1946
  this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
1801
1947
  this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
1802
1948
  this.nameField = kind.declaration.entry?.nameField ?? "name";
1949
+ registerServedInstanceKind(records.owner, {
1950
+ kind,
1951
+ reapply: () => this.reapply(),
1952
+ unrowed: () => this.unrowed()
1953
+ });
1803
1954
  if (hooks.kindOf === void 0 && hooks.description.kinds.length !== 1) throw new Error(`record kind '${kind.name}': describe().kinds has ${hooks.description.kinds.length} entries, so kindOf is required to say which one an instance is`);
1804
1955
  }
1805
1956
  /**
@@ -1813,7 +1964,7 @@ var RecordIntegrationInstances = class {
1813
1964
  return record === null ? null : {
1814
1965
  id,
1815
1966
  body: record.data,
1816
- enabled: isInstanceEnabled(record.data),
1967
+ enabled: this.knownSwitchOf(id),
1817
1968
  secrets: "resolved"
1818
1969
  };
1819
1970
  } catch (err) {
@@ -1823,7 +1974,7 @@ var RecordIntegrationInstances = class {
1823
1974
  return {
1824
1975
  id,
1825
1976
  body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
1826
- enabled: isInstanceEnabled(stored.data),
1977
+ enabled: this.knownSwitchOf(id),
1827
1978
  secrets: "unavailable"
1828
1979
  };
1829
1980
  }
@@ -1862,7 +2013,7 @@ var RecordIntegrationInstances = class {
1862
2013
  id: record.id,
1863
2014
  name: typeof rawName === "string" ? rawName : record.id,
1864
2015
  configured: this.hooks.configured(record.data),
1865
- enabled: isInstanceEnabled(record.data),
2016
+ enabled: this.viewSwitchOf(record.id),
1866
2017
  formValues: shown,
1867
2018
  kind,
1868
2019
  addDevice: this.hooks.addDevice?.(record.data) ?? defaultAddDeviceMode(this.hooks.description),
@@ -1918,6 +2069,8 @@ var RecordIntegrationInstances = class {
1918
2069
  id: minted,
1919
2070
  data: initial
1920
2071
  }, { ifRev: 0 });
2072
+ claimInstance(this.records.owner, minted);
2073
+ recordRegistrySwitch(minted, true);
1921
2074
  if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
1922
2075
  await this.hooks.onChanged?.(minted, "created");
1923
2076
  return { id: minted };
@@ -1963,23 +2116,53 @@ var RecordIntegrationInstances = class {
1963
2116
  this.switchListeners.add(listener);
1964
2117
  }
1965
2118
  /**
1966
- * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
1967
- * configured thing is an instance, so an id with no record yet (a default integration that was
1968
- * never configured) gets its record from `initialBody` before the switch is written.
2119
+ * The hub's notification that the registry row of `id` moved (D1066). The registry holds the
2120
+ * switch; this keeps NO copy of it in the record. It remembers the state for this process's
2121
+ * readers ({@link isInstanceOn}), lets the addon re-apply, and fires the listeners.
1969
2122
  */
1970
2123
  setInstanceEnabled = async ({ id, enabled }) => {
1971
- if (await this.handle.get(id) === null) await this.handle.put({
1972
- id,
1973
- data: this.hooks.initialBody(id)
1974
- }, { ifRev: 0 });
1975
- await this.handle.patch(id, { [SWITCH_KEY]: enabled });
2124
+ claimInstance(this.records.owner, id);
2125
+ recordRegistrySwitch(id, enabled);
2126
+ this.knownSwitches.set(id, enabled);
1976
2127
  await this.hooks.onChanged?.(id, "enabled");
1977
2128
  for (const listener of this.switchListeners) await listener(id, enabled);
1978
2129
  return { ok: true };
1979
2130
  };
2131
+ /**
2132
+ * After the registry answered for a kind built before it could: announce the state of every
2133
+ * instance of this kind, on and off, so an addon that started on the fail-closed default (off)
2134
+ * starts what is on and stops what is off.
2135
+ */
2136
+ async reapply() {
2137
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
2138
+ for (const record of page.records) {
2139
+ claimInstance(this.records.owner, record.id);
2140
+ const enabled = isInstanceOn(record.id);
2141
+ if (this.knownSwitches.get(record.id) === enabled) continue;
2142
+ this.knownSwitches.set(record.id, enabled);
2143
+ await this.hooks.onChanged?.(record.id, "enabled");
2144
+ for (const listener of this.switchListeners) await listener(record.id, enabled);
2145
+ }
2146
+ }
2147
+ /**
2148
+ * The records of this kind the registry holds no row for: created outside the hub door (a
2149
+ * seed, a migration, a store write). Each carries the state this process holds for it, on when
2150
+ * it holds none, because on was its effective state before the registry owned the switch.
2151
+ */
2152
+ async unrowed() {
2153
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.filter((record) => !hasRegistryRow(record.id)).map((record) => {
2154
+ const name = record.data[this.nameField];
2155
+ return {
2156
+ id: record.id,
2157
+ name: typeof name === "string" ? name : record.id,
2158
+ enabled: statedInstanceSwitch(record.id) ?? true
2159
+ };
2160
+ });
2161
+ }
1980
2162
  /** The row and its keychain refs go together (the records door). */
1981
2163
  deleteInstance = async ({ id }) => {
1982
2164
  await this.handle.delete(id);
2165
+ forgetInstanceSwitch(id);
1983
2166
  await this.hooks.onChanged?.(id, "deleted");
1984
2167
  return { ok: true };
1985
2168
  };
@@ -2116,6 +2299,109 @@ function registrySwitchPortsOver(deps) {
2116
2299
  };
2117
2300
  }
2118
2301
  //#endregion
2302
+ //#region src/migrations/body-switch-to-registry.ts
2303
+ /**
2304
+ * The switch comes back to the registry (D1066), the reverse of {@link registrySwitchToBodyMigration}.
2305
+ * An instance's on/off state lived in its record body (`enabled`, D1007 superseded by D1015); the hub
2306
+ * registry row, keyed by (addon, integration id) like a device, is now the only stored switch.
2307
+ *
2308
+ * For every record of the addon's kind:
2309
+ * - the state is the body's `enabled` (absent means on). When the registry row of that id disagrees,
2310
+ * the BODY wins: it was the only live copy while the body held the switch, and the registry
2311
+ * column of a migrated row was never read;
2312
+ * - a record with no registry row gets one (a services instance, under its addon-minted id);
2313
+ * - the key is then removed from the body, so no second copy remains.
2314
+ * A rerun finds no body that states `enabled` and writes nothing. The registry write goes first, so
2315
+ * a crash between the two steps repeats the pair (idempotent) and never loses a switched-off state.
2316
+ *
2317
+ * It runs in the addon process, after {@link registrySwitchToBodyMigration}, BEFORE the addon
2318
+ * registers its provider.
2319
+ */
2320
+ function bodySwitchToRegistryId(addonId, date, kindName) {
2321
+ return `${addonId}/${date}-body-switch-to-registry-${kindName}`;
2322
+ }
2323
+ async function moveBodySwitchToRegistry(ports, spec) {
2324
+ const records = await ports.listRecords();
2325
+ const adopted = records.length === 0 ? {
2326
+ created: 0,
2327
+ updated: 0,
2328
+ conflicts: []
2329
+ } : await ports.adoptRows(spec.addonId, records.map((r) => ({
2330
+ id: r.id,
2331
+ name: r.name,
2332
+ enabled: r.enabled,
2333
+ stated: r.stated
2334
+ })));
2335
+ const foreign = new Map(adopted.conflicts.map((c) => [c.id, c.ownerAddonId]));
2336
+ for (const [id, owner] of foreign) await ports.warn(`body switch kept: the registry row "${id}" belongs to addon "${owner}", not "${spec.addonId}"`);
2337
+ const stated = records.filter((r) => r.stated && !foreign.has(r.id));
2338
+ for (const row of stated) await ports.stripSwitch(row.id);
2339
+ const summary = {
2340
+ records: records.length,
2341
+ stripped: stated.length,
2342
+ rowsCreated: adopted.created,
2343
+ rowsCorrected: adopted.updated,
2344
+ conflicts: adopted.conflicts.length
2345
+ };
2346
+ return stated.length === 0 && adopted.created === 0 && adopted.updated === 0 ? {
2347
+ outcome: "already-done",
2348
+ summary
2349
+ } : {
2350
+ outcome: "done",
2351
+ summary
2352
+ };
2353
+ }
2354
+ /** A migration entry: an addon states its kind, nothing else. */
2355
+ function bodySwitchToRegistryMigration(spec) {
2356
+ return {
2357
+ meta: {
2358
+ id: bodySwitchToRegistryId(spec.addonId, spec.date, spec.kindName),
2359
+ owner: spec.addonId,
2360
+ level: "addon-state",
2361
+ seq: spec.seq,
2362
+ dependsOn: spec.followsDate === void 0 ? [] : [registrySwitchToBodyId(spec.addonId, spec.followsDate)],
2363
+ store: "settings",
2364
+ scope: "cluster",
2365
+ onFailure: "block-owner",
2366
+ bodyKind: "procedure",
2367
+ description: "Move the switch of every instance record back to its registry row (creating the row of a services instance) and remove it from the body",
2368
+ fixtureMark: "enabled"
2369
+ },
2370
+ procedure: (ports) => moveBodySwitchToRegistry(ports, { addonId: spec.addonId })
2371
+ };
2372
+ }
2373
+ function bodySwitchPortsOver(deps) {
2374
+ const handle = deps.records.kind({
2375
+ name: deps.kind.name,
2376
+ declaration: deps.kind.declaration,
2377
+ schema: zod.z.record(zod.z.string(), zod.z.unknown())
2378
+ });
2379
+ return {
2380
+ listRecords: async () => {
2381
+ return (await handle.query({ limit: 1e3 })).records.map((r) => {
2382
+ const name = r.data[deps.nameField];
2383
+ return {
2384
+ id: r.id,
2385
+ name: typeof name === "string" ? name : r.id,
2386
+ enabled: r.data[SWITCH_KEY] !== false,
2387
+ stated: SWITCH_KEY in r.data
2388
+ };
2389
+ });
2390
+ },
2391
+ adoptRows: deps.adopt,
2392
+ warn: deps.warn,
2393
+ stripSwitch: async (id) => {
2394
+ const row = await handle.get(id);
2395
+ if (row === null || !("enabled" in row.data)) return;
2396
+ const { [SWITCH_KEY]: _dropped, ...rest } = row.data;
2397
+ await handle.put({
2398
+ id,
2399
+ data: rest
2400
+ }, { ifRev: row.rev });
2401
+ }
2402
+ };
2403
+ }
2404
+ //#endregion
2119
2405
  //#region src/addon/durable-state.ts
2120
2406
  /**
2121
2407
  * Build a {@link DurableState} over a single store key. Transport-agnostic:
@@ -2149,6 +2435,26 @@ function createDurableState(deps) {
2149
2435
  };
2150
2436
  }
2151
2437
  //#endregion
2438
+ //#region src/addon/instance-switches-unread-error.ts
2439
+ /**
2440
+ * The registry could not be read for the switches of an addon that serves instance kinds, so its
2441
+ * instances read off (D1066). A forked runner treats it as a failed boot: the supervisor respawns
2442
+ * it, bounded and marked terminally failed (D6), rather than leave instances off silently.
2443
+ */
2444
+ var INSTANCE_SWITCHES_UNREAD_ERROR_NAME = "InstanceSwitchesUnreadError";
2445
+ var InstanceSwitchesUnreadError = class extends Error {
2446
+ ownerId;
2447
+ constructor(ownerId) {
2448
+ super(`'${ownerId}': the registry did not answer for the instance switches; its instances stay off`);
2449
+ this.ownerId = ownerId;
2450
+ this.name = INSTANCE_SWITCHES_UNREAD_ERROR_NAME;
2451
+ }
2452
+ };
2453
+ /** By name, so a second copy of this module in a bundle still matches. */
2454
+ function isInstanceSwitchesUnreadError(err) {
2455
+ return err instanceof Error && err.name === "InstanceSwitchesUnreadError";
2456
+ }
2457
+ //#endregion
2152
2458
  //#region src/addon/per-node-store.ts
2153
2459
  /**
2154
2460
  * Per-node scoping for the shared addon-settings blob.
@@ -3208,7 +3514,14 @@ var BaseAddon = class {
3208
3514
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
3209
3515
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
3210
3516
  });
3517
+ await this.hydrateSwitches();
3211
3518
  const result = await this.onInitialize();
3519
+ await this.moveLateInstanceKinds();
3520
+ await this.adoptUnrowed();
3521
+ if (this.switchesHydrated) {
3522
+ settleHydration(this.ctx.id);
3523
+ for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
3524
+ }
3212
3525
  this.emitLifecycle(require_event_category.EventCategory.AddonStarted);
3213
3526
  const normalized = normalizeAddonInitResult(result);
3214
3527
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
@@ -3248,17 +3561,22 @@ var BaseAddon = class {
3248
3561
  this.retiredMigrationIds = ids;
3249
3562
  }
3250
3563
  registrySwitchSpec = null;
3564
+ /** The instance kinds whose switch move this process already ran (or tried), by record kind name. */
3565
+ switchMoved = /* @__PURE__ */ new Set();
3566
+ lastDeclared = [];
3251
3567
  registrySwitchBound() {
3252
- const spec = this.registrySwitchSpec;
3253
- if (spec === null) return [];
3254
3568
  const api = this.ctx.migrationApi;
3569
+ const spec = this.registrySwitchSpec;
3570
+ const kinds = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
3571
+ if (spec === null && kinds.length === 0) return [];
3255
3572
  if (api === void 0) {
3256
3573
  this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
3257
3574
  return [];
3258
3575
  }
3259
- return migrationSet([registrySwitchToBodyMigration({
3576
+ const date = "2026-11-06";
3577
+ const moveIn = spec === null ? [] : migrationSet([registrySwitchToBodyMigration({
3260
3578
  addonId: this.ctx.id,
3261
- date: "2026-11-06",
3579
+ date,
3262
3580
  seq: 1e3,
3263
3581
  initialBody: spec.initialBody
3264
3582
  })], (a) => registrySwitchPortsOver({
@@ -3266,13 +3584,53 @@ var BaseAddon = class {
3266
3584
  records: switchRecordsOverMigrationApi(a),
3267
3585
  kind: spec.kind
3268
3586
  })).bind(api);
3587
+ const moveBack = kinds.flatMap(({ kind }, index) => {
3588
+ this.switchMoved.add(kind.name);
3589
+ return migrationSet([bodySwitchToRegistryMigration({
3590
+ addonId: this.ctx.id,
3591
+ date: "2026-11-19",
3592
+ seq: 1001 + index,
3593
+ kindName: kind.name,
3594
+ ...spec === null ? {} : { followsDate: date }
3595
+ })], (a) => bodySwitchPortsOver({
3596
+ records: bodySwitchRecordsOverMigrationApi(a),
3597
+ kind,
3598
+ nameField: kind.declaration.entry?.nameField ?? "name",
3599
+ adopt: (addonId, rows) => this.ctx.api.integrations.adoptInstanceRows.mutate({
3600
+ addonId,
3601
+ rows: [...rows]
3602
+ }),
3603
+ warn: async (message) => {
3604
+ await a.log.warn({ message });
3605
+ }
3606
+ })).bind(api);
3607
+ });
3608
+ return [...moveIn, ...moveBack];
3609
+ }
3610
+ /**
3611
+ * A helper built AFTER the addon's migrations ran has a kind that moved nothing yet. Run its
3612
+ * switch move now (the engine replaces an owner's catalogue on every declare, so the whole
3613
+ * declared set goes with it, phased to the late ids), read the registry again, and tell the
3614
+ * addon about every instance that is off so it stops what it started on the default.
3615
+ */
3616
+ async moveLateInstanceKinds() {
3617
+ const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
3618
+ if (late.length === 0) return;
3619
+ try {
3620
+ const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
3621
+ await this.runBound(this.lastDeclared, { only });
3622
+ } catch (err) {
3623
+ if (err instanceof AddonMigrationsBlockedError) throw err;
3624
+ this.ctx.logger.error("the late instance switch move failed", { meta: { error: require_composed_stable_id.errMsg(err) } });
3625
+ }
3269
3626
  }
3270
3627
  async runBound(declared, options) {
3628
+ this.lastDeclared = declared;
3271
3629
  const added = this.registrySwitchBound();
3272
3630
  const migrations = [...declared, ...added];
3273
3631
  const widened = options?.only === void 0 || added.length === 0 ? options : {
3274
3632
  ...options,
3275
- only: [...options.only, ...added.map((m) => m.meta.id)]
3633
+ only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
3276
3634
  };
3277
3635
  const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
3278
3636
  ...widened,
@@ -3285,9 +3643,87 @@ var BaseAddon = class {
3285
3643
  finishMigration: (input) => api.finishMigration.mutate(input)
3286
3644
  }, migrations, this.ctx.logger, phased);
3287
3645
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
3646
+ await this.hydrateSwitches();
3647
+ await this.adoptUnrowed();
3288
3648
  return report;
3289
3649
  }
3290
3650
  /**
3651
+ * Learn the on/off state of this addon's instances from the registry rows (D1066), at boot, after
3652
+ * a migration run, and again through {@link rehydrateSwitches}. It runs on the addon's own boot
3653
+ * path, never inside a method the hub calls into. A registry that cannot answer leaves the
3654
+ * instances of THIS addon reading off (fail closed, per owner) until a read answers.
3655
+ */
3656
+ switchesHydrated = false;
3657
+ async hydrateSwitches() {
3658
+ beginHydration(this.ctx.id);
3659
+ try {
3660
+ const rows = await this.ctx.api.integrations.listByAddon.query({ addonId: this.ctx.id });
3661
+ hydrateInstanceSwitches(this.ctx.id, rows);
3662
+ this.switchesHydrated = true;
3663
+ return true;
3664
+ } catch (err) {
3665
+ this.ctx.logger.warn("instance switches not read from the registry: instances stay off", { meta: { error: require_composed_stable_id.errMsg(err) } });
3666
+ return false;
3667
+ }
3668
+ }
3669
+ /**
3670
+ * Every record of a served kind the registry holds no row for (created outside the hub door:
3671
+ * a seed, a store write) is adopted with the state it effectively had, on unless this process
3672
+ * stated it off, so the hub can switch it. A failure is logged; the next hydration retries.
3673
+ */
3674
+ async adoptUnrowed() {
3675
+ if (!this.switchesHydrated) return;
3676
+ try {
3677
+ for (const served of servedInstanceKindsOf(this.ctx.id)) {
3678
+ const rows = await served.unrowed();
3679
+ if (rows.length === 0) continue;
3680
+ await this.ctx.api.integrations.adoptInstanceRows.mutate({
3681
+ addonId: this.ctx.id,
3682
+ rows: rows.map((r) => ({
3683
+ id: r.id,
3684
+ name: r.name,
3685
+ enabled: r.enabled,
3686
+ stated: false
3687
+ }))
3688
+ });
3689
+ for (const r of rows) recordRegistrySwitch(r.id, r.enabled);
3690
+ }
3691
+ } catch (err) {
3692
+ this.ctx.logger.warn("records without a registry row were not adopted", { meta: { error: require_composed_stable_id.errMsg(err) } });
3693
+ }
3694
+ }
3695
+ /**
3696
+ * Read the switches from the registry again and announce the states now known, so an addon that
3697
+ * started on the fail-closed default (off) starts what is on. Throws
3698
+ * {@link InstanceSwitchesUnreadError} when the registry still does not answer while this addon
3699
+ * serves instance kinds: a forked runner turns that into a failed boot (the supervisor respawns
3700
+ * it, bounded, D6), an agent or the hub reads again on the next hub connect (event-driven, D3).
3701
+ * An addon with no instance kind has nothing waiting and never throws.
3702
+ */
3703
+ async rehydrateSwitches() {
3704
+ if (this._ctx === null) return;
3705
+ if (await this.hydrateSwitches()) {
3706
+ await this.adoptUnrowed();
3707
+ settleHydration(this.ctx.id);
3708
+ for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
3709
+ return;
3710
+ }
3711
+ if (isHydrationPending(this.ctx.id)) throw new InstanceSwitchesUnreadError(this.ctx.id);
3712
+ }
3713
+ /**
3714
+ * Called on the hub-reachable event (instead of `onHubReachable` directly): the switches are
3715
+ * read again, then `onHubReachable` runs. A registry that still does not answer is logged and
3716
+ * left for the next connect.
3717
+ */
3718
+ async hubReachable() {
3719
+ try {
3720
+ await this.rehydrateSwitches();
3721
+ } catch (err) {
3722
+ this.ctx.logger.warn("instance switches still unread at the hub connect", { meta: { error: require_composed_stable_id.errMsg(err) } });
3723
+ }
3724
+ await this.onHubReachable();
3725
+ }
3726
+ /**
3291
3727
  * Called by the isolated-process runner AFTER `broker.start()`.
3292
3728
  * In-process addons never need this because the hub broker is already
3293
3729
  * running when `initialize()` fires. For forked children the broker
@@ -21004,6 +21440,152 @@ var RUNTIME_DEFAULTS = {
21004
21440
  "auth.tokenExpiry": "30d"
21005
21441
  };
21006
21442
  //#endregion
21443
+ //#region src/device/device-restore-retry.ts
21444
+ /**
21445
+ * Delays before retry rounds 1..N — the round count IS the bound.
21446
+ * 10 s catches "the hub was busy for a moment"; the full schedule
21447
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
21448
+ * per attempt) covers a device-manager lock held for minutes — the
21449
+ * 2026-09-04 outage's migration hold was ~3.5 min.
21450
+ */
21451
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
21452
+ 1e4,
21453
+ 3e4,
21454
+ 9e4
21455
+ ];
21456
+ /** Lane width for retry rounds. See module docblock — retries are
21457
+ * evidence of congestion, so they never re-stampede full-width. */
21458
+ var DEVICE_RESTORE_RETRY_CONCURRENCY = 4;
21459
+ /** Abortable sleep — resolves early (never rejects) on abort. */
21460
+ function sleep$1(ms, signal) {
21461
+ return new Promise((resolve) => {
21462
+ if (signal.aborted) {
21463
+ resolve();
21464
+ return;
21465
+ }
21466
+ const onAbort = () => {
21467
+ clearTimeout(timer);
21468
+ resolve();
21469
+ };
21470
+ const timer = setTimeout(() => {
21471
+ signal.removeEventListener("abort", onAbort);
21472
+ resolve();
21473
+ }, ms);
21474
+ timer.unref?.();
21475
+ signal.addEventListener("abort", onAbort, { once: true });
21476
+ });
21477
+ }
21478
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
21479
+ * not reject (callers wrap their own try/catch). */
21480
+ async function runWithConcurrency(items, width, fn) {
21481
+ const queue = [...items];
21482
+ const laneCount = Math.max(1, Math.min(width, queue.length));
21483
+ const lane = async () => {
21484
+ for (;;) {
21485
+ const item = queue.shift();
21486
+ if (item === void 0) return;
21487
+ await fn(item);
21488
+ }
21489
+ };
21490
+ await Promise.all(Array.from({ length: laneCount }, lane));
21491
+ }
21492
+ var DeviceRestoreRetryScheduler = class {
21493
+ #logger;
21494
+ #attempt;
21495
+ #onPermanentFailure;
21496
+ #delaysMs;
21497
+ #concurrency;
21498
+ #now;
21499
+ #abort = new AbortController();
21500
+ constructor(options) {
21501
+ this.#logger = options.logger;
21502
+ this.#attempt = options.attempt;
21503
+ this.#onPermanentFailure = options.onPermanentFailure;
21504
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
21505
+ this.#concurrency = options.concurrency ?? 4;
21506
+ this.#now = options.now ?? Date.now;
21507
+ }
21508
+ /** Stop retrying (shutdown). Pending entries are NOT marked
21509
+ * permanently failed — the next boot restores them from disk. */
21510
+ cancel() {
21511
+ this.#abort.abort();
21512
+ }
21513
+ /**
21514
+ * Run the bounded retry rounds. Resolves when every entry has either
21515
+ * restored, been marked permanently failed, or the scheduler was
21516
+ * cancelled. Never rejects.
21517
+ */
21518
+ async run(initialFailures) {
21519
+ let pending = initialFailures.map((failure) => ({
21520
+ saved: failure.saved,
21521
+ lastError: failure.error,
21522
+ attempts: 1
21523
+ }));
21524
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
21525
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
21526
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
21527
+ if (this.#abort.signal.aborted) break;
21528
+ pending = await this.#runRound(pending, round);
21529
+ }
21530
+ if (this.#abort.signal.aborted) return [];
21531
+ const terminal = pending.map((entry) => ({
21532
+ deviceId: entry.saved.id,
21533
+ stableId: entry.saved.stableId,
21534
+ type: String(entry.saved.type),
21535
+ attempts: entry.attempts,
21536
+ lastError: entry.lastError,
21537
+ failedAt: this.#now()
21538
+ }));
21539
+ for (const failure of terminal) this.#onPermanentFailure(failure);
21540
+ return terminal;
21541
+ }
21542
+ /** One retry round: parents first (phase 0), then hub-adopted
21543
+ * children (phase 1) — a child's attempt depends on its parent
21544
+ * having landed, exactly like the initial two-pass restore. */
21545
+ async #runRound(pending, round) {
21546
+ const next = [];
21547
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
21548
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
21549
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
21550
+ if (this.#abort.signal.aborted) {
21551
+ next.push(entry);
21552
+ return;
21553
+ }
21554
+ const attemptNo = entry.attempts + 1;
21555
+ try {
21556
+ await this.#attempt(entry.saved);
21557
+ this.#logger.info("Device restored on retry", {
21558
+ tags: {
21559
+ deviceId: entry.saved.id,
21560
+ stableId: entry.saved.stableId
21561
+ },
21562
+ meta: { attempt: attemptNo }
21563
+ });
21564
+ } catch (err) {
21565
+ const lastError = err instanceof Error ? err.message : String(err);
21566
+ const remainingRetries = this.#delaysMs.length - (round + 1);
21567
+ this.#logger.warn("Device restore retry failed", {
21568
+ tags: {
21569
+ deviceId: entry.saved.id,
21570
+ stableId: entry.saved.stableId
21571
+ },
21572
+ meta: {
21573
+ attempt: attemptNo,
21574
+ remainingRetries,
21575
+ error: lastError
21576
+ }
21577
+ });
21578
+ next.push({
21579
+ saved: entry.saved,
21580
+ lastError,
21581
+ attempts: attemptNo
21582
+ });
21583
+ }
21584
+ });
21585
+ return next;
21586
+ }
21587
+ };
21588
+ //#endregion
21007
21589
  //#region src/device/cap-vocabulary/command-catalog.ts
21008
21590
  /**
21009
21591
  * The command catalogue (D1022): which cap methods are COMMANDS - the
@@ -23542,6 +24124,18 @@ Object.defineProperty(exports, "DEVICE_CHILDREN_BATCH_MAX", {
23542
24124
  return DEVICE_CHILDREN_BATCH_MAX;
23543
24125
  }
23544
24126
  });
24127
+ Object.defineProperty(exports, "DEVICE_RESTORE_RETRY_CONCURRENCY", {
24128
+ enumerable: true,
24129
+ get: function() {
24130
+ return DEVICE_RESTORE_RETRY_CONCURRENCY;
24131
+ }
24132
+ });
24133
+ Object.defineProperty(exports, "DEVICE_RESTORE_RETRY_DELAYS_MS", {
24134
+ enumerable: true,
24135
+ get: function() {
24136
+ return DEVICE_RESTORE_RETRY_DELAYS_MS;
24137
+ }
24138
+ });
23545
24139
  Object.defineProperty(exports, "DEVICE_SCOPED_CAPS", {
23546
24140
  enumerable: true,
23547
24141
  get: function() {
@@ -23620,6 +24214,12 @@ Object.defineProperty(exports, "DeviceCommandSettledEventSchema", {
23620
24214
  return DeviceCommandSettledEventSchema;
23621
24215
  }
23622
24216
  });
24217
+ Object.defineProperty(exports, "DeviceRestoreRetryScheduler", {
24218
+ enumerable: true,
24219
+ get: function() {
24220
+ return DeviceRestoreRetryScheduler;
24221
+ }
24222
+ });
23623
24223
  Object.defineProperty(exports, "DeviceTransitionSchema", {
23624
24224
  enumerable: true,
23625
24225
  get: function() {
@@ -23698,6 +24298,12 @@ Object.defineProperty(exports, "HISTORY_UNIT_LABELS", {
23698
24298
  return HISTORY_UNIT_LABELS;
23699
24299
  }
23700
24300
  });
24301
+ Object.defineProperty(exports, "InstanceSwitchesUnreadError", {
24302
+ enumerable: true,
24303
+ get: function() {
24304
+ return InstanceSwitchesUnreadError;
24305
+ }
24306
+ });
23701
24307
  Object.defineProperty(exports, "InvalidRecordError", {
23702
24308
  enumerable: true,
23703
24309
  get: function() {
@@ -24310,12 +24916,48 @@ Object.defineProperty(exports, "baseUnitOf", {
24310
24916
  return baseUnitOf;
24311
24917
  }
24312
24918
  });
24919
+ Object.defineProperty(exports, "beginHydration", {
24920
+ enumerable: true,
24921
+ get: function() {
24922
+ return beginHydration;
24923
+ }
24924
+ });
24925
+ Object.defineProperty(exports, "bodySwitchPortsOver", {
24926
+ enumerable: true,
24927
+ get: function() {
24928
+ return bodySwitchPortsOver;
24929
+ }
24930
+ });
24931
+ Object.defineProperty(exports, "bodySwitchRecordsOverMigrationApi", {
24932
+ enumerable: true,
24933
+ get: function() {
24934
+ return bodySwitchRecordsOverMigrationApi;
24935
+ }
24936
+ });
24937
+ Object.defineProperty(exports, "bodySwitchToRegistryId", {
24938
+ enumerable: true,
24939
+ get: function() {
24940
+ return bodySwitchToRegistryId;
24941
+ }
24942
+ });
24943
+ Object.defineProperty(exports, "bodySwitchToRegistryMigration", {
24944
+ enumerable: true,
24945
+ get: function() {
24946
+ return bodySwitchToRegistryMigration;
24947
+ }
24948
+ });
24313
24949
  Object.defineProperty(exports, "buildSecretRef", {
24314
24950
  enumerable: true,
24315
24951
  get: function() {
24316
24952
  return buildSecretRef;
24317
24953
  }
24318
24954
  });
24955
+ Object.defineProperty(exports, "claimInstance", {
24956
+ enumerable: true,
24957
+ get: function() {
24958
+ return claimInstance;
24959
+ }
24960
+ });
24319
24961
  Object.defineProperty(exports, "classifySecretWrite", {
24320
24962
  enumerable: true,
24321
24963
  get: function() {
@@ -24328,6 +24970,12 @@ Object.defineProperty(exports, "classifyStoreError", {
24328
24970
  return classifyStoreError;
24329
24971
  }
24330
24972
  });
24973
+ Object.defineProperty(exports, "clearInstanceSwitches", {
24974
+ enumerable: true,
24975
+ get: function() {
24976
+ return clearInstanceSwitches;
24977
+ }
24978
+ });
24331
24979
  Object.defineProperty(exports, "clearKnownSecrets", {
24332
24980
  enumerable: true,
24333
24981
  get: function() {
@@ -24640,6 +25288,12 @@ Object.defineProperty(exports, "forbiddenError", {
24640
25288
  return forbiddenError;
24641
25289
  }
24642
25290
  });
25291
+ Object.defineProperty(exports, "forgetInstanceSwitch", {
25292
+ enumerable: true,
25293
+ get: function() {
25294
+ return forgetInstanceSwitch;
25295
+ }
25296
+ });
24643
25297
  Object.defineProperty(exports, "forgetKnownSecret", {
24644
25298
  enumerable: true,
24645
25299
  get: function() {
@@ -24688,6 +25342,12 @@ Object.defineProperty(exports, "historyUnitFor", {
24688
25342
  return historyUnitFor;
24689
25343
  }
24690
25344
  });
25345
+ Object.defineProperty(exports, "hydrateInstanceSwitches", {
25346
+ enumerable: true,
25347
+ get: function() {
25348
+ return hydrateInstanceSwitches;
25349
+ }
25350
+ });
24691
25351
  Object.defineProperty(exports, "hydrateSchema", {
24692
25352
  enumerable: true,
24693
25353
  get: function() {
@@ -24748,10 +25408,22 @@ Object.defineProperty(exports, "isEvent", {
24748
25408
  return isEvent;
24749
25409
  }
24750
25410
  });
24751
- Object.defineProperty(exports, "isInstanceEnabled", {
25411
+ Object.defineProperty(exports, "isHydrationPending", {
25412
+ enumerable: true,
25413
+ get: function() {
25414
+ return isHydrationPending;
25415
+ }
25416
+ });
25417
+ Object.defineProperty(exports, "isInstanceOn", {
24752
25418
  enumerable: true,
24753
25419
  get: function() {
24754
- return isInstanceEnabled;
25420
+ return isInstanceOn;
25421
+ }
25422
+ });
25423
+ Object.defineProperty(exports, "isInstanceSwitchesUnreadError", {
25424
+ enumerable: true,
25425
+ get: function() {
25426
+ return isInstanceSwitchesUnreadError;
24755
25427
  }
24756
25428
  });
24757
25429
  Object.defineProperty(exports, "isKeychainStoredField", {
@@ -24892,6 +25564,12 @@ Object.defineProperty(exports, "modelFormatForRuntime", {
24892
25564
  return modelFormatForRuntime;
24893
25565
  }
24894
25566
  });
25567
+ Object.defineProperty(exports, "moveBodySwitchToRegistry", {
25568
+ enumerable: true,
25569
+ get: function() {
25570
+ return moveBodySwitchToRegistry;
25571
+ }
25572
+ });
24895
25573
  Object.defineProperty(exports, "moveRegistrySwitchToBody", {
24896
25574
  enumerable: true,
24897
25575
  get: function() {
@@ -24988,6 +25666,12 @@ Object.defineProperty(exports, "parseSecretStatePath", {
24988
25666
  return parseSecretStatePath;
24989
25667
  }
24990
25668
  });
25669
+ Object.defineProperty(exports, "pendingHydrationOwners", {
25670
+ enumerable: true,
25671
+ get: function() {
25672
+ return pendingHydrationOwners;
25673
+ }
25674
+ });
24991
25675
  Object.defineProperty(exports, "pythonScriptForBackend", {
24992
25676
  enumerable: true,
24993
25677
  get: function() {
@@ -25030,6 +25714,18 @@ Object.defineProperty(exports, "recordArrayItemPath", {
25030
25714
  return recordArrayItemPath;
25031
25715
  }
25032
25716
  });
25717
+ Object.defineProperty(exports, "recordInstanceSwitch", {
25718
+ enumerable: true,
25719
+ get: function() {
25720
+ return recordInstanceSwitch;
25721
+ }
25722
+ });
25723
+ Object.defineProperty(exports, "recordRegistrySwitch", {
25724
+ enumerable: true,
25725
+ get: function() {
25726
+ return recordRegistrySwitch;
25727
+ }
25728
+ });
25033
25729
  Object.defineProperty(exports, "recordSecretCollection", {
25034
25730
  enumerable: true,
25035
25731
  get: function() {
@@ -25210,6 +25906,12 @@ Object.defineProperty(exports, "selectAssignedProfileSlots", {
25210
25906
  return selectAssignedProfileSlots;
25211
25907
  }
25212
25908
  });
25909
+ Object.defineProperty(exports, "settleHydration", {
25910
+ enumerable: true,
25911
+ get: function() {
25912
+ return settleHydration;
25913
+ }
25914
+ });
25213
25915
  Object.defineProperty(exports, "shortSecretRefHash", {
25214
25916
  enumerable: true,
25215
25917
  get: function() {