@camstack/addon-export-google 0.1.1 → 0.1.3

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.
@@ -11379,6 +11379,28 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
11379
11379
  content: string()
11380
11380
  })) }), { auth: "admin" });
11381
11381
  /**
11382
+ * Identity — preserves literal types for downstream inference.
11383
+ *
11384
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
11385
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
11386
+ * the broader unions declared on `CustomActionSpec`'s default generics.
11387
+ * Shape validity is enforced separately by the `customAction(...)` helper
11388
+ * whose return type is already a `CustomActionSpec<...>`.
11389
+ */
11390
+ function defineCustomActions(spec) {
11391
+ return spec;
11392
+ }
11393
+ function customAction(input, output, options) {
11394
+ return {
11395
+ input,
11396
+ output,
11397
+ kind: options?.kind ?? "query",
11398
+ auth: options?.auth ?? "protected",
11399
+ scope: options?.scope ?? { kind: "system" },
11400
+ ...options?.caller ? { caller: "required" } : {}
11401
+ };
11402
+ }
11403
+ /**
11382
11404
  * `custom-model-registry` — collection cap exposing operator-registered
11383
11405
  * custom detection models. Each provider (today: `addon-model-studio`)
11384
11406
  * contributes a list of `CustomModelDescriptor`s; the hub auto-concatenates
@@ -13447,6 +13469,114 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
13447
13469
  limit: number().optional(),
13448
13470
  tags: record(string(), string()).optional()
13449
13471
  }), array(LogEntrySchema).readonly());
13472
+ /**
13473
+ * `failure-contribution` — the capability an addon reports its OWN losses
13474
+ * through, per camera, with the denominator attached. It stores nothing.
13475
+ *
13476
+ * ## The twin of `load-contribution`, and why it is a twin and not a field
13477
+ *
13478
+ * `load-contribution` answers *what did this camera COST*. This answers *what
13479
+ * did this camera LOSE*. The reporting discipline is identical and deliberately
13480
+ * copied: the contributor reports what it already knows, hub-main adds only
13481
+ * `addonId`, nothing needs global knowledge, and there is no central list for
13482
+ * somebody to forget to edit.
13483
+ *
13484
+ * They are not merged, because their invariants are opposites:
13485
+ *
13486
+ * - a `load-contribution` measurement is **absent, never zero** — a zero would
13487
+ * claim a camera cost nothing, which is a measurement nobody made;
13488
+ * - a `failure-contribution` zero is the **most valuable value on the
13489
+ * surface** — `attempts: 400, succeeded: 400` is the proof a fix landed,
13490
+ * and it is exactly what an absent entry cannot say.
13491
+ *
13492
+ * Putting a loss counter on a cost entry would also break the reconciliation
13493
+ * that gives `load-contribution` its point: contributions are subtracted from
13494
+ * `metrics.node-processes-snapshot` to find processes nobody claims. A failure
13495
+ * has no process.
13496
+ *
13497
+ * ## Why not a log line, since the counters already exist
13498
+ *
13499
+ * Several of these paths already counted themselves — `CaptureScheduler`'s
13500
+ * per-device window, `KeyFrameCaptureLog`, `bumpCropMetric`. Every one of them
13501
+ * ends in a log line, and a log line is the thing the operator asked to stop
13502
+ * needing: *"possiamo armare questi errori intanto? Così al prossimo giro
13503
+ * ricontrolliamo tutti questi punti"*. Reading them meant grepping Loki and
13504
+ * hand-correlating timestamps, which is how a 22% thumbnail gap and a 3-hour
13505
+ * media blackout were both diagnosed. The counters stay; this is where they can
13506
+ * be READ.
13507
+ *
13508
+ * ## The rate is served with its denominator or not at all
13509
+ *
13510
+ * Every entry carries `attempts` and `succeeded`. A miss count alone is
13511
+ * unreadable: on 2026-08-28 the enrichment-crop miss count read as "35x worse
13512
+ * than yesterday" and was **flat across twelve hours** once divided by the
13513
+ * successes on the same path. A surface that publishes only the numerator
13514
+ * reproduces that mistake on every read.
13515
+ *
13516
+ * ## Shape
13517
+ *
13518
+ * Copied from `load-contribution.cap.ts` (`mode: 'collection'`,
13519
+ * `internal: true`, `mount: { kind: 'skip' }`): no tRPC route of its own and no
13520
+ * generated hooks, while `addons.listCapabilityProviders` still enumerates it
13521
+ * and the hub's `CapabilityRegistry` still holds an RPC proxy per provider — so
13522
+ * a forked runner's entries reach hub-main over transport that already exists.
13523
+ * No new UDS message, no second registry (D3). The operator reads the assembled
13524
+ * result through `system.getFailureContributions`.
13525
+ */
13526
+ var FailureReasonCountSchema = object({
13527
+ /**
13528
+ * Why the attempt did not land, in the contributor's own vocabulary —
13529
+ * `worker-lease-gone`, `queue-overflow`, `timeout`, `empty-read`. The same
13530
+ * strings that already appear in this repo's logs and, where one exists, the
13531
+ * same string the per-track `previewMissReason` records (D276): a second
13532
+ * vocabulary for the same loss would make the row and the counter
13533
+ * un-joinable.
13534
+ */
13535
+ reason: string(),
13536
+ count: number().int().nonnegative()
13537
+ });
13538
+ var FailureContributionSchema = object({
13539
+ /**
13540
+ * The failing path — `enrichment-crop`, `inference`, `plate-ocr`,
13541
+ * `person-over-vehicle`. Free text, for the reason `load-contribution` keeps
13542
+ * `unit` free: the families are owned by different addons and a shared enum
13543
+ * is a central list that rots invisibly.
13544
+ */
13545
+ family: string(),
13546
+ /**
13547
+ * The NUMERIC device id — the same value every log line carries as
13548
+ * `tags.deviceId`. Never nullable and never absent: a contributor that
13549
+ * cannot name the camera must not emit the entry, because a fleet total
13550
+ * cannot answer the only question anybody asks of this surface.
13551
+ */
13552
+ deviceId: number().int().positive(),
13553
+ /**
13554
+ * A second dimension inside the family: the model / step id for an inference
13555
+ * timeout, so "which camera AND which model" is one read. Absent when the
13556
+ * family has a single variant.
13557
+ */
13558
+ variant: string().optional(),
13559
+ /**
13560
+ * Epoch ms this counter started — the INCARNATION MARKER. A consumer
13561
+ * differencing two reads must drop the interval when it changes, because the
13562
+ * counter restarted from zero in a respawned runner. Same discipline as
13563
+ * `LoadContribution.startedAtMs`.
13564
+ */
13565
+ sinceMs: number(),
13566
+ /** Epoch ms it was read. `atMs - sinceMs` is the interval this covers. */
13567
+ atMs: number(),
13568
+ /**
13569
+ * THE DENOMINATOR — every attempt on this path for this camera in the
13570
+ * window. A failure count published without it is the mistake this schema
13571
+ * exists to make impossible.
13572
+ */
13573
+ attempts: number().int().nonnegative(),
13574
+ /** Attempts that landed. `attempts - succeeded` is the loss. */
13575
+ succeeded: number().int().nonnegative(),
13576
+ /** The loss, partitioned. Sums to `attempts - succeeded`. */
13577
+ reasons: array(FailureReasonCountSchema).readonly()
13578
+ });
13579
+ method(_void(), array(FailureContributionSchema).readonly());
13450
13580
  var LoadContributionSchema = object({
13451
13581
  role: _enum([
13452
13582
  "decode",
@@ -17975,6 +18105,20 @@ var TrackSchema = object({
17975
18105
  * `=== true` and render nothing otherwise — never infer "no rider".
17976
18106
  */
17977
18107
  hasRider: boolean().optional(),
18108
+ /**
18109
+ * WHY this track ended without a NATIVE best-shot tile
18110
+ * ([D276](../decisions/adr-0276-a-stand-in-tile-is-provisional-and-a-close-says-why.md)) —
18111
+ * a composed token line (`no-key-frame capture=keyframe:native-missx4`,
18112
+ * `derive-returned-null tile=standin`, …) written at close and CLEARED by
18113
+ * the late-keyFrame upgrade when a native tile lands after all. The
18114
+ * operator-facing answer to "perché manca l'immagine?" on a track whose
18115
+ * tile is a face/plate stand-in, a raster crop, or an icon.
18116
+ *
18117
+ * **Absent ≠ "missed silently"**: a row written before the column, a hub
18118
+ * that predates the field, and every track whose tile landed native all
18119
+ * omit it. Render nothing when absent.
18120
+ */
18121
+ previewMissReason: string().optional(),
17978
18122
  ...TrackFlagFields,
17979
18123
  ...TrackRetrainFields
17980
18124
  });
@@ -27220,6 +27364,13 @@ var LoggingSettingsPatchSchema = object({
27220
27364
  * anyone but its owner.
27221
27365
  */
27222
27366
  var ReportedLoadContributionSchema = LoadContributionSchema.extend({ addonId: string() });
27367
+ /**
27368
+ * One per-camera failure counter, plus WHO reported it.
27369
+ *
27370
+ * Same rule as {@link ReportedLoadContributionSchema}: `addonId` is stamped by
27371
+ * the hub as it enumerates providers, never by the contributor.
27372
+ */
27373
+ var ReportedFailureContributionSchema = FailureContributionSchema.extend({ addonId: string() });
27223
27374
  var GetLoggingSettingsInputSchema = object({
27224
27375
  scopeNodeId: string().optional(),
27225
27376
  /**
@@ -27278,7 +27429,7 @@ method(_void(), FeatureManifestSchema), method(_void(), HealthStatusSchema), met
27278
27429
  }), method(_void(), SiteLocationStatusSchema, {
27279
27430
  kind: "mutation",
27280
27431
  auth: "admin"
27281
- }), method(_void(), RequestCensusStatusSchema, { auth: "admin" }), method(_void(), array(ReportedLoadContributionSchema).readonly(), { auth: "admin" }), method(GetLoggingSettingsInputSchema, LoggingSettingsStateSchema, { auth: "admin" }), method(SetLoggingSettingsInputSchema, LoggingSettingsStateSchema, {
27432
+ }), method(_void(), RequestCensusStatusSchema, { auth: "admin" }), method(_void(), array(ReportedLoadContributionSchema).readonly(), { auth: "admin" }), method(_void(), array(ReportedFailureContributionSchema).readonly(), { auth: "admin" }), method(GetLoggingSettingsInputSchema, LoggingSettingsStateSchema, { auth: "admin" }), method(SetLoggingSettingsInputSchema, LoggingSettingsStateSchema, {
27282
27433
  kind: "mutation",
27283
27434
  auth: "admin"
27284
27435
  });
@@ -29860,6 +30011,12 @@ Object.freeze({
29860
30011
  addonId: null,
29861
30012
  access: "create"
29862
30013
  },
30014
+ "failureContribution.list": {
30015
+ capName: "failure-contribution",
30016
+ capScope: "system",
30017
+ addonId: null,
30018
+ access: "view"
30019
+ },
29863
30020
  "fanControl.setDirection": {
29864
30021
  capName: "fan-control",
29865
30022
  capScope: "device",
@@ -33166,6 +33323,12 @@ Object.freeze({
33166
33323
  addonId: null,
33167
33324
  access: "create"
33168
33325
  },
33326
+ "system.getFailureContributions": {
33327
+ capName: "system",
33328
+ capScope: "system",
33329
+ addonId: null,
33330
+ access: "view"
33331
+ },
33169
33332
  "system.getLoadContributions": {
33170
33333
  capName: "system",
33171
33334
  capScope: "system",
@@ -36053,6 +36216,32 @@ DEFAULT_NATIVE_LEASE_SETTINGS.admission;
36053
36216
  var MB = 1024 * 1024;
36054
36217
  1024 * MB, 3072 * MB;
36055
36218
  //#endregion
36219
+ //#region src/custom-actions.ts
36220
+ /**
36221
+ * Google Home export — customActions catalog.
36222
+ *
36223
+ * One entry. The settings form's `type: 'button'` field dispatches through the
36224
+ * generic `api.addons.custom.mutate({ addonId, action, input })` channel, so a
36225
+ * button here costs no capability, no codegen and no framework publish train —
36226
+ * the catalog travels inside this addon's own bundle.
36227
+ */
36228
+ var exportGoogleActions = defineCustomActions({
36229
+ /**
36230
+ * Re-scan the connected `network-access` providers and refresh the address
36231
+ * shown under the field.
36232
+ *
36233
+ * Deliberately NOT the same contract as `export-alexa`'s action of the same
36234
+ * shape: that one replaces a manual override when it is no longer detected,
36235
+ * because Alexa ROUTES on the value. Nothing routes on this one — it is what
36236
+ * the operator already pasted into Google's console — so this only fills the
36237
+ * field when it is empty. `filled` says whether it did.
36238
+ */
36239
+ detectPublicHubUrl: customAction(object({}).optional(), object({
36240
+ publicHubUrl: string(),
36241
+ detectedPublicHubUrl: string(),
36242
+ filled: boolean()
36243
+ }), { kind: "mutation" }) });
36244
+ //#endregion
36056
36245
  //#region src/google-home/trait-catalog.ts
36057
36246
  /**
36058
36247
  * The trait catalog — one ROW per camstack capability, and that row is the
@@ -36081,7 +36270,7 @@ var MB = 1024 * 1024;
36081
36270
  * Cameras. Google's `CameraStream` trait answers `GetCameraStream` with a
36082
36271
  * playable URL or a WebRTC signaling endpoint, and neither exists here yet, so
36083
36272
  * a camera would be declared and then fail every command. It is omitted rather
36084
- * than declared — see docs/decisions/adr-0268-one-capability-is-one-trait-row-that-declares-reads-and-writes.md.
36273
+ * than declared — see docs/decisions/adr-0273-one-capability-is-one-trait-row-that-declares-reads-and-writes.md.
36085
36274
  */
36086
36275
  /**
36087
36276
  * The Google state a SUCCEEDED call establishes.
@@ -36830,9 +37019,262 @@ function buildGoogleOauthIntegration() {
36830
37019
  };
36831
37020
  }
36832
37021
  //#endregion
37022
+ //#region src/public-hub-url.ts
37023
+ /**
37024
+ * The hub's public HTTPS origin — detected, never invented.
37025
+ *
37026
+ * `publicHubUrl` is the single operator-facing value in this addon, and the
37027
+ * three URLs pasted into the Google Home Developer Console (fulfillment,
37028
+ * authorization, token) are all rendered from it. Nothing ROUTES on it: Google
37029
+ * calls the fulfillment URL it was configured with. A wrong value therefore
37030
+ * fails at paste time, in the console, hours before anything here notices —
37031
+ * which is exactly why the field has to say where its content came from.
37032
+ *
37033
+ * ## Where the URL comes from
37034
+ *
37035
+ * The `network-access` capability, same source `addon-export-alexa` uses. It is
37036
+ * a codegen'd collection cap with `scope: 'system'`, so it is reachable
37037
+ * cross-process through `ctx.api` — unlike the `addons` core router, which a
37038
+ * forked addon calling `ctx.api.addons.*` would wait on forever.
37039
+ *
37040
+ * **Not** `CAMSTACK_HUB_PUBLIC_URL`. That variable answers a different
37041
+ * question: which origin the hub should mint its OWN media / model-distribution
37042
+ * links on, and it defaults to `https://127.0.0.1:4443`. It is routinely a
37043
+ * loopback or LAN address, and the backend's `publicHubUrl()` fallback is
37044
+ * localhost in dev. Google calls from its own cloud, so a LAN answer here is
37045
+ * worse than no answer — it produces three console URLs that look complete and
37046
+ * can never be reached.
37047
+ *
37048
+ * ## Why this is a second copy of Alexa's mechanism
37049
+ *
37050
+ * Alexa's lives in `packages/addon-export-alexa/src/export-alexa.addon.ts` as
37051
+ * private methods, and addons never import each other. The only shared home
37052
+ * would be `@camstack/types` or `@camstack/system` — both stay host-resolved in
37053
+ * an addon bundle (`tools/build/vite-lib.preset.ts`), so putting it there would
37054
+ * put this addon on the framework publish train and destroy the one property
37055
+ * that makes it attractive: `camstack deploy packages/addon-export-google` and
37056
+ * nothing else. The SOURCE and the POLICY are Alexa's; two behaviours diverge
37057
+ * on purpose and both are named below.
37058
+ *
37059
+ * ## Two deliberate divergences from Alexa
37060
+ *
37061
+ * 1. **Refresh never clobbers.** Alexa's `redetectPublicHubUrl` replaces a
37062
+ * manual override whenever it is not among the detected endpoints — sound
37063
+ * there, because the URL is baked into every Alexa-bound JWT as a routing
37064
+ * claim and a stale one breaks routing. Here the value is what the operator
37065
+ * already pasted into Google's console; silently rewriting it would leave
37066
+ * the console and the hub disagreeing with no visible cause. Detection fills
37067
+ * an EMPTY field and does nothing else.
37068
+ * 2. **A non-routable origin is dropped.** Alexa forwards whatever the cap
37069
+ * reports. See {@link isPubliclyRoutableOrigin}.
37070
+ */
37071
+ /** Trailing slashes off, surrounding space off. Nothing else is rewritten. */
37072
+ var normalisePublicHubUrl = (raw) => raw.trim().replace(/\/+$/, "");
37073
+ var LOOPBACK_HOSTS = [
37074
+ "localhost",
37075
+ "127.0.0.1",
37076
+ "::1",
37077
+ "[::1]",
37078
+ "0.0.0.0"
37079
+ ];
37080
+ /**
37081
+ * Whether Google's cloud could plausibly reach this origin.
37082
+ *
37083
+ * The `network-access` providers this hub ships (Cloudflare Tunnel, Tailscale
37084
+ * Funnel) publish public FQDNs, but the cap does not promise it: a provider is
37085
+ * free to report an HTTPS ingress on a private address. Defaulting the field to
37086
+ * one of those would hand the operator three console URLs that look finished
37087
+ * and can never answer — strictly worse than an empty field, because an empty
37088
+ * field is visibly unfinished.
37089
+ *
37090
+ * Conservative on purpose: only loopback, RFC1918, link-local, `.local` and
37091
+ * dotless hostnames are refused. A public tunnel hostname always has a dot.
37092
+ */
37093
+ var isPubliclyRoutableOrigin = (origin) => {
37094
+ let host;
37095
+ try {
37096
+ host = new URL(origin).hostname.toLowerCase();
37097
+ } catch {
37098
+ return false;
37099
+ }
37100
+ if (host.length === 0) return false;
37101
+ if (LOOPBACK_HOSTS.includes(host)) return false;
37102
+ if (host.startsWith("127.") || host.startsWith("169.254.")) return false;
37103
+ if (host.startsWith("10.") || host.startsWith("192.168.")) return false;
37104
+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(host)) return false;
37105
+ if (host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan")) return false;
37106
+ if (!host.includes(".")) return false;
37107
+ return true;
37108
+ };
37109
+ /**
37110
+ * Every publicly routable HTTPS origin the `network-access` cap reports, in the
37111
+ * cap's own order, deduped. Empty when there is none — the caller leaves the
37112
+ * field alone rather than inventing a value.
37113
+ */
37114
+ var detectPublicHubOrigins = async (deps) => {
37115
+ const fromList = await originsFromListEndpoints(deps);
37116
+ if (fromList.length > 0) return fromList;
37117
+ const fromStatus = await originFromGetStatus(deps);
37118
+ if (fromStatus.length > 0) return [fromStatus];
37119
+ deps.logger.warn("export-google: no connected HTTPS external address — the public hub URL cannot be derived, so the Google console URLs stay unrendered. Set up remote access (Cloudflare Tunnel, Tailscale Funnel, …) and press \"Detect external address\", or type the URL on the settings form.");
37120
+ return [];
37121
+ };
37122
+ var usableOrigins = (candidates, logger) => {
37123
+ const out = /* @__PURE__ */ new Set();
37124
+ for (const candidate of candidates) {
37125
+ if (candidate.protocol !== "https" || candidate.url.length === 0) continue;
37126
+ const origin = normalisePublicHubUrl(candidate.url);
37127
+ if (!isPubliclyRoutableOrigin(origin)) {
37128
+ logger.info("export-google: ignored an external address that is not reachable from the internet — Google calls the fulfillment URL from its own cloud", { meta: { origin } });
37129
+ continue;
37130
+ }
37131
+ out.add(origin);
37132
+ }
37133
+ return [...out];
37134
+ };
37135
+ var originsFromListEndpoints = async (deps) => {
37136
+ try {
37137
+ return usableOrigins(await deps.network.listEndpoints(), deps.logger);
37138
+ } catch (err) {
37139
+ deps.logger.debug("export-google: networkAccess.listEndpoints failed", { meta: { error: errMsg(err) } });
37140
+ return [];
37141
+ }
37142
+ };
37143
+ var originFromGetStatus = async (deps) => {
37144
+ try {
37145
+ const status = await deps.network.getStatus();
37146
+ if (status === null || !status.connected || status.endpoint === null) return "";
37147
+ return usableOrigins([status.endpoint], deps.logger)[0] ?? "";
37148
+ } catch (err) {
37149
+ deps.logger.debug("export-google: networkAccess.getStatus failed", { meta: { error: errMsg(err) } });
37150
+ return "";
37151
+ }
37152
+ };
37153
+ /**
37154
+ * Apply the default-not-override policy.
37155
+ *
37156
+ * The operator's value is never in the returned patch. Detection's own answer
37157
+ * always is, because the settings panel needs it to say "you set this one, and
37158
+ * a different one is detected".
37159
+ */
37160
+ var resolvePublicHubUrl = (current, detected) => {
37161
+ const detectedPublicHubUrl = detected[0] ?? "";
37162
+ if (current.length > 0) return {
37163
+ patch: { detectedPublicHubUrl },
37164
+ publicHubUrl: current,
37165
+ detectedPublicHubUrl,
37166
+ defaulted: false
37167
+ };
37168
+ if (detectedPublicHubUrl.length === 0) return {
37169
+ patch: { detectedPublicHubUrl },
37170
+ publicHubUrl: "",
37171
+ detectedPublicHubUrl,
37172
+ defaulted: false
37173
+ };
37174
+ return {
37175
+ patch: {
37176
+ publicHubUrl: detectedPublicHubUrl,
37177
+ detectedPublicHubUrl
37178
+ },
37179
+ publicHubUrl: detectedPublicHubUrl,
37180
+ detectedPublicHubUrl,
37181
+ defaulted: true
37182
+ };
37183
+ };
37184
+ /** Which of the two authored the value currently in the field. */
37185
+ var publicHubUrlSource = (state) => {
37186
+ if (state.publicHubUrl.length === 0) return "unset";
37187
+ if (state.detectedPublicHubUrl.length > 0 && state.publicHubUrl === state.detectedPublicHubUrl) return "derived";
37188
+ return "operator-set";
37189
+ };
37190
+ /**
37191
+ * The line under the field. A URL that appeared by itself with no provenance is
37192
+ * worse than a blank field: the operator cannot tell whether it is right.
37193
+ */
37194
+ var buildPublicHubUrlNotice = (state) => {
37195
+ switch (publicHubUrlSource(state)) {
37196
+ case "derived": return {
37197
+ variant: "info",
37198
+ content: `Derived from remote access — ${state.publicHubUrl} is the first HTTPS address the network-access capability reports. Edit the field to override it; nothing here ever overwrites a value you set.`
37199
+ };
37200
+ case "operator-set": return {
37201
+ variant: "info",
37202
+ content: state.detectedPublicHubUrl.length > 0 ? `Set by you — ${state.publicHubUrl}. The address currently detected from remote access is ${state.detectedPublicHubUrl}; paste it in yourself if you want to switch, detection will not do it for you.` : `Set by you — ${state.publicHubUrl}. No external HTTPS address is detected right now, so nothing is corroborating it.`
37203
+ };
37204
+ case "unset": return state.detectedPublicHubUrl.length > 0 ? {
37205
+ variant: "info",
37206
+ content: `Detected external address: ${state.detectedPublicHubUrl}. Press "Detect external address" to fill the field with it.`
37207
+ } : {
37208
+ variant: "warning",
37209
+ content: "No public HTTPS address detected — no network-access provider on this hub reports a connected HTTPS endpoint, so there is nothing to derive from. Set up remote access (Cloudflare Tunnel, Tailscale Funnel, …) and press \"Detect external address\", or type the URL yourself. An address on your own network will not do: Google calls this URL from its own cloud."
37210
+ };
37211
+ }
37212
+ };
37213
+ /**
37214
+ * The `device-export` setup block: the three console URLs plus the
37215
+ * linked-account count. All three come off the SAME origin, so they can never
37216
+ * disagree with each other.
37217
+ */
37218
+ var buildConsoleSetup = (input) => {
37219
+ const origin = normalisePublicHubUrl(input.publicHubUrl);
37220
+ const linked = String(input.linkedAccounts);
37221
+ if (origin.length === 0) return {
37222
+ note: ["Set the public hub URL on the settings form first — every URL Google needs is derived from it.", buildPublicHubUrlNotice(input).content].join("\n"),
37223
+ fields: [{
37224
+ label: "Linked Google accounts",
37225
+ value: linked
37226
+ }]
37227
+ };
37228
+ return {
37229
+ note: [
37230
+ "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
37231
+ "The integration stays in test mode: publishing requires Google certification, which a private hub cannot obtain.",
37232
+ "This hub pushes nothing to Google — state is read by polling, so a change made outside the Home app appears on the next query, not instantly.",
37233
+ buildPublicHubUrlNotice(input).content
37234
+ ].join("\n"),
37235
+ fields: [
37236
+ {
37237
+ label: "Fulfillment URL",
37238
+ value: `${origin}/addon/${input.addonId}/fulfillment`
37239
+ },
37240
+ {
37241
+ label: "Authorization URL",
37242
+ value: `${origin}/api/oauth2/authorize?integration=${input.addonId}`
37243
+ },
37244
+ {
37245
+ label: "Token URL",
37246
+ value: `${origin}/api/oauth2/token`
37247
+ },
37248
+ {
37249
+ label: "Linked Google accounts",
37250
+ value: linked
37251
+ }
37252
+ ]
37253
+ };
37254
+ };
37255
+ /**
37256
+ * Detect, apply the policy, persist, and say out loud what happened.
37257
+ *
37258
+ * Every branch here logs: a fill names the URL it picked and the source it came
37259
+ * from, and a miss that leaves the field empty says so rather than passing for
37260
+ * "never ran".
37261
+ */
37262
+ var refreshPublicHubUrl = async (deps) => {
37263
+ const detected = await deps.detect();
37264
+ const resolution = resolvePublicHubUrl(deps.current().publicHubUrl, detected);
37265
+ await deps.persist(resolution.patch);
37266
+ if (resolution.defaulted) deps.logger.info("export-google: defaulted public hub URL to the detected external address", { meta: {
37267
+ publicHubUrl: resolution.publicHubUrl,
37268
+ source: "network-access"
37269
+ } });
37270
+ else if (resolution.publicHubUrl.length === 0) deps.logger.warn("export-google: public hub URL still unset after detection — the Google console URLs cannot be rendered until one is available", { meta: { detectedCount: detected.length } });
37271
+ return resolution;
37272
+ };
37273
+ //#endregion
36833
37274
  //#region src/types.ts
36834
37275
  var DEFAULT_SETTINGS = {
36835
37276
  publicHubUrl: "",
37277
+ detectedPublicHubUrl: "",
36836
37278
  exposed: [],
36837
37279
  linkedAccounts: []
36838
37280
  };
@@ -36871,7 +37313,7 @@ var DEFAULT_SETTINGS = {
36871
37313
  *
36872
37314
  * Switches, dimmable lights, locks and covers — the non-camera fleet neither
36873
37315
  * `export-hap` nor `export-alexa` covers. Cameras are out of scope on purpose
36874
- * (docs/decisions/adr-0268-one-capability-is-one-trait-row-that-declares-reads-and-writes.md); the trait catalog is the single place that
37316
+ * (docs/decisions/adr-0273-one-capability-is-one-trait-row-that-declares-reads-and-writes.md); the trait catalog is the single place that
36875
37317
  * decides, so widening scope is one row.
36876
37318
  */
36877
37319
  var ADDON_ID = "export-google";
@@ -36886,6 +37328,9 @@ var ExportGoogleAddon = class extends BaseAddon {
36886
37328
  logger: this.ctx.logger
36887
37329
  });
36888
37330
  this.gateway = gateway;
37331
+ this.detectPublicHubUrl().catch((err) => {
37332
+ this.ctx.logger.warn("export-google: public hub URL auto-detect failed", { meta: { error: errMsg(err) } });
37333
+ });
36889
37334
  const deviceExportProvider = {
36890
37335
  getStatus: async () => ({
36891
37336
  linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
@@ -36925,26 +37370,93 @@ var ExportGoogleAddon = class extends BaseAddon {
36925
37370
  }
36926
37371
  }));
36927
37372
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
37373
+ const offTunnelStarted = this.ctx.eventBus.subscribe({ category: EventCategory.NetworkTunnelStarted }, () => {
37374
+ this.detectPublicHubUrl().catch((err) => {
37375
+ this.ctx.logger.warn("export-google: public hub URL detect after tunnel connect failed", { meta: { error: errMsg(err) } });
37376
+ });
37377
+ });
37378
+ this.ctx.addDisposer(async () => offTunnelStarted());
36928
37379
  this.ctx.logger.info("export-google: initialized", { meta: {
36929
37380
  exposedCount: this.config.exposed.length,
36930
37381
  linkedAccounts: this.config.linkedAccounts.length,
36931
37382
  publicHubUrlSet: this.config.publicHubUrl.length > 0,
36932
37383
  willReportState: false
36933
37384
  } });
36934
- return { providers: [
36935
- {
36936
- capability: deviceExportCapability,
36937
- provider: deviceExportProvider
36938
- },
36939
- {
36940
- capability: addonRoutesCapability,
36941
- provider: routeProvider
37385
+ return {
37386
+ providers: [
37387
+ {
37388
+ capability: deviceExportCapability,
37389
+ provider: deviceExportProvider
37390
+ },
37391
+ {
37392
+ capability: addonRoutesCapability,
37393
+ provider: routeProvider
37394
+ },
37395
+ {
37396
+ capability: oauthIntegrationCapability,
37397
+ provider: oauthIntegrationProvider
37398
+ }
37399
+ ],
37400
+ customActions: exportGoogleActions,
37401
+ actionHandlers: { detectPublicHubUrl: async () => this.detectPublicHubUrl() }
37402
+ };
37403
+ }
37404
+ /** This addon's slice of `PublicHubUrlState`. */
37405
+ publicHubUrlState() {
37406
+ return {
37407
+ publicHubUrl: this.config.publicHubUrl,
37408
+ detectedPublicHubUrl: this.config.detectedPublicHubUrl
37409
+ };
37410
+ }
37411
+ /**
37412
+ * Adapter from the codegen'd `network-access` router onto the narrow reader
37413
+ * `public-hub-url.ts` consumes. Fields are copied one by one rather than
37414
+ * passed through, so the module never depends on the cap's wider shape and a
37415
+ * test double for it needs no cast.
37416
+ */
37417
+ networkAccessReader() {
37418
+ return {
37419
+ listEndpoints: async () => {
37420
+ return (await this.ctx.api.networkAccess.listEndpoints.query({})).map((entry) => ({
37421
+ url: entry.url,
37422
+ protocol: entry.protocol
37423
+ }));
36942
37424
  },
36943
- {
36944
- capability: oauthIntegrationCapability,
36945
- provider: oauthIntegrationProvider
37425
+ getStatus: async () => {
37426
+ const status = await this.ctx.api.networkAccess.getStatus.query({});
37427
+ return {
37428
+ connected: status.connected,
37429
+ endpoint: status.endpoint === null ? null : {
37430
+ url: status.endpoint.url,
37431
+ protocol: status.endpoint.protocol
37432
+ }
37433
+ };
36946
37434
  }
36947
- ] };
37435
+ };
37436
+ }
37437
+ /**
37438
+ * Refresh the detected address and DEFAULT the field to it when it is empty.
37439
+ * Backs both the boot-time detect and the "Detect external address" button.
37440
+ *
37441
+ * Never replaces a value the operator set — that value is what they already
37442
+ * pasted into the Google console, and rewriting it here would leave the two
37443
+ * sides disagreeing with nothing on screen to say so.
37444
+ */
37445
+ async detectPublicHubUrl() {
37446
+ const resolution = await refreshPublicHubUrl({
37447
+ current: () => this.publicHubUrlState(),
37448
+ detect: () => detectPublicHubOrigins({
37449
+ network: this.networkAccessReader(),
37450
+ logger: this.ctx.logger
37451
+ }),
37452
+ persist: (patch) => this.updateGlobalSettings(patch),
37453
+ logger: this.ctx.logger
37454
+ });
37455
+ return {
37456
+ publicHubUrl: resolution.publicHubUrl,
37457
+ detectedPublicHubUrl: resolution.detectedPublicHubUrl,
37458
+ filled: resolution.defaulted
37459
+ };
36948
37460
  }
36949
37461
  async onShutdown() {
36950
37462
  this.gateway = null;
@@ -37014,65 +37526,54 @@ var ExportGoogleAddon = class extends BaseAddon {
37014
37526
  * tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
37015
37527
  */
37016
37528
  buildSetupBlock() {
37017
- const origin = this.config.publicHubUrl.replace(/\/+$/, "");
37018
- const linked = this.config.linkedAccounts.length;
37019
- if (origin.length === 0) return {
37020
- note: "Set the public hub URL on the settings form first — every URL Google needs is derived from it.",
37021
- fields: [{
37022
- label: "Linked Google accounts",
37023
- value: String(linked)
37024
- }]
37025
- };
37026
- return {
37027
- note: [
37028
- "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
37029
- "The integration stays in test mode: publishing requires Google certification, which a private hub cannot obtain.",
37030
- "This hub pushes nothing to Google — state is read by polling, so a change made outside the Home app appears on the next query, not instantly."
37031
- ].join("\n"),
37529
+ return buildConsoleSetup({
37530
+ addonId: ADDON_ID,
37531
+ ...this.publicHubUrlState(),
37532
+ linkedAccounts: this.config.linkedAccounts.length
37533
+ });
37534
+ }
37535
+ globalSettingsSchema() {
37536
+ return this.schema({ sections: [{
37537
+ id: ADDON_ID,
37538
+ title: "Google Home export",
37539
+ description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
37540
+ columns: 1,
37032
37541
  fields: [
37033
37542
  {
37034
- label: "Fulfillment URL",
37035
- value: `${origin}/addon/${ADDON_ID}/fulfillment`
37036
- },
37037
- {
37038
- label: "Authorization URL",
37039
- value: `${origin}/api/oauth2/authorize?integration=${ADDON_ID}`
37543
+ type: "info",
37544
+ key: "__google-setup-banner",
37545
+ label: "Setup overview",
37546
+ variant: "info",
37547
+ content: [
37548
+ "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
37549
+ "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
37550
+ "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
37551
+ ].join("\n")
37040
37552
  },
37553
+ this.field({
37554
+ type: "text",
37555
+ key: "publicHubUrl",
37556
+ label: "Public hub URL",
37557
+ description: "HTTPS origin Google reaches this hub on, e.g. https://hub.example.com. Used to render the URLs you paste into the Google console. Left empty, it defaults to the first external address remote access reports; once it holds a value, nothing overwrites it.",
37558
+ placeholder: "https://hub.example.com",
37559
+ default: DEFAULT_SETTINGS.publicHubUrl
37560
+ }),
37041
37561
  {
37042
- label: "Token URL",
37043
- value: `${origin}/api/oauth2/token`
37562
+ type: "info",
37563
+ key: "__public-hub-url-source",
37564
+ label: "Where this came from",
37565
+ ...buildPublicHubUrlNotice(this.publicHubUrlState())
37044
37566
  },
37045
37567
  {
37046
- label: "Linked Google accounts",
37047
- value: String(linked)
37568
+ type: "button",
37569
+ key: "__detect-public-hub-url",
37570
+ label: "External address",
37571
+ description: "Re-scan the connected remote-access providers. Fills the field above when it is empty; a value you set is left exactly as it is.",
37572
+ buttonLabel: "Detect external address",
37573
+ action: "detectPublicHubUrl",
37574
+ variant: "default"
37048
37575
  }
37049
37576
  ]
37050
- };
37051
- }
37052
- globalSettingsSchema() {
37053
- return this.schema({ sections: [{
37054
- id: ADDON_ID,
37055
- title: "Google Home export",
37056
- description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
37057
- columns: 1,
37058
- fields: [{
37059
- type: "info",
37060
- key: "__google-setup-banner",
37061
- label: "Setup overview",
37062
- variant: "info",
37063
- content: [
37064
- "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
37065
- "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
37066
- "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
37067
- ].join("\n")
37068
- }, this.field({
37069
- type: "text",
37070
- key: "publicHubUrl",
37071
- label: "Public hub URL",
37072
- description: "HTTPS origin Google reaches this hub on, e.g. https://hub.example.com. Used to render the URLs you paste into the Google console.",
37073
- placeholder: "https://hub.example.com",
37074
- default: DEFAULT_SETTINGS.publicHubUrl
37075
- })]
37076
37577
  }] });
37077
37578
  }
37078
37579
  /**