@camstack/addon-post-analysis 1.2.6 → 1.2.8

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.
@@ -1,26 +1,4 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
- key = keys[i];
11
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
- get: ((k) => from[k]).bind(null, key),
13
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
- });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
- value: mod,
20
- enumerable: true
21
- }) : target, mod));
22
- //#endregion
23
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
1
+ //#region ../types/dist/event-category-BLcNejAE.mjs
24
2
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
25
3
  EventCategory["SystemBoot"] = "system.boot";
26
4
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -170,9 +148,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
170
148
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
171
149
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
172
150
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
173
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
174
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
175
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
176
151
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
177
152
  * progress bar the client reconciles via `recordingExport.getExport`. */
178
153
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6837,7 +6812,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6837
6812
  patch: record(string(), unknown())
6838
6813
  }), object({ success: literal(true) });
6839
6814
  object({ deviceId: number() }), unknown().nullable();
6840
- /** Shorthand to define a method schema */
6841
6815
  function method(input, output, options) {
6842
6816
  return {
6843
6817
  input,
@@ -6845,6 +6819,7 @@ function method(input, output, options) {
6845
6819
  kind: options?.kind ?? "query",
6846
6820
  auth: options?.auth ?? "protected",
6847
6821
  ...options?.access !== void 0 ? { access: options.access } : {},
6822
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6848
6823
  timeoutMs: options?.timeoutMs
6849
6824
  };
6850
6825
  }
@@ -8302,6 +8277,61 @@ function subKindsOf(macro) {
8302
8277
  return out;
8303
8278
  }
8304
8279
  /**
8280
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8281
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8282
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8283
+ * taxonomy surface (timeline, filters, event page).
8284
+ *
8285
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8286
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8287
+ * for the `classes` / `classesExclude` conditions.
8288
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8289
+ * the same class picker, grouped under an Audio header.
8290
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8291
+ * lock / …) for the `sensorKinds` device-event condition.
8292
+ *
8293
+ * Each entry carries `parentKind` so the client can group video subs under
8294
+ * their macro and sensor/control kinds under their category. This surface is
8295
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8296
+ * method, no codegen — so it ships train-free with an addon deploy.
8297
+ */
8298
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8299
+ var NcTaxonomyEntrySchema = object({
8300
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8301
+ kind: string(),
8302
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8303
+ label: string(),
8304
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8305
+ parentKind: string().nullable()
8306
+ });
8307
+ /** The complete NC picker taxonomy — three grouped buckets. */
8308
+ var NcTaxonomySchema = object({
8309
+ videoClasses: array(NcTaxonomyEntrySchema),
8310
+ audioKinds: array(NcTaxonomyEntrySchema),
8311
+ labels: array(NcTaxonomyEntrySchema)
8312
+ });
8313
+ function toEntry(kind, label, parentKind) {
8314
+ return {
8315
+ kind,
8316
+ label,
8317
+ parentKind
8318
+ };
8319
+ }
8320
+ /**
8321
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8322
+ * (macros before their subs), which the client relies on for stable grouping.
8323
+ */
8324
+ function buildNcTaxonomy() {
8325
+ const all = Object.values(EVENT_TAXONOMY);
8326
+ return {
8327
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8328
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8329
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8330
+ };
8331
+ }
8332
+ /** The frozen NC taxonomy, derived once from the taxonomy dictionary. */
8333
+ var NC_TAXONOMY = Object.freeze(buildNcTaxonomy());
8334
+ /**
8305
8335
  * Error types for the safe expression engine. Two distinct classes so callers
8306
8336
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8307
8337
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -13743,94 +13773,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13743
13773
  bundleUrl: string()
13744
13774
  });
13745
13775
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13746
- var NotificationRuleConditionsSchema = object({
13747
- deviceIds: array(number()).readonly().optional(),
13748
- classNames: array(string()).readonly().optional(),
13749
- zoneIds: array(string()).readonly().optional(),
13750
- minConfidence: number().optional(),
13751
- source: _enum([
13752
- "pipeline",
13753
- "onboard",
13754
- "any"
13755
- ]).optional(),
13756
- schedule: object({
13757
- days: array(number()).readonly(),
13758
- startHour: number(),
13759
- endHour: number()
13760
- }).optional(),
13761
- cooldownSeconds: number().optional(),
13762
- minDwellSeconds: number().optional(),
13763
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13764
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13765
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13766
- eventTypeTokens: array(string()).readonly().optional(),
13767
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13768
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13769
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13770
- clipDescription: object({
13771
- text: string().min(1),
13772
- minSimilarity: number().min(0).max(1)
13773
- }).optional(),
13774
- /** Match events whose recognized-entity label (face identity name or plate
13775
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13776
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13777
- * vehicle/person> is seen". */
13778
- labels: array(string()).readonly().optional()
13779
- });
13780
- var NotificationRuleTemplateSchema = object({
13781
- title: string(),
13782
- body: string(),
13783
- imageMode: _enum([
13784
- "crop",
13785
- "annotated",
13786
- "full",
13787
- "none"
13788
- ])
13789
- });
13790
- var NotificationRuleSchema = object({
13791
- id: string(),
13792
- name: string(),
13793
- enabled: boolean(),
13794
- eventTypes: array(string()).readonly(),
13795
- conditions: NotificationRuleConditionsSchema,
13796
- outputs: array(string()).readonly(),
13797
- template: NotificationRuleTemplateSchema.optional(),
13798
- priority: _enum([
13799
- "low",
13800
- "normal",
13801
- "high",
13802
- "critical"
13803
- ])
13804
- });
13805
- var NotificationTestResultSchema = object({
13806
- ruleId: string(),
13807
- eventId: string(),
13808
- timestamp: number(),
13809
- wouldFire: boolean(),
13810
- reason: string().optional()
13811
- });
13812
- var NotificationHistoryEntrySchema = object({
13813
- id: string(),
13814
- ruleId: string(),
13815
- ruleName: string(),
13816
- eventId: string(),
13817
- timestamp: number(),
13818
- outputs: array(string()).readonly(),
13819
- success: boolean(),
13820
- error: string().optional(),
13821
- deviceId: number().optional()
13822
- });
13823
- var NotificationHistoryFilterSchema = object({
13824
- ruleId: string().optional(),
13825
- deviceId: number().optional(),
13826
- from: number().optional(),
13827
- to: number().optional(),
13828
- limit: number().optional()
13829
- });
13830
- method(_void(), object({ rules: array(NotificationRuleSchema).readonly() })), method(object({ rule: NotificationRuleSchema }), object({ success: literal(true) }), { kind: "mutation" }), method(object({ ruleId: string() }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
13831
- ruleId: string(),
13832
- lookbackMinutes: number()
13833
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13834
13776
  /**
13835
13777
  * Alerts capability — collection-based internal alert system.
13836
13778
  *
@@ -14017,89 +13959,6 @@ method(object({
14017
13959
  password: string()
14018
13960
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
14019
13961
  /**
14020
- * `login-method` — collection cap through which auth addons contribute
14021
- * their pre-auth login surfaces to the login page. This is the SINGLE,
14022
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
14023
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
14024
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
14025
- * procedure aggregates them for the unauthenticated login page.
14026
- *
14027
- * A contribution is a discriminated union on `kind`:
14028
- *
14029
- * - `redirect` — a declarative button. The login page renders a generic
14030
- * button that navigates to `startUrl` (an addon-owned HTTP route).
14031
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
14032
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
14033
- * login page needs NO change.
14034
- *
14035
- * - `widget` — a Module-Federation widget the login page mounts (via
14036
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
14037
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
14038
- * mechanism kept for future use; no shipped addon uses it on the login
14039
- * page (the passkey ceremony below runs natively in the shell instead).
14040
- *
14041
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
14042
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
14043
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
14044
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
14045
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
14046
- * fetching any remote code pre-auth. Contribution stays unconditional —
14047
- * enrollment state is never leaked pre-auth; visibility is a shell
14048
- * decision.
14049
- *
14050
- * Every contribution carries a `stage`:
14051
- * - `primary` — shown on the first credentials screen (OIDC /
14052
- * magic-link buttons; a future usernameless passkey).
14053
- * - `second-factor` — shown AFTER the password leg, gated on the
14054
- * returned `factors` (passkey-as-2FA today).
14055
- *
14056
- * `mount: skip` — the cap is read server-side by the core auth router
14057
- * (`registry.getCollection('login-method')`), never mounted as its own
14058
- * tRPC router.
14059
- */
14060
- /** When a login method renders in the two-phase login flow. */
14061
- var LoginStageEnum = _enum(["primary", "second-factor"]);
14062
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
14063
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
14064
- object({
14065
- kind: literal("redirect"),
14066
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
14067
- id: string(),
14068
- /** Operator-facing button label. */
14069
- label: string(),
14070
- /** lucide-react icon name. */
14071
- icon: string().optional(),
14072
- /** Addon-owned HTTP route the button navigates to (GET). */
14073
- startUrl: string(),
14074
- stage: LoginStageEnum
14075
- }),
14076
- object({
14077
- kind: literal("widget"),
14078
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
14079
- id: string(),
14080
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
14081
- addonId: string(),
14082
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
14083
- bundle: string(),
14084
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
14085
- remote: WidgetRemoteSchema,
14086
- stage: LoginStageEnum
14087
- }),
14088
- object({
14089
- kind: literal("passkey"),
14090
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
14091
- id: string(),
14092
- /** Operator-facing button label. */
14093
- label: string(),
14094
- stage: LoginStageEnum,
14095
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
14096
- rpId: string(),
14097
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
14098
- origin: string().nullable()
14099
- })
14100
- ]);
14101
- method(_void(), array(LoginMethodContributionSchema).readonly());
14102
- /**
14103
13962
  * Orchestrator-side destination metadata. The orchestrator computes
14104
13963
  * `id = <addonId>:<subId>` from its provider lookup so consumers
14105
13964
  * (admin UI, restore flow) see one canonical key.
@@ -14456,6 +14315,28 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
14456
14315
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
14457
14316
  DeviceType.Camera;
14458
14317
  /**
14318
+ * Identity — preserves literal types for downstream inference.
14319
+ *
14320
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
14321
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
14322
+ * the broader unions declared on `CustomActionSpec`'s default generics.
14323
+ * Shape validity is enforced separately by the `customAction(...)` helper
14324
+ * whose return type is already a `CustomActionSpec<...>`.
14325
+ */
14326
+ function defineCustomActions(spec) {
14327
+ return spec;
14328
+ }
14329
+ function customAction(input, output, options) {
14330
+ return {
14331
+ input,
14332
+ output,
14333
+ kind: options?.kind ?? "query",
14334
+ auth: options?.auth ?? "protected",
14335
+ scope: options?.scope ?? { kind: "system" },
14336
+ ...options?.caller ? { caller: "required" } : {}
14337
+ };
14338
+ }
14339
+ /**
14459
14340
  * `custom-model-registry` — collection cap exposing operator-registered
14460
14341
  * custom detection models. Each provider (today: `addon-model-studio`)
14461
14342
  * contributes a list of `CustomModelDescriptor`s; the hub auto-concatenates
@@ -15453,373 +15334,748 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15453
15334
  kind: "mutation",
15454
15335
  auth: "admin"
15455
15336
  });
15456
- var LogLevelSchema = _enum([
15457
- "debug",
15458
- "info",
15459
- "warn",
15460
- "error"
15337
+ /**
15338
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15339
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15340
+ * caps stay wire-compatible without a circular cap→cap import.
15341
+ *
15342
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15343
+ * every transport tier structurally, and failed calls still write usage rows.
15344
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15345
+ */
15346
+ var LlmUsageSchema = object({
15347
+ inputTokens: number(),
15348
+ outputTokens: number()
15349
+ });
15350
+ var LlmErrorCodeSchema = _enum([
15351
+ "timeout",
15352
+ "rate-limited",
15353
+ "auth",
15354
+ "refusal",
15355
+ "bad-request",
15356
+ "unavailable",
15357
+ "no-profile",
15358
+ "budget-exceeded",
15359
+ "adapter-error"
15461
15360
  ]);
15462
- var LogEntrySchema = object({
15463
- timestamp: date(),
15464
- level: LogLevelSchema,
15465
- scope: array(string()),
15361
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15362
+ ok: literal(true),
15363
+ text: string(),
15364
+ model: string(),
15365
+ usage: LlmUsageSchema,
15366
+ truncated: boolean(),
15367
+ latencyMs: number()
15368
+ }), object({
15369
+ ok: literal(false),
15370
+ code: LlmErrorCodeSchema,
15466
15371
  message: string(),
15467
- meta: record(string(), unknown()).optional(),
15468
- tags: record(string(), string()).optional()
15469
- });
15470
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15471
- scope: array(string()).optional(),
15472
- level: LogLevelSchema.optional(),
15473
- since: date().optional(),
15474
- until: date().optional(),
15475
- limit: number().optional(),
15476
- tags: record(string(), string()).optional()
15477
- }), array(LogEntrySchema).readonly());
15478
- var CpuBreakdownSchema = object({
15479
- total: number(),
15480
- user: number(),
15481
- system: number(),
15482
- irq: number(),
15483
- nice: number(),
15484
- loadAvg: tuple([
15485
- number(),
15486
- number(),
15487
- number()
15488
- ]),
15489
- cores: number()
15372
+ retryAfterMs: number().optional()
15373
+ })]);
15374
+ /**
15375
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15376
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15377
+ * notification-output.cap.ts:27-31 precedents).
15378
+ */
15379
+ var LlmImageSchema = object({
15380
+ bytes: _instanceof(Uint8Array),
15381
+ mimeType: string()
15490
15382
  });
15491
- var MemoryInfoSchema = object({
15492
- percent: number(),
15493
- totalBytes: number(),
15494
- usedBytes: number(),
15495
- availableBytes: number(),
15496
- swapUsedBytes: number(),
15497
- swapTotalBytes: number()
15383
+ var LlmGenerateBaseInputSchema = object({
15384
+ /** Collection routing (the notification-output posture). */
15385
+ addonId: string().optional(),
15386
+ /** Explicit profile; else the resolution chain (spec §3). */
15387
+ profileId: string().optional(),
15388
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15389
+ consumer: string(),
15390
+ system: string().optional(),
15391
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15392
+ prompt: string(),
15393
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15394
+ jsonSchema: record(string(), unknown()).optional(),
15395
+ /** Per-call override of the profile default. */
15396
+ maxTokens: number().int().positive().optional(),
15397
+ temperature: number().optional()
15498
15398
  });
15499
- var DiskIoSnapshotSchema = object({
15500
- readBytes: number(),
15501
- writeBytes: number(),
15502
- readOps: number(),
15503
- writeOps: number(),
15504
- timestampMs: number()
15505
- });
15506
- var NetworkIoSnapshotSchema = object({
15507
- rxBytes: number(),
15508
- txBytes: number(),
15509
- rxPackets: number(),
15510
- txPackets: number(),
15511
- rxErrors: number(),
15512
- txErrors: number(),
15513
- timestampMs: number()
15514
- });
15515
- var MetricsGpuInfoSchema = object({
15516
- utilization: number(),
15517
- model: string(),
15518
- memoryUsedBytes: number(),
15519
- memoryTotalBytes: number(),
15520
- temperature: number().nullable()
15521
- });
15522
- var ProcessResourceInfoSchema = object({
15523
- openFds: number(),
15524
- threadCount: number(),
15525
- activeHandles: number(),
15526
- activeRequests: number()
15527
- });
15528
- var PressureAvgsSchema = object({
15529
- avg10: number(),
15530
- avg60: number(),
15531
- avg300: number()
15532
- });
15533
- var PressureInfoSchema = object({
15534
- some: PressureAvgsSchema,
15535
- full: PressureAvgsSchema.nullable()
15536
- });
15537
- var SystemResourceSnapshotSchema = object({
15538
- cpu: CpuBreakdownSchema,
15539
- memory: MemoryInfoSchema,
15540
- gpu: MetricsGpuInfoSchema.nullable(),
15541
- network: NetworkIoSnapshotSchema,
15542
- disk: DiskIoSnapshotSchema,
15543
- pressure: object({
15544
- cpu: PressureInfoSchema.nullable(),
15545
- memory: PressureInfoSchema.nullable(),
15546
- io: PressureInfoSchema.nullable()
15399
+ /**
15400
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15401
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15402
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15403
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15404
+ * this only through the `llm` cap's methods.
15405
+ *
15406
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15407
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15408
+ * watchdog — operator decision #3).
15409
+ */
15410
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15411
+ object({
15412
+ kind: literal("catalog"),
15413
+ catalogId: string()
15547
15414
  }),
15548
- process: ProcessResourceInfoSchema,
15549
- cpuTemperature: number().nullable(),
15550
- timestampMs: number()
15551
- });
15552
- var DiskSpaceInfoSchema = object({
15553
- path: string(),
15554
- totalBytes: number(),
15555
- usedBytes: number(),
15556
- availableBytes: number(),
15557
- percent: number()
15558
- });
15559
- var PidResourceStatsSchema = object({
15560
- pid: number(),
15561
- cpu: number(),
15562
- memory: number(),
15563
- /**
15564
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15565
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15566
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15567
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15568
- * Undefined where /proc is unavailable (e.g. macOS).
15569
- */
15570
- privateBytes: number().optional(),
15571
- /**
15572
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15573
- * code shared copy-on-write across runners. Undefined on macOS.
15574
- */
15575
- sharedBytes: number().optional()
15415
+ object({
15416
+ kind: literal("url"),
15417
+ url: string(),
15418
+ sha256: string().optional()
15419
+ }),
15420
+ object({
15421
+ kind: literal("path"),
15422
+ path: string()
15423
+ })
15424
+ ]);
15425
+ var ManagedRuntimeConfigSchema = object({
15426
+ /** WHERE the runtime lives — hub or any agent. */
15427
+ nodeId: string(),
15428
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15429
+ engine: _enum(["llama-cpp"]),
15430
+ model: ManagedModelRefSchema,
15431
+ contextSize: number().int().default(4096),
15432
+ /** 0 = CPU-only. */
15433
+ gpuLayers: number().int().default(0),
15434
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15435
+ threads: number().int().optional(),
15436
+ /** Concurrent slots. */
15437
+ parallel: number().int().default(1),
15438
+ /** Else lazy: first generate boots it. */
15439
+ autoStart: boolean().default(false),
15440
+ /** 0 = never; frees RAM after quiet periods. */
15441
+ idleStopMinutes: number().int().default(30)
15576
15442
  });
15577
- var AddonInstanceSchema = object({
15578
- addonId: string(),
15443
+ var LlmRuntimeStatusSchema = object({
15444
+ /** Status is ALWAYS node-qualified. */
15579
15445
  nodeId: string(),
15580
- role: _enum(["hub", "worker"]),
15581
- pid: number(),
15582
15446
  state: _enum([
15583
- "starting",
15584
- "running",
15585
- "stopping",
15586
15447
  "stopped",
15587
- "crashed"
15588
- ]),
15589
- uptimeSec: number()
15590
- });
15591
- var NodeProcessSchema = object({
15592
- pid: number(),
15593
- ppid: number(),
15594
- pgid: number(),
15595
- classification: _enum([
15596
- "root",
15597
- "managed",
15598
- "system",
15599
- "ghost"
15448
+ "downloading",
15449
+ "starting",
15450
+ "ready",
15451
+ "crashed",
15452
+ "failed"
15600
15453
  ]),
15601
- /** `$process` addon binding when `managed`, else null. */
15602
- addonId: string().nullable(),
15603
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15604
- nodeId: string().nullable(),
15605
- /** Truncated command line. */
15606
- command: string(),
15607
- cpuPercent: number(),
15608
- memoryRssBytes: number(),
15609
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15610
- uptimeSec: number(),
15611
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15612
- orphaned: boolean()
15613
- });
15614
- var KillProcessInputSchema = object({
15615
- pid: number(),
15616
- /** Force = SIGKILL. Default is SIGTERM. */
15617
- force: boolean().optional()
15618
- });
15619
- var KillProcessResultSchema = object({
15620
- success: boolean(),
15621
- reason: string().optional(),
15622
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15623
- });
15624
- var DumpHeapSnapshotInputSchema = object({
15625
- /** The addon whose runner should dump a heap snapshot. */
15626
- addonId: string() });
15627
- var DumpHeapSnapshotResultSchema = object({
15628
- success: boolean(),
15629
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15630
- path: string().optional(),
15631
- /** Process pid that was signalled. */
15632
15454
  pid: number().optional(),
15633
- reason: string().optional()
15455
+ port: number().optional(),
15456
+ modelPath: string().optional(),
15457
+ modelId: string().optional(),
15458
+ downloadProgress: number().min(0).max(1).optional(),
15459
+ lastError: string().optional(),
15460
+ crashesInWindow: number(),
15461
+ /** Child RSS (sampled best-effort). */
15462
+ memoryBytes: number().optional(),
15463
+ vramBytes: number().optional()
15634
15464
  });
15635
- var SystemMetricsSchema = object({
15636
- cpuPercent: number(),
15637
- memoryPercent: number(),
15638
- memoryUsedMB: number(),
15639
- memoryTotalMB: number(),
15640
- diskPercent: number().optional(),
15641
- temperature: number().optional(),
15642
- gpuPercent: number().optional(),
15643
- gpuMemoryPercent: number().optional()
15465
+ var LlmNodeModelSchema = object({
15466
+ file: string(),
15467
+ sizeBytes: number(),
15468
+ catalogId: string().optional(),
15469
+ installedAt: number().optional()
15644
15470
  });
15645
- method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
15471
+ var LlmRuntimeDiskUsageSchema = object({
15472
+ nodeId: string(),
15473
+ modelsBytes: number(),
15474
+ freeBytes: number().optional()
15475
+ });
15476
+ method(LlmGenerateBaseInputSchema.extend({
15477
+ images: array(LlmImageSchema).optional(),
15478
+ runtime: ManagedRuntimeConfigSchema,
15479
+ /** The managed profile's timeout, threaded by the hub provider. */
15480
+ timeoutMs: number().int().positive().optional()
15481
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15646
15482
  kind: "mutation",
15647
15483
  auth: "admin"
15648
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15484
+ }), method(object({}), _void(), {
15649
15485
  kind: "mutation",
15650
15486
  auth: "admin"
15651
- });
15652
- method(object({
15653
- sourceUrl: string(),
15654
- metadata: ModelConvertMetadataSchema,
15655
- targets: array(ConvertTargetSchema).min(1).readonly(),
15656
- calibrationRef: string().optional(),
15657
- sessionId: string().optional()
15658
- }), ConvertResultSchema, {
15487
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15659
15488
  kind: "mutation",
15660
- auth: "admin",
15661
- timeoutMs: 6e5
15662
- });
15663
- method(object({
15664
- nodeId: string(),
15665
- modelId: string(),
15666
- format: _enum(MODEL_FORMATS),
15667
- entry: ModelCatalogEntrySchema
15668
- }), object({
15669
- ok: boolean(),
15670
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15671
- sha256: string(),
15672
- bytes: number(),
15673
- /** The target node's modelsDir the artifact landed in. */
15674
- path: string()
15675
- }), {
15489
+ auth: "admin"
15490
+ }), method(object({ file: string() }), _void(), {
15676
15491
  kind: "mutation",
15677
15492
  auth: "admin"
15678
- });
15493
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15679
15494
  /**
15680
- * `mqtt-broker` — broker-registry cap.
15681
- *
15682
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15683
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15684
- * and (b) the connection details a consumer addon needs to spin up
15685
- * its OWN `mqtt.js` client.
15495
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15496
+ * methods concat-fan across providers; single-row methods route to ONE
15497
+ * provider by the `addonId` in the call input (the notification-output
15498
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15499
+ * (hub-placed); the cap stays open for future providers.
15686
15500
  *
15687
- * Why: pub/sub routing over the system event-bus loses fidelity
15688
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15689
- * refcount bookkeeping that addons would rather own themselves. The
15690
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15691
- * features anyway — give it the connection config, get out of the way.
15692
- *
15693
- * Consumer flow:
15694
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15695
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15696
- * client.subscribe('zigbee2mqtt/+')
15697
- *
15698
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
15699
- * cloud bridge). The "embedded" entry (when present) is just another
15700
- * broker in the registry — its lifecycle is owned by the addon that
15701
- * spawned it.
15702
- */
15703
- var BrokerKindSchema = _enum(["external", "embedded"]);
15704
- /**
15705
- * Broker live-probe status.
15706
- *
15707
- * - `connected` — last probe completed a clean CONNACK
15708
- * - `disconnected` — no probe has run yet (cold cache)
15709
- * - `auth-failed` — CONNACK refused with auth error (RC 4 / 5)
15710
- * - `unreachable` — TCP connect timed out / refused
15711
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15501
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15502
+ * `apiKey` is a password field providers REDACT it on read and merge on
15503
+ * write; a stored key NEVER round-trips to a client.
15712
15504
  */
15713
- var BrokerStatusSchema$1 = _enum([
15714
- "connected",
15715
- "disconnected",
15716
- "auth-failed",
15717
- "unreachable",
15718
- "tls-error"
15505
+ var LlmProfileKindSchema = _enum([
15506
+ "openai-compatible",
15507
+ "openai",
15508
+ "anthropic",
15509
+ "google",
15510
+ "managed-local"
15719
15511
  ]);
15720
- var BrokerInfoSchema = object({
15512
+ var LlmProfileSchema = object({
15721
15513
  id: string(),
15722
15514
  name: string(),
15723
- url: string(),
15724
- kind: BrokerKindSchema,
15725
- status: BrokerStatusSchema$1,
15726
- latencyMs: number().nullable(),
15727
- error: string().optional(),
15728
- /** Embedded brokers only: number of MQTT clients currently connected. */
15729
- connectedClients: number().int().nonnegative().optional(),
15730
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15731
- lastCheckedAt: number().optional()
15515
+ kind: LlmProfileKindSchema,
15516
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15517
+ addonId: string(),
15518
+ enabled: boolean(),
15519
+ /** Vendor model id, or the managed runtime's loaded model. */
15520
+ model: string(),
15521
+ /** Required for openai-compatible; override for cloud kinds. */
15522
+ baseUrl: string().optional(),
15523
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15524
+ apiKey: string().optional(),
15525
+ supportsVision: boolean(),
15526
+ temperature: number().min(0).max(2).optional(),
15527
+ maxTokens: number().int().positive().optional(),
15528
+ timeoutMs: number().int().positive().default(6e4),
15529
+ extraHeaders: record(string(), string()).optional(),
15530
+ /** kind === 'managed-local' only (spec §4). */
15531
+ runtime: ManagedRuntimeConfigSchema.optional()
15732
15532
  });
15733
- /**
15734
- * Connection details — what a consumer needs to call
15735
- * `mqtt.connect(url, options)`. We split URL + credentials so the
15736
- * consumer can pass them as `mqtt.connect(url, { username, password })`
15737
- * instead of stuffing creds into the URL (which leaks them into logs).
15738
- */
15739
- var BrokerConnectionDetailsSchema = object({
15740
- url: string(),
15741
- username: string().optional(),
15742
- password: string().optional(),
15743
- /**
15744
- * Suggested prefix for `clientId`. Each consumer should suffix this
15745
- * with its own discriminator (addon id, instance id) so reconnects
15746
- * don't kick each other off (MQTT spec: clientId must be unique per
15747
- * broker).
15748
- */
15749
- clientIdPrefix: string().optional()
15533
+ /** ConfigUISchema tree passed through untyped on the wire (the
15534
+ * notification-output `ConfigSchemaPassthrough` precedent at
15535
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15536
+ var ConfigSchemaPassthrough$1 = unknown();
15537
+ var LlmProfileKindDescriptorSchema = object({
15538
+ kind: LlmProfileKindSchema,
15539
+ label: string(),
15540
+ icon: string(),
15541
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15542
+ addonId: string(),
15543
+ configSchema: ConfigSchemaPassthrough$1
15750
15544
  });
15751
- var AddBrokerInputSchema = object({
15752
- name: string().min(1),
15753
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15754
- username: string().optional(),
15755
- password: string().optional(),
15756
- clientIdPrefix: string().optional()
15545
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15546
+ var LlmDefaultSchema = object({
15547
+ selector: LlmDefaultSelectorSchema,
15548
+ profileId: string()
15757
15549
  });
15758
- var AddBrokerResultSchema = object({ id: string() });
15759
- var IdInputSchema = object({ id: string() });
15760
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
15761
- ok: literal(true),
15762
- latencyMs: number()
15763
- }), object({
15764
- ok: literal(false),
15765
- error: string()
15766
- })]);
15767
- var StartEmbeddedInputSchema = object({
15768
- port: number().int().min(1).max(65535).default(1883),
15769
- /** Allow anonymous connect (no username/password). Default: false. */
15770
- allowAnonymous: boolean().default(false),
15771
- /** Optional shared username/password for clients. */
15772
- username: string().optional(),
15773
- password: string().optional()
15550
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
15551
+ var LlmUsageRollupSchema = object({
15552
+ day: string(),
15553
+ consumer: string(),
15554
+ profileId: string(),
15555
+ calls: number(),
15556
+ okCalls: number(),
15557
+ errorCalls: number(),
15558
+ inputTokens: number(),
15559
+ outputTokens: number(),
15560
+ avgLatencyMs: number()
15774
15561
  });
15775
- var StartEmbeddedResultSchema = object({
15562
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15563
+ var ManagedModelCatalogEntrySchema = object({
15776
15564
  id: string(),
15777
- url: string()
15778
- });
15779
- var StatusSchema = object({
15780
- brokerCount: number(),
15781
- embeddedRunning: boolean()
15782
- });
15783
- method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
15784
- var NetworkEndpointSchema = object({
15565
+ label: string(),
15566
+ family: string(),
15567
+ purpose: _enum(["text", "vision"]),
15785
15568
  url: string(),
15786
- hostname: string(),
15787
- port: number(),
15788
- protocol: _enum(["http", "https"])
15569
+ sha256: string(),
15570
+ sizeBytes: number(),
15571
+ quantization: string(),
15572
+ /** Load-time guidance shown in the picker. */
15573
+ minRamBytes: number(),
15574
+ contextSizeDefault: number().int(),
15575
+ /** Vision models: companion projector file. */
15576
+ mmprojUrl: string().optional()
15789
15577
  });
15790
- var NetworkAccessStatusSchema = object({
15791
- connected: boolean(),
15792
- endpoint: NetworkEndpointSchema.nullable(),
15578
+ var LlmRuntimeNodeSchema = object({
15579
+ nodeId: string(),
15580
+ reachable: boolean(),
15581
+ status: LlmRuntimeStatusSchema.optional(),
15582
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15793
15583
  error: string().optional()
15794
15584
  });
15795
- /**
15796
- * Optional, richer endpoint shape returned by providers that expose
15797
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15798
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15799
- * the originating provider config (mode + sourcePort) so the
15800
- * orchestrator UI can label rows distinctly. Providers that expose only
15801
- * one endpoint just omit `listEndpoints` from their provider impl.
15802
- */
15803
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15804
- /**
15805
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15806
- * the orchestrator can dedupe across `listEndpoints` polls.
15807
- */
15808
- id: string(),
15809
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15810
- label: string(),
15811
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15812
- mode: string().optional(),
15813
- /** Originating local port the ingress fronts (informational). */
15814
- sourcePort: number().optional()
15585
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15586
+ var ProfileRefInputSchema = object({
15587
+ addonId: string(),
15588
+ profileId: string()
15815
15589
  });
15816
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
15590
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15591
+ kind: "mutation",
15592
+ auth: "admin"
15593
+ }), method(ProfileRefInputSchema, _void(), {
15594
+ kind: "mutation",
15595
+ auth: "admin"
15596
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15597
+ kind: "mutation",
15598
+ auth: "admin"
15599
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15600
+ selector: LlmDefaultSelectorSchema,
15601
+ profileId: string().nullable()
15602
+ }), _void(), {
15603
+ kind: "mutation",
15604
+ auth: "admin"
15605
+ }), method(object({
15606
+ since: number().optional(),
15607
+ until: number().optional(),
15608
+ consumer: string().optional(),
15609
+ profileId: string().optional()
15610
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15611
+ nodeId: string(),
15612
+ model: ManagedModelRefSchema
15613
+ }), _void(), {
15614
+ kind: "mutation",
15615
+ auth: "admin"
15616
+ }), method(object({
15617
+ nodeId: string(),
15618
+ file: string()
15619
+ }), _void(), {
15620
+ kind: "mutation",
15621
+ auth: "admin"
15622
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15623
+ kind: "mutation",
15624
+ auth: "admin"
15625
+ }), method(ProfileRefInputSchema, _void(), {
15626
+ kind: "mutation",
15627
+ auth: "admin"
15628
+ });
15629
+ var LogLevelSchema = _enum([
15630
+ "debug",
15631
+ "info",
15632
+ "warn",
15633
+ "error"
15634
+ ]);
15635
+ var LogEntrySchema = object({
15636
+ timestamp: date(),
15637
+ level: LogLevelSchema,
15638
+ scope: array(string()),
15639
+ message: string(),
15640
+ meta: record(string(), unknown()).optional(),
15641
+ tags: record(string(), string()).optional()
15642
+ });
15643
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15644
+ scope: array(string()).optional(),
15645
+ level: LogLevelSchema.optional(),
15646
+ since: date().optional(),
15647
+ until: date().optional(),
15648
+ limit: number().optional(),
15649
+ tags: record(string(), string()).optional()
15650
+ }), array(LogEntrySchema).readonly());
15817
15651
  /**
15818
- * notification-outputcanonical, capability-gated notification delivery.
15652
+ * `login-method`collection cap through which auth addons contribute
15653
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15654
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15655
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15656
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15657
+ * procedure aggregates them for the unauthenticated login page.
15819
15658
  *
15820
- * Apprise-derived model (see
15821
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15822
- * callers emit ONE canonical `Notification`; each provider declares a
15659
+ * A contribution is a discriminated union on `kind`:
15660
+ *
15661
+ * - `redirect` a declarative button. The login page renders a generic
15662
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15663
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15664
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15665
+ * login page needs NO change.
15666
+ *
15667
+ * - `widget` — a Module-Federation widget the login page mounts (via
15668
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15669
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15670
+ * mechanism kept for future use; no shipped addon uses it on the login
15671
+ * page (the passkey ceremony below runs natively in the shell instead).
15672
+ *
15673
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15674
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15675
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15676
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15677
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15678
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15679
+ * enrollment state is never leaked pre-auth; visibility is a shell
15680
+ * decision.
15681
+ *
15682
+ * Every contribution carries a `stage`:
15683
+ * - `primary` — shown on the first credentials screen (OIDC /
15684
+ * magic-link buttons; a future usernameless passkey).
15685
+ * - `second-factor` — shown AFTER the password leg, gated on the
15686
+ * returned `factors` (passkey-as-2FA today).
15687
+ *
15688
+ * `mount: skip` — the cap is read server-side by the core auth router
15689
+ * (`registry.getCollection('login-method')`), never mounted as its own
15690
+ * tRPC router.
15691
+ */
15692
+ /** When a login method renders in the two-phase login flow. */
15693
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15694
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15695
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15696
+ object({
15697
+ kind: literal("redirect"),
15698
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15699
+ id: string(),
15700
+ /** Operator-facing button label. */
15701
+ label: string(),
15702
+ /** lucide-react icon name. */
15703
+ icon: string().optional(),
15704
+ /** Addon-owned HTTP route the button navigates to (GET). */
15705
+ startUrl: string(),
15706
+ stage: LoginStageEnum
15707
+ }),
15708
+ object({
15709
+ kind: literal("widget"),
15710
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15711
+ id: string(),
15712
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15713
+ addonId: string(),
15714
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15715
+ bundle: string(),
15716
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15717
+ remote: WidgetRemoteSchema,
15718
+ stage: LoginStageEnum
15719
+ }),
15720
+ object({
15721
+ kind: literal("passkey"),
15722
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15723
+ id: string(),
15724
+ /** Operator-facing button label. */
15725
+ label: string(),
15726
+ stage: LoginStageEnum,
15727
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15728
+ rpId: string(),
15729
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15730
+ origin: string().nullable()
15731
+ })
15732
+ ]);
15733
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15734
+ var CpuBreakdownSchema = object({
15735
+ total: number(),
15736
+ user: number(),
15737
+ system: number(),
15738
+ irq: number(),
15739
+ nice: number(),
15740
+ loadAvg: tuple([
15741
+ number(),
15742
+ number(),
15743
+ number()
15744
+ ]),
15745
+ cores: number()
15746
+ });
15747
+ var MemoryInfoSchema = object({
15748
+ percent: number(),
15749
+ totalBytes: number(),
15750
+ usedBytes: number(),
15751
+ availableBytes: number(),
15752
+ swapUsedBytes: number(),
15753
+ swapTotalBytes: number()
15754
+ });
15755
+ var DiskIoSnapshotSchema = object({
15756
+ readBytes: number(),
15757
+ writeBytes: number(),
15758
+ readOps: number(),
15759
+ writeOps: number(),
15760
+ timestampMs: number()
15761
+ });
15762
+ var NetworkIoSnapshotSchema = object({
15763
+ rxBytes: number(),
15764
+ txBytes: number(),
15765
+ rxPackets: number(),
15766
+ txPackets: number(),
15767
+ rxErrors: number(),
15768
+ txErrors: number(),
15769
+ timestampMs: number()
15770
+ });
15771
+ var MetricsGpuInfoSchema = object({
15772
+ utilization: number(),
15773
+ model: string(),
15774
+ memoryUsedBytes: number(),
15775
+ memoryTotalBytes: number(),
15776
+ temperature: number().nullable()
15777
+ });
15778
+ var ProcessResourceInfoSchema = object({
15779
+ openFds: number(),
15780
+ threadCount: number(),
15781
+ activeHandles: number(),
15782
+ activeRequests: number()
15783
+ });
15784
+ var PressureAvgsSchema = object({
15785
+ avg10: number(),
15786
+ avg60: number(),
15787
+ avg300: number()
15788
+ });
15789
+ var PressureInfoSchema = object({
15790
+ some: PressureAvgsSchema,
15791
+ full: PressureAvgsSchema.nullable()
15792
+ });
15793
+ var SystemResourceSnapshotSchema = object({
15794
+ cpu: CpuBreakdownSchema,
15795
+ memory: MemoryInfoSchema,
15796
+ gpu: MetricsGpuInfoSchema.nullable(),
15797
+ network: NetworkIoSnapshotSchema,
15798
+ disk: DiskIoSnapshotSchema,
15799
+ pressure: object({
15800
+ cpu: PressureInfoSchema.nullable(),
15801
+ memory: PressureInfoSchema.nullable(),
15802
+ io: PressureInfoSchema.nullable()
15803
+ }),
15804
+ process: ProcessResourceInfoSchema,
15805
+ cpuTemperature: number().nullable(),
15806
+ timestampMs: number()
15807
+ });
15808
+ var DiskSpaceInfoSchema = object({
15809
+ path: string(),
15810
+ totalBytes: number(),
15811
+ usedBytes: number(),
15812
+ availableBytes: number(),
15813
+ percent: number()
15814
+ });
15815
+ var PidResourceStatsSchema = object({
15816
+ pid: number(),
15817
+ cpu: number(),
15818
+ memory: number(),
15819
+ /**
15820
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15821
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15822
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15823
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15824
+ * Undefined where /proc is unavailable (e.g. macOS).
15825
+ */
15826
+ privateBytes: number().optional(),
15827
+ /**
15828
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15829
+ * code shared copy-on-write across runners. Undefined on macOS.
15830
+ */
15831
+ sharedBytes: number().optional()
15832
+ });
15833
+ var AddonInstanceSchema = object({
15834
+ addonId: string(),
15835
+ nodeId: string(),
15836
+ role: _enum(["hub", "worker"]),
15837
+ pid: number(),
15838
+ state: _enum([
15839
+ "starting",
15840
+ "running",
15841
+ "stopping",
15842
+ "stopped",
15843
+ "crashed"
15844
+ ]),
15845
+ uptimeSec: number()
15846
+ });
15847
+ var NodeProcessSchema = object({
15848
+ pid: number(),
15849
+ ppid: number(),
15850
+ pgid: number(),
15851
+ classification: _enum([
15852
+ "root",
15853
+ "managed",
15854
+ "system",
15855
+ "ghost"
15856
+ ]),
15857
+ /** `$process` addon binding when `managed`, else null. */
15858
+ addonId: string().nullable(),
15859
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15860
+ nodeId: string().nullable(),
15861
+ /** Truncated command line. */
15862
+ command: string(),
15863
+ cpuPercent: number(),
15864
+ memoryRssBytes: number(),
15865
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15866
+ uptimeSec: number(),
15867
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15868
+ orphaned: boolean()
15869
+ });
15870
+ var KillProcessInputSchema = object({
15871
+ pid: number(),
15872
+ /** Force = SIGKILL. Default is SIGTERM. */
15873
+ force: boolean().optional()
15874
+ });
15875
+ var KillProcessResultSchema = object({
15876
+ success: boolean(),
15877
+ reason: string().optional(),
15878
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15879
+ });
15880
+ var DumpHeapSnapshotInputSchema = object({
15881
+ /** The addon whose runner should dump a heap snapshot. */
15882
+ addonId: string() });
15883
+ var DumpHeapSnapshotResultSchema = object({
15884
+ success: boolean(),
15885
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15886
+ path: string().optional(),
15887
+ /** Process pid that was signalled. */
15888
+ pid: number().optional(),
15889
+ reason: string().optional()
15890
+ });
15891
+ var SystemMetricsSchema = object({
15892
+ cpuPercent: number(),
15893
+ memoryPercent: number(),
15894
+ memoryUsedMB: number(),
15895
+ memoryTotalMB: number(),
15896
+ diskPercent: number().optional(),
15897
+ temperature: number().optional(),
15898
+ gpuPercent: number().optional(),
15899
+ gpuMemoryPercent: number().optional()
15900
+ });
15901
+ method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
15902
+ kind: "mutation",
15903
+ auth: "admin"
15904
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15905
+ kind: "mutation",
15906
+ auth: "admin"
15907
+ });
15908
+ method(object({
15909
+ sourceUrl: string(),
15910
+ metadata: ModelConvertMetadataSchema,
15911
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15912
+ calibrationRef: string().optional(),
15913
+ sessionId: string().optional()
15914
+ }), ConvertResultSchema, {
15915
+ kind: "mutation",
15916
+ auth: "admin",
15917
+ timeoutMs: 6e5
15918
+ });
15919
+ method(object({
15920
+ nodeId: string(),
15921
+ modelId: string(),
15922
+ format: _enum(MODEL_FORMATS),
15923
+ entry: ModelCatalogEntrySchema
15924
+ }), object({
15925
+ ok: boolean(),
15926
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15927
+ sha256: string(),
15928
+ bytes: number(),
15929
+ /** The target node's modelsDir the artifact landed in. */
15930
+ path: string()
15931
+ }), {
15932
+ kind: "mutation",
15933
+ auth: "admin"
15934
+ });
15935
+ /**
15936
+ * `mqtt-broker` — broker-registry cap.
15937
+ *
15938
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15939
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15940
+ * and (b) the connection details a consumer addon needs to spin up
15941
+ * its OWN `mqtt.js` client.
15942
+ *
15943
+ * Why: pub/sub routing over the system event-bus loses fidelity
15944
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15945
+ * refcount bookkeeping that addons would rather own themselves. The
15946
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15947
+ * features anyway — give it the connection config, get out of the way.
15948
+ *
15949
+ * Consumer flow:
15950
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15951
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15952
+ * client.subscribe('zigbee2mqtt/+')
15953
+ *
15954
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
15955
+ * cloud bridge). The "embedded" entry (when present) is just another
15956
+ * broker in the registry — its lifecycle is owned by the addon that
15957
+ * spawned it.
15958
+ */
15959
+ var BrokerKindSchema = _enum(["external", "embedded"]);
15960
+ /**
15961
+ * Broker live-probe status.
15962
+ *
15963
+ * - `connected` — last probe completed a clean CONNACK
15964
+ * - `disconnected` — no probe has run yet (cold cache)
15965
+ * - `auth-failed` — CONNACK refused with auth error (RC 4 / 5)
15966
+ * - `unreachable` — TCP connect timed out / refused
15967
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15968
+ */
15969
+ var BrokerStatusSchema$1 = _enum([
15970
+ "connected",
15971
+ "disconnected",
15972
+ "auth-failed",
15973
+ "unreachable",
15974
+ "tls-error"
15975
+ ]);
15976
+ var BrokerInfoSchema = object({
15977
+ id: string(),
15978
+ name: string(),
15979
+ url: string(),
15980
+ kind: BrokerKindSchema,
15981
+ status: BrokerStatusSchema$1,
15982
+ latencyMs: number().nullable(),
15983
+ error: string().optional(),
15984
+ /** Embedded brokers only: number of MQTT clients currently connected. */
15985
+ connectedClients: number().int().nonnegative().optional(),
15986
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15987
+ lastCheckedAt: number().optional()
15988
+ });
15989
+ /**
15990
+ * Connection details — what a consumer needs to call
15991
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
15992
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
15993
+ * instead of stuffing creds into the URL (which leaks them into logs).
15994
+ */
15995
+ var BrokerConnectionDetailsSchema = object({
15996
+ url: string(),
15997
+ username: string().optional(),
15998
+ password: string().optional(),
15999
+ /**
16000
+ * Suggested prefix for `clientId`. Each consumer should suffix this
16001
+ * with its own discriminator (addon id, instance id) so reconnects
16002
+ * don't kick each other off (MQTT spec: clientId must be unique per
16003
+ * broker).
16004
+ */
16005
+ clientIdPrefix: string().optional()
16006
+ });
16007
+ var AddBrokerInputSchema = object({
16008
+ name: string().min(1),
16009
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
16010
+ username: string().optional(),
16011
+ password: string().optional(),
16012
+ clientIdPrefix: string().optional()
16013
+ });
16014
+ var AddBrokerResultSchema = object({ id: string() });
16015
+ var IdInputSchema = object({ id: string() });
16016
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
16017
+ ok: literal(true),
16018
+ latencyMs: number()
16019
+ }), object({
16020
+ ok: literal(false),
16021
+ error: string()
16022
+ })]);
16023
+ var StartEmbeddedInputSchema = object({
16024
+ port: number().int().min(1).max(65535).default(1883),
16025
+ /** Allow anonymous connect (no username/password). Default: false. */
16026
+ allowAnonymous: boolean().default(false),
16027
+ /** Optional shared username/password for clients. */
16028
+ username: string().optional(),
16029
+ password: string().optional()
16030
+ });
16031
+ var StartEmbeddedResultSchema = object({
16032
+ id: string(),
16033
+ url: string()
16034
+ });
16035
+ var StatusSchema = object({
16036
+ brokerCount: number(),
16037
+ embeddedRunning: boolean()
16038
+ });
16039
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
16040
+ var NetworkEndpointSchema = object({
16041
+ url: string(),
16042
+ hostname: string(),
16043
+ port: number(),
16044
+ protocol: _enum(["http", "https"])
16045
+ });
16046
+ var NetworkAccessStatusSchema = object({
16047
+ connected: boolean(),
16048
+ endpoint: NetworkEndpointSchema.nullable(),
16049
+ error: string().optional()
16050
+ });
16051
+ /**
16052
+ * Optional, richer endpoint shape returned by providers that expose
16053
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
16054
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16055
+ * the originating provider config (mode + sourcePort) so the
16056
+ * orchestrator UI can label rows distinctly. Providers that expose only
16057
+ * one endpoint just omit `listEndpoints` from their provider impl.
16058
+ */
16059
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16060
+ /**
16061
+ * Stable id within the provider — typically `<mode>-<sourcePort>` so
16062
+ * the orchestrator can dedupe across `listEndpoints` polls.
16063
+ */
16064
+ id: string(),
16065
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16066
+ label: string(),
16067
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16068
+ mode: string().optional(),
16069
+ /** Originating local port the ingress fronts (informational). */
16070
+ sourcePort: number().optional()
16071
+ });
16072
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16073
+ /**
16074
+ * notification-output — canonical, capability-gated notification delivery.
16075
+ *
16076
+ * Apprise-derived model (see
16077
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16078
+ * callers emit ONE canonical `Notification`; each provider declares a
15823
16079
  * per-kind capability descriptor (`TargetKind`), and the pure degrade
15824
16080
  * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15825
16081
  * message to what the kind supports — callers never special-case a service.
@@ -15947,14 +16203,14 @@ var TargetKindCapsSchema = object({
15947
16203
  * the union is large and not meant for runtime validation here; the exported
15948
16204
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15949
16205
  */
15950
- var ConfigSchemaPassthrough$1 = unknown();
16206
+ var ConfigSchemaPassthrough = unknown();
15951
16207
  var TargetKindSchema = object({
15952
16208
  kind: string(),
15953
16209
  label: string(),
15954
16210
  icon: string(),
15955
16211
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
15956
16212
  addonId: string(),
15957
- configSchema: ConfigSchemaPassthrough$1,
16213
+ configSchema: ConfigSchemaPassthrough,
15958
16214
  supportsDiscovery: boolean(),
15959
16215
  caps: TargetKindCapsSchema
15960
16216
  });
@@ -16005,299 +16261,766 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
16005
16261
  }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16006
16262
  targetId: string(),
16007
16263
  enabled: boolean()
16008
- }), _void(), { kind: "mutation" });
16009
- /**
16010
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
16011
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
16012
- * caps stay wire-compatible without a circular cap→cap import.
16013
- *
16014
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
16015
- * every transport tier structurally, and failed calls still write usage rows.
16016
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
16017
- */
16018
- var LlmUsageSchema = object({
16019
- inputTokens: number(),
16020
- outputTokens: number()
16021
- });
16022
- var LlmErrorCodeSchema = _enum([
16023
- "timeout",
16024
- "rate-limited",
16025
- "auth",
16026
- "refusal",
16027
- "bad-request",
16028
- "unavailable",
16029
- "no-profile",
16030
- "budget-exceeded",
16031
- "adapter-error"
16032
- ]);
16033
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
16034
- ok: literal(true),
16035
- text: string(),
16036
- model: string(),
16037
- usage: LlmUsageSchema,
16038
- truncated: boolean(),
16039
- latencyMs: number()
16040
- }), object({
16041
- ok: literal(false),
16042
- code: LlmErrorCodeSchema,
16043
- message: string(),
16044
- retryAfterMs: number().optional()
16045
- })]);
16046
- /**
16047
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
16048
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
16049
- * notification-output.cap.ts:27-31 precedents).
16050
- */
16051
- var LlmImageSchema = object({
16052
- bytes: _instanceof(Uint8Array),
16053
- mimeType: string()
16054
- });
16055
- var LlmGenerateBaseInputSchema = object({
16056
- /** Collection routing (the notification-output posture). */
16057
- addonId: string().optional(),
16058
- /** Explicit profile; else the resolution chain (spec §3). */
16059
- profileId: string().optional(),
16060
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
16061
- consumer: string(),
16062
- system: string().optional(),
16063
- /** v1: single-turn. `messages[]` is a v2 additive field. */
16064
- prompt: string(),
16065
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
16066
- jsonSchema: record(string(), unknown()).optional(),
16067
- /** Per-call override of the profile default. */
16068
- maxTokens: number().int().positive().optional(),
16069
- temperature: number().optional()
16070
- });
16264
+ }), _void(), { kind: "mutation" });
16071
16265
  /**
16072
- * `llm-runtime`node-side managed llama.cpp executor (spec §4). Registered
16073
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
16074
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
16075
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
16076
- * this only through the `llm` cap's methods.
16266
+ * notification-rulesthe Notification Center rule surface (P1 core).
16077
16267
  *
16078
- * One running llama-server child per node in v1 (models are RAM-heavy).
16079
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
16080
- * watchdog — operator decision #3).
16268
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16269
+ * (operator decisions D-1/D-2/D-3 are binding):
16270
+ *
16271
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16272
+ * `notification-center` module), hooked on the durable persistence
16273
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16274
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16275
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16276
+ * FIRST persisted detection matching the conditions (per-track dedup,
16277
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16278
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16279
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16280
+ * by id; per-backend params are a passthrough blob capped by the
16281
+ * target kind's own caps/degrade engine).
16282
+ *
16283
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16284
+ * server-injected caller identity — the first `caller: 'required'`
16285
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16286
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16287
+ * windows, and the optional label/identity/plate matchers. User rules,
16288
+ * private zones, per-recipient fan-out and the wider condition table are
16289
+ * P2+ (see spec §7).
16290
+ *
16291
+ * All schemas here are the single source of truth — `NcRule` etc. are
16292
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16293
+ * schema/interface drift is explicitly not repeated).
16081
16294
  */
16082
- var ManagedModelRefSchema = discriminatedUnion("kind", [
16083
- object({
16084
- kind: literal("catalog"),
16085
- catalogId: string()
16086
- }),
16087
- object({
16088
- kind: literal("url"),
16089
- url: string(),
16090
- sha256: string().optional()
16091
- }),
16092
- object({
16093
- kind: literal("path"),
16094
- path: string()
16095
- })
16295
+ /**
16296
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16297
+ * The value maps 1:1 onto the evaluated record kind:
16298
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16299
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16300
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16301
+ * change of a LINKED device, one row per linked camera)
16302
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16303
+ * delivery / pick-up)
16304
+ *
16305
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16306
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16307
+ * this one field keeps the schema additive — a rule still declares exactly
16308
+ * one trigger.
16309
+ */
16310
+ var NcDeliverySchema = _enum([
16311
+ "immediate",
16312
+ "track-end",
16313
+ "device-event",
16314
+ "package-event"
16096
16315
  ]);
16097
- var ManagedRuntimeConfigSchema = object({
16098
- /** WHERE the runtime lives — hub or any agent. */
16099
- nodeId: string(),
16100
- /** Closed for v1; 'ollama' is a v2 candidate. */
16101
- engine: _enum(["llama-cpp"]),
16102
- model: ManagedModelRefSchema,
16103
- contextSize: number().int().default(4096),
16104
- /** 0 = CPU-only. */
16105
- gpuLayers: number().int().default(0),
16106
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16107
- threads: number().int().optional(),
16108
- /** Concurrent slots. */
16109
- parallel: number().int().default(1),
16110
- /** Else lazy: first generate boots it. */
16111
- autoStart: boolean().default(false),
16112
- /** 0 = never; frees RAM after quiet periods. */
16113
- idleStopMinutes: number().int().default(30)
16316
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16317
+ var NcScheduleSchema = object({
16318
+ windows: array(object({
16319
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16320
+ days: array(number().int().min(0).max(6)).min(1),
16321
+ startMinute: number().int().min(0).max(1439),
16322
+ endMinute: number().int().min(0).max(1439)
16323
+ })).min(1),
16324
+ /** IANA timezone; default = hub host timezone. */
16325
+ timezone: string().optional(),
16326
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16327
+ invert: boolean().optional()
16114
16328
  });
16115
- var LlmRuntimeStatusSchema = object({
16116
- /** Status is ALWAYS node-qualified. */
16117
- nodeId: string(),
16118
- state: _enum([
16119
- "stopped",
16120
- "downloading",
16121
- "starting",
16122
- "ready",
16123
- "crashed",
16124
- "failed"
16125
- ]),
16126
- pid: number().optional(),
16127
- port: number().optional(),
16128
- modelPath: string().optional(),
16129
- modelId: string().optional(),
16130
- downloadProgress: number().min(0).max(1).optional(),
16131
- lastError: string().optional(),
16132
- crashesInWindow: number(),
16133
- /** Child RSS (sampled best-effort). */
16134
- memoryBytes: number().optional(),
16135
- vramBytes: number().optional()
16329
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16330
+ var NcPlateMatcherSchema = object({
16331
+ values: array(string().min(1)).min(1),
16332
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16333
+ maxDistance: number().int().min(0).max(3).default(1)
16136
16334
  });
16137
- var LlmNodeModelSchema = object({
16138
- file: string(),
16139
- sizeBytes: number(),
16140
- catalogId: string().optional(),
16141
- installedAt: number().optional()
16335
+ /**
16336
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16337
+ * occupancy edge for a device — optionally narrowed to a single admin
16338
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16339
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16340
+ * - `became-free` — count crossed ≥ `count` → below it
16341
+ * - `>=` / `<=` — count is at/over or at/under `count`
16342
+ * `sustainSeconds` requires the condition hold continuously that long
16343
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16344
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16345
+ * the condition never matches. Confirmed edge-state survives addon restarts
16346
+ * (declared SQLite collection, reseeded on boot).
16347
+ */
16348
+ var NcOccupancyConditionSchema = object({
16349
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16350
+ zoneId: string().optional(),
16351
+ /** Object class to count; absent = any class. */
16352
+ className: string().optional(),
16353
+ op: _enum([
16354
+ "became-occupied",
16355
+ "became-free",
16356
+ ">=",
16357
+ "<="
16358
+ ]).default("became-occupied"),
16359
+ count: number().int().min(0).default(1),
16360
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16361
+ });
16362
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16363
+ var NcZoneConditionSchema = object({
16364
+ ids: array(string().min(1)).min(1),
16365
+ /** Quantifier over `ids` — at least one / every one visited. */
16366
+ match: _enum(["any", "all"]).default("any")
16142
16367
  });
16143
- var LlmRuntimeDiskUsageSchema = object({
16144
- nodeId: string(),
16145
- modelsBytes: number(),
16146
- freeBytes: number().optional()
16368
+ /**
16369
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16370
+ * membership lists are OR within the list (spec §2.3).
16371
+ */
16372
+ var NcConditionsSchema = object({
16373
+ /** Device scope — absent = all devices. */
16374
+ devices: array(number()).optional(),
16375
+ /** Detector class names (any overlap with the record's class set). */
16376
+ classes: array(string().min(1)).optional(),
16377
+ /** Veto classes — any overlap fails the rule. */
16378
+ classesExclude: array(string().min(1)).optional(),
16379
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16380
+ minConfidence: number().min(0).max(1).optional(),
16381
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16382
+ zones: NcZoneConditionSchema.optional(),
16383
+ /** Veto zones — any hit fails the rule. */
16384
+ zonesExclude: array(string().min(1)).optional(),
16385
+ /**
16386
+ * Exact (case-insensitive) match on the record's collapsed `label`
16387
+ * (identity name / plate text / subclass).
16388
+ */
16389
+ labelEquals: array(string().min(1)).optional(),
16390
+ /**
16391
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16392
+ * `label` (the identity display name propagated by the face pipeline) —
16393
+ * identity-ID matching rides in P2 when identity ids reach the record.
16394
+ */
16395
+ identities: array(string().min(1)).optional(),
16396
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16397
+ plates: NcPlateMatcherSchema.optional(),
16398
+ /**
16399
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16400
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16401
+ * identity display name). A record with NO label passes (nothing to
16402
+ * exclude), unlike the include variant which fails on an absent label.
16403
+ */
16404
+ identitiesExclude: array(string().min(1)).optional(),
16405
+ /**
16406
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16407
+ * TRACK-END only: importance is scored at track close, so it does not exist
16408
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16409
+ * close the value is threaded via the close-time info (the `Track` clone is
16410
+ * captured before the DB row is updated, so it would otherwise read stale).
16411
+ * Fails when the record carries no importance (never guess quality — the
16412
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16413
+ */
16414
+ minImportance: number().min(0).max(1).optional(),
16415
+ /**
16416
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16417
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16418
+ * lifespan, so a dwell condition never matches immediate delivery
16419
+ * (documented choice — the object-event record carries no `firstSeen`,
16420
+ * so dwell cannot be computed from what the subject actually carries).
16421
+ */
16422
+ minDwellSeconds: number().min(0).optional(),
16423
+ /**
16424
+ * Detection provenance filter. `any` (default / absent) matches every
16425
+ * source; otherwise the subject's source must equal it. Legacy records
16426
+ * with no stamped source are treated as `pipeline`. The union spans both
16427
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16428
+ * tracks carry `sensor`.
16429
+ */
16430
+ source: _enum([
16431
+ "pipeline",
16432
+ "onboard",
16433
+ "sensor",
16434
+ "any"
16435
+ ]).optional(),
16436
+ /**
16437
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16438
+ * detector `minConfidence` (that gates the object-detection score; this
16439
+ * gates the recognition/OCR match score). Fails when the subject carries
16440
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16441
+ * lives on the recognition result and reaches the subject at track close.
16442
+ *
16443
+ * What it measures precisely (plumbed at track close — the closer threads
16444
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16445
+ * `importance`): the BEST recognition match confidence observed for the
16446
+ * label the track carries at close — for a face, the peak cosine similarity
16447
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16448
+ * for a plate, the peak OCR read score of the best-held plate
16449
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16450
+ * one track the higher of the two is used. A track that ended with no
16451
+ * confident identity/plate match carries no value, so the condition fails
16452
+ * closed for it (an un-recognized subject).
16453
+ */
16454
+ minLabelConfidence: number().min(0).max(1).optional(),
16455
+ /**
16456
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16457
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16458
+ * against the token carried on the device-event subject (extracted from the
16459
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16460
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16461
+ * eventType, so gate those with {@link sensorKinds} instead.
16462
+ */
16463
+ eventTypeTokens: array(string().min(1)).optional(),
16464
+ /**
16465
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16466
+ * `contact`, `button`, `device-event`) — matched against the persisted
16467
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16468
+ */
16469
+ sensorKinds: array(string().min(1)).optional(),
16470
+ /**
16471
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16472
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16473
+ * when the subject's phase does not match (a subject always carries a phase
16474
+ * on the package-event trigger).
16475
+ */
16476
+ packagePhase: _enum([
16477
+ "delivered",
16478
+ "picked-up",
16479
+ "both"
16480
+ ]).optional(),
16481
+ /**
16482
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16483
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16484
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16485
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16486
+ */
16487
+ customZones: array(MaskPolygonShapeSchema).optional(),
16488
+ /**
16489
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16490
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16491
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16492
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16493
+ */
16494
+ occupancy: NcOccupancyConditionSchema.optional()
16495
+ });
16496
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16497
+ var NcRuleTargetSchema = object({
16498
+ /** `notification-output` Target id. */
16499
+ targetId: string().min(1),
16500
+ /**
16501
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16502
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16503
+ * degrade engine drops what the backend can't render.
16504
+ */
16505
+ params: record(string(), unknown()).optional()
16147
16506
  });
16148
- method(LlmGenerateBaseInputSchema.extend({
16149
- images: array(LlmImageSchema).optional(),
16150
- runtime: ManagedRuntimeConfigSchema,
16151
- /** The managed profile's timeout, threaded by the hub provider. */
16152
- timeoutMs: number().int().positive().optional()
16153
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16154
- kind: "mutation",
16155
- auth: "admin"
16156
- }), method(object({}), _void(), {
16157
- kind: "mutation",
16158
- auth: "admin"
16159
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16160
- kind: "mutation",
16161
- auth: "admin"
16162
- }), method(object({ file: string() }), _void(), {
16163
- kind: "mutation",
16164
- auth: "admin"
16165
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16166
16507
  /**
16167
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16168
- * methods concat-fan across providers; single-row methods route to ONE
16169
- * provider by the `addonId` in the call input (the notification-output
16170
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16171
- * (hub-placed); the cap stays open for future providers.
16172
- *
16173
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16174
- * `apiKey` is a password field providers REDACT it on read and merge on
16175
- * write; a stored key NEVER round-trips to a client.
16508
+ * Media attachment policy (P1 still-image subset).
16509
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16510
+ * - `best-matching` the media that explains WHY the rule fired: a rule
16511
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16512
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16513
+ * (or when the specific crop is missing) degrades to `best`, then
16514
+ * `keyFrame`, then no attachment never delaying the send. The matched
16515
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16516
+ * name), so the choice never drifts from the record that fired it.
16517
+ * - `keyFrame` — the clean scene frame (no subject box).
16518
+ * - `none` — no attachment.
16176
16519
  */
16177
- var LlmProfileKindSchema = _enum([
16178
- "openai-compatible",
16179
- "openai",
16180
- "anthropic",
16181
- "google",
16182
- "managed-local"
16183
- ]);
16184
- var LlmProfileSchema = object({
16520
+ var NcMediaPolicySchema = object({ attach: _enum([
16521
+ "best",
16522
+ "best-matching",
16523
+ "keyFrame",
16524
+ "none"
16525
+ ]).default("best") });
16526
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16527
+ var NcThrottleSchema = object({
16528
+ cooldownSec: number().int().min(0).max(86400).default(60),
16529
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16530
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16531
+ });
16532
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16533
+ var NcRuleInputSchema = object({
16534
+ name: string().min(1).max(200),
16535
+ enabled: boolean().default(true),
16536
+ delivery: NcDeliverySchema,
16537
+ conditions: NcConditionsSchema.default({}),
16538
+ schedule: NcScheduleSchema.optional(),
16539
+ targets: array(NcRuleTargetSchema).min(1),
16540
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16541
+ throttle: NcThrottleSchema.default({
16542
+ cooldownSec: 60,
16543
+ scope: "rule-device"
16544
+ }),
16545
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16546
+ template: object({
16547
+ title: string().max(500).optional(),
16548
+ body: string().max(2e3).optional()
16549
+ }).optional(),
16550
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16551
+ priority: number().int().min(1).max(5).default(3),
16552
+ /**
16553
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16554
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16555
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16556
+ */
16557
+ ownerUserId: string().optional()
16558
+ });
16559
+ /**
16560
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16561
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16562
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16563
+ * input), so it is added here explicitly to let the store's per-target opt-out
16564
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16565
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16566
+ * `updateRule` patch.
16567
+ */
16568
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16569
+ /** A persisted rule. */
16570
+ var NcRuleSchema = NcRuleInputSchema.extend({
16185
16571
  id: string(),
16186
- name: string(),
16187
- kind: LlmProfileKindSchema,
16188
- /** Stamped by the provider — keeps the fanned catalog routable. */
16189
- addonId: string(),
16190
- enabled: boolean(),
16191
- /** Vendor model id, or the managed runtime's loaded model. */
16192
- model: string(),
16193
- /** Required for openai-compatible; override for cloud kinds. */
16194
- baseUrl: string().optional(),
16195
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16196
- apiKey: string().optional(),
16197
- supportsVision: boolean(),
16198
- temperature: number().min(0).max(2).optional(),
16199
- maxTokens: number().int().positive().optional(),
16200
- timeoutMs: number().int().positive().default(6e4),
16201
- extraHeaders: record(string(), string()).optional(),
16202
- /** kind === 'managed-local' only (spec §4). */
16203
- runtime: ManagedRuntimeConfigSchema.optional()
16572
+ /** userId of the admin who created the rule (server-stamped caller). */
16573
+ createdBy: string(),
16574
+ createdAt: number(),
16575
+ updatedAt: number(),
16576
+ /**
16577
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16578
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16579
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16580
+ */
16581
+ disabledTargetIds: array(string()).default([])
16582
+ });
16583
+ var NcTestResultSchema = object({
16584
+ recordId: string(),
16585
+ recordKind: _enum([
16586
+ "object-event",
16587
+ "track",
16588
+ "device-event",
16589
+ "package-event"
16590
+ ]),
16591
+ deviceId: number(),
16592
+ timestamp: number(),
16593
+ wouldFire: boolean(),
16594
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16595
+ failedCondition: string().optional(),
16596
+ className: string().optional(),
16597
+ label: string().optional()
16204
16598
  });
16205
- /** ConfigUISchema tree passed through untyped on the wire (the
16206
- * notification-output `ConfigSchemaPassthrough` precedent at
16207
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16208
- var ConfigSchemaPassthrough = unknown();
16209
- var LlmProfileKindDescriptorSchema = object({
16210
- kind: LlmProfileKindSchema,
16599
+ var NcConditionDescriptorSchema = object({
16600
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16601
+ id: string(),
16602
+ group: _enum([
16603
+ "scope",
16604
+ "class",
16605
+ "zones",
16606
+ "quality",
16607
+ "label",
16608
+ "schedule",
16609
+ "device",
16610
+ "package",
16611
+ "occupancy"
16612
+ ]),
16211
16613
  label: string(),
16212
- icon: string(),
16213
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16214
- addonId: string(),
16215
- configSchema: ConfigSchemaPassthrough
16216
- });
16217
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16218
- var LlmDefaultSchema = object({
16219
- selector: LlmDefaultSelectorSchema,
16220
- profileId: string()
16614
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16615
+ valueType: _enum([
16616
+ "deviceIdList",
16617
+ "stringList",
16618
+ "number01",
16619
+ "number",
16620
+ "sourceSelect",
16621
+ "zoneSelection",
16622
+ "zoneIdList",
16623
+ "schedule",
16624
+ "plateMatcher",
16625
+ "packagePhase",
16626
+ "polygonDraw",
16627
+ "occupancy"
16628
+ ]),
16629
+ operator: _enum([
16630
+ "in",
16631
+ "notIn",
16632
+ "anyOf",
16633
+ "allOf",
16634
+ "gte",
16635
+ "fuzzyIn",
16636
+ "withinSchedule"
16637
+ ]),
16638
+ /** Which delivery kinds the condition applies to. */
16639
+ appliesTo: array(NcDeliverySchema),
16640
+ phase: string(),
16641
+ description: string().optional()
16221
16642
  });
16222
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16223
- var LlmUsageRollupSchema = object({
16224
- day: string(),
16225
- consumer: string(),
16226
- profileId: string(),
16227
- calls: number(),
16228
- okCalls: number(),
16229
- errorCalls: number(),
16230
- inputTokens: number(),
16231
- outputTokens: number(),
16232
- avgLatencyMs: number()
16643
+ /**
16644
+ * The P1 condition surface as data — served by `getConditionCatalog` so
16645
+ * rule editors render from the catalog, not hardcoded forms (spec §4.2).
16646
+ */
16647
+ var NC_CONDITION_CATALOG = [
16648
+ {
16649
+ id: "devices",
16650
+ group: "scope",
16651
+ label: "Cameras",
16652
+ valueType: "deviceIdList",
16653
+ operator: "in",
16654
+ appliesTo: [
16655
+ "immediate",
16656
+ "track-end",
16657
+ "device-event",
16658
+ "package-event"
16659
+ ],
16660
+ phase: "P1",
16661
+ description: "Restrict the rule to these devices; absent = all devices."
16662
+ },
16663
+ {
16664
+ id: "classes",
16665
+ group: "class",
16666
+ label: "Object classes",
16667
+ valueType: "stringList",
16668
+ operator: "in",
16669
+ appliesTo: [
16670
+ "immediate",
16671
+ "track-end",
16672
+ "package-event"
16673
+ ],
16674
+ phase: "P1",
16675
+ description: "Any overlap with the detection class set passes."
16676
+ },
16677
+ {
16678
+ id: "classesExclude",
16679
+ group: "class",
16680
+ label: "Excluded classes",
16681
+ valueType: "stringList",
16682
+ operator: "notIn",
16683
+ appliesTo: [
16684
+ "immediate",
16685
+ "track-end",
16686
+ "package-event"
16687
+ ],
16688
+ phase: "P1"
16689
+ },
16690
+ {
16691
+ id: "minConfidence",
16692
+ group: "quality",
16693
+ label: "Minimum confidence",
16694
+ valueType: "number01",
16695
+ operator: "gte",
16696
+ appliesTo: [
16697
+ "immediate",
16698
+ "track-end",
16699
+ "package-event"
16700
+ ],
16701
+ phase: "P1"
16702
+ },
16703
+ {
16704
+ id: "zones",
16705
+ group: "zones",
16706
+ label: "Zones",
16707
+ valueType: "zoneSelection",
16708
+ operator: "anyOf",
16709
+ appliesTo: [
16710
+ "immediate",
16711
+ "track-end",
16712
+ "package-event"
16713
+ ],
16714
+ phase: "P1",
16715
+ description: "Admin zone ids; quantifier any/all over the visited set."
16716
+ },
16717
+ {
16718
+ id: "zonesExclude",
16719
+ group: "zones",
16720
+ label: "Excluded zones",
16721
+ valueType: "zoneIdList",
16722
+ operator: "notIn",
16723
+ appliesTo: [
16724
+ "immediate",
16725
+ "track-end",
16726
+ "package-event"
16727
+ ],
16728
+ phase: "P1"
16729
+ },
16730
+ {
16731
+ id: "labelEquals",
16732
+ group: "label",
16733
+ label: "Label equals",
16734
+ valueType: "stringList",
16735
+ operator: "in",
16736
+ appliesTo: ["immediate", "track-end"],
16737
+ phase: "P1",
16738
+ description: "Exact match on the collapsed label (identity / plate / subclass)."
16739
+ },
16740
+ {
16741
+ id: "identities",
16742
+ group: "label",
16743
+ label: "Identities",
16744
+ valueType: "stringList",
16745
+ operator: "in",
16746
+ appliesTo: ["immediate", "track-end"],
16747
+ phase: "P1",
16748
+ description: "P1: matched against the identity display name on the record label."
16749
+ },
16750
+ {
16751
+ id: "plates",
16752
+ group: "label",
16753
+ label: "License plates",
16754
+ valueType: "plateMatcher",
16755
+ operator: "fuzzyIn",
16756
+ appliesTo: ["immediate", "track-end"],
16757
+ phase: "P1",
16758
+ description: "Levenshtein-tolerant match against the plate text."
16759
+ },
16760
+ {
16761
+ id: "identitiesExclude",
16762
+ group: "label",
16763
+ label: "Excluded identities",
16764
+ valueType: "stringList",
16765
+ operator: "notIn",
16766
+ appliesTo: ["immediate", "track-end"],
16767
+ phase: "P1",
16768
+ description: "Veto by identity display name (mirror of Identities; absent label passes)."
16769
+ },
16770
+ {
16771
+ id: "minLabelConfidence",
16772
+ group: "label",
16773
+ label: "Minimum label confidence",
16774
+ valueType: "number01",
16775
+ operator: "gte",
16776
+ appliesTo: ["track-end"],
16777
+ phase: "P1",
16778
+ description: "Best identity/plate recognition match confidence [0,1] for the label the track carries at close (peak assigned-identity cosine / peak plate OCR score; the higher of the two when both were read). Distinct from detection confidence. Fails closed for a track that ended un-recognized."
16779
+ },
16780
+ {
16781
+ id: "minImportance",
16782
+ group: "quality",
16783
+ label: "Minimum importance",
16784
+ valueType: "number01",
16785
+ operator: "gte",
16786
+ appliesTo: ["track-end"],
16787
+ phase: "P1",
16788
+ description: "Server-computed key-event importance [0,1]; track-end rules only (importance is scored at close). Fails when the record has none."
16789
+ },
16790
+ {
16791
+ id: "minDwellSeconds",
16792
+ group: "quality",
16793
+ label: "Minimum dwell (seconds)",
16794
+ valueType: "number",
16795
+ operator: "gte",
16796
+ appliesTo: ["track-end"],
16797
+ phase: "P1",
16798
+ description: "Track lifespan in seconds (lastSeen − firstSeen); track-end rules only."
16799
+ },
16800
+ {
16801
+ id: "source",
16802
+ group: "scope",
16803
+ label: "Detection source",
16804
+ valueType: "sourceSelect",
16805
+ operator: "in",
16806
+ appliesTo: [
16807
+ "immediate",
16808
+ "track-end",
16809
+ "device-event",
16810
+ "package-event"
16811
+ ],
16812
+ phase: "P1",
16813
+ description: "pipeline / onboard / sensor; a record with no stamped source counts as pipeline."
16814
+ },
16815
+ {
16816
+ id: "sensorKinds",
16817
+ group: "device",
16818
+ label: "Sensor kinds",
16819
+ valueType: "stringList",
16820
+ operator: "in",
16821
+ appliesTo: ["device-event"],
16822
+ phase: "P1",
16823
+ description: "Sensor/control taxonomy kinds (doorbell / contact / button / …) matched against the persisted device event."
16824
+ },
16825
+ {
16826
+ id: "eventTypeTokens",
16827
+ group: "device",
16828
+ label: "Event-type tokens",
16829
+ valueType: "stringList",
16830
+ operator: "in",
16831
+ appliesTo: ["device-event"],
16832
+ phase: "P1",
16833
+ description: "Raw device event-type tokens (e.g. doorbell press / press_long) from the event-emitter slice; absent on doorbell-pulse / passive sensors."
16834
+ },
16835
+ {
16836
+ id: "packagePhase",
16837
+ group: "package",
16838
+ label: "Package phase",
16839
+ valueType: "packagePhase",
16840
+ operator: "in",
16841
+ appliesTo: ["package-event"],
16842
+ phase: "P1",
16843
+ description: "Delivered / picked-up / both."
16844
+ },
16845
+ {
16846
+ id: "occupancy",
16847
+ group: "occupancy",
16848
+ label: "Occupancy",
16849
+ valueType: "occupancy",
16850
+ operator: "anyOf",
16851
+ appliesTo: ["device-event"],
16852
+ phase: "P1",
16853
+ description: "ZoneAnalytics occupancy edge (optionally zone/class-scoped): count crosses the threshold and holds for sustainSeconds. Fail-closed on a missing snapshot."
16854
+ },
16855
+ {
16856
+ id: "customZones",
16857
+ group: "zones",
16858
+ label: "Custom zones",
16859
+ valueType: "polygonDraw",
16860
+ operator: "anyOf",
16861
+ appliesTo: [
16862
+ "immediate",
16863
+ "track-end",
16864
+ "package-event"
16865
+ ],
16866
+ phase: "P1",
16867
+ description: "User-drawn polygons; a detection whose bbox overlaps any polygon matches."
16868
+ },
16869
+ {
16870
+ id: "schedule",
16871
+ group: "schedule",
16872
+ label: "Schedule",
16873
+ valueType: "schedule",
16874
+ operator: "withinSchedule",
16875
+ appliesTo: [
16876
+ "immediate",
16877
+ "track-end",
16878
+ "device-event",
16879
+ "package-event"
16880
+ ],
16881
+ phase: "P1",
16882
+ description: "Weekly activation windows (invertible); absent = always active."
16883
+ }
16884
+ ];
16885
+ /**
16886
+ * The delivery lifecycle status of a history row — a straight read of the
16887
+ * durable outbox row's own status (single source of truth):
16888
+ * - `pending` — enqueued, in-flight or retrying with backoff
16889
+ * - `sent` — delivered (terminal)
16890
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16891
+ * backend rejection / a deleted target (terminal; carries
16892
+ * the failure `error`)
16893
+ *
16894
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16895
+ * user dimension (quiet hours / snooze) and are additive when they land.
16896
+ */
16897
+ var NcHistoryStatusSchema = _enum([
16898
+ "pending",
16899
+ "sent",
16900
+ "dead"
16901
+ ]);
16902
+ /** The evaluated record kind a history row descends from (one per trigger). */
16903
+ var NcHistoryRecordKindSchema = _enum([
16904
+ "object-event",
16905
+ "track-end",
16906
+ "device-event",
16907
+ "package-event"
16908
+ ]);
16909
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16910
+ var NcHistorySubjectSchema = object({
16911
+ className: string(),
16912
+ label: string().optional(),
16913
+ confidence: number().optional(),
16914
+ zones: array(string()),
16915
+ timestamp: number()
16233
16916
  });
16234
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16235
- var ManagedModelCatalogEntrySchema = object({
16917
+ /**
16918
+ * One delivery-history row. This is a read-only VIEW over the durable
16919
+ * outbox row (single source of truth — the same row the drain loop drives;
16920
+ * NO second write path, so history can never drift from delivery state).
16921
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16922
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16923
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16924
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16925
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16926
+ * P1 (admin scope only).
16927
+ */
16928
+ var NcHistoryEntrySchema = object({
16929
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16236
16930
  id: string(),
16237
- label: string(),
16238
- family: string(),
16239
- purpose: _enum(["text", "vision"]),
16240
- url: string(),
16241
- sha256: string(),
16242
- sizeBytes: number(),
16243
- quantization: string(),
16244
- /** Load-time guidance shown in the picker. */
16245
- minRamBytes: number(),
16246
- contextSizeDefault: number().int(),
16247
- /** Vision models: companion projector file. */
16248
- mmprojUrl: string().optional()
16249
- });
16250
- var LlmRuntimeNodeSchema = object({
16251
- nodeId: string(),
16252
- reachable: boolean(),
16253
- status: LlmRuntimeStatusSchema.optional(),
16254
- disk: LlmRuntimeDiskUsageSchema.optional(),
16255
- error: string().optional()
16256
- });
16257
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16258
- var ProfileRefInputSchema = object({
16259
- addonId: string(),
16260
- profileId: string()
16931
+ ruleId: string(),
16932
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16933
+ ruleName: string(),
16934
+ /** The rule urgency/trigger that produced this delivery. */
16935
+ delivery: NcDeliverySchema,
16936
+ targetId: string(),
16937
+ deviceId: number(),
16938
+ recordKind: NcHistoryRecordKindSchema,
16939
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16940
+ recordId: string(),
16941
+ /** Present for track-scoped deliveries (object-event / track-end). */
16942
+ trackId: string().optional(),
16943
+ status: NcHistoryStatusSchema,
16944
+ /** Delivery attempts made so far. */
16945
+ attempts: number().int(),
16946
+ /** Fire time (outbox enqueue). */
16947
+ createdAt: number(),
16948
+ /** Last transition time (terminal for sent / dead). */
16949
+ updatedAt: number(),
16950
+ /** Failure detail — present on a `dead` row. */
16951
+ error: string().optional(),
16952
+ subject: NcHistorySubjectSchema
16261
16953
  });
16262
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16263
- kind: "mutation",
16264
- auth: "admin"
16265
- }), method(ProfileRefInputSchema, _void(), {
16266
- kind: "mutation",
16267
- auth: "admin"
16268
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16269
- kind: "mutation",
16270
- auth: "admin"
16271
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16272
- selector: LlmDefaultSelectorSchema,
16273
- profileId: string().nullable()
16274
- }), _void(), {
16275
- kind: "mutation",
16276
- auth: "admin"
16277
- }), method(object({
16954
+ /**
16955
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16956
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16957
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16958
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16959
+ */
16960
+ var NcHistoryFilterSchema = object({
16961
+ ruleId: string().optional(),
16962
+ deviceId: number().optional(),
16963
+ status: NcHistoryStatusSchema.optional(),
16278
16964
  since: number().optional(),
16279
16965
  until: number().optional(),
16280
- consumer: string().optional(),
16281
- profileId: string().optional()
16282
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16283
- nodeId: string(),
16284
- model: ManagedModelRefSchema
16285
- }), _void(), {
16286
- kind: "mutation",
16287
- auth: "admin"
16288
- }), method(object({
16289
- nodeId: string(),
16290
- file: string()
16291
- }), _void(), {
16292
- kind: "mutation",
16293
- auth: "admin"
16294
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16295
- kind: "mutation",
16296
- auth: "admin"
16297
- }), method(ProfileRefInputSchema, _void(), {
16298
- kind: "mutation",
16299
- auth: "admin"
16966
+ limit: number().int().min(1).max(500).default(100)
16300
16967
  });
16968
+ var notificationRulesCapability = {
16969
+ name: "notification-rules",
16970
+ scope: "system",
16971
+ mode: "singleton",
16972
+ methods: {
16973
+ listRules: method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }),
16974
+ getRule: method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }),
16975
+ createRule: method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
16976
+ kind: "mutation",
16977
+ auth: "admin",
16978
+ caller: "required"
16979
+ }),
16980
+ updateRule: method(object({
16981
+ ruleId: string(),
16982
+ patch: NcRulePatchSchema
16983
+ }), object({ rule: NcRuleSchema }), {
16984
+ kind: "mutation",
16985
+ auth: "admin",
16986
+ caller: "required"
16987
+ }),
16988
+ deleteRule: method(object({ ruleId: string() }), object({ success: literal(true) }), {
16989
+ kind: "mutation",
16990
+ auth: "admin"
16991
+ }),
16992
+ setRuleEnabled: method(object({
16993
+ ruleId: string(),
16994
+ enabled: boolean()
16995
+ }), object({ success: literal(true) }), {
16996
+ kind: "mutation",
16997
+ auth: "admin"
16998
+ }),
16999
+ /**
17000
+ * Dry-run a rule against recently persisted records (object events for
17001
+ * `immediate`, closed tracks for `track-end`). Mutation kind only to
17002
+ * carry the full rule object safely; no side effects.
17003
+ */
17004
+ testRule: method(object({
17005
+ rule: NcRuleInputSchema,
17006
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
17007
+ }), object({ results: array(NcTestResultSchema) }), {
17008
+ kind: "mutation",
17009
+ auth: "admin"
17010
+ }),
17011
+ getConditionCatalog: method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })),
17012
+ /**
17013
+ * Queryable delivery history — a read-only view over the durable outbox
17014
+ * (fired rule, subject summary, target, status, timestamps, error on a
17015
+ * dead row). Newest-first, bounded by `filter.limit`. Retention follows
17016
+ * the outbox's own terminal-row prune horizon (no separate history
17017
+ * horizon — single collection, single source of truth). Admin-only in
17018
+ * P1 (no user dimension); the P2 viewer History screen adds per-caller
17019
+ * scoping on the same method.
17020
+ */
17021
+ getHistory: method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" })
17022
+ }
17023
+ };
16301
17024
  /**
16302
17025
  * Zod schemas for persisted record types.
16303
17026
  *
@@ -17124,144 +17847,44 @@ var pipelineAnalyticsCapability = {
17124
17847
  */
17125
17848
  searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly())
17126
17849
  },
17127
- events: {
17128
- /**
17129
- * Enriched frame emitted after refinement — the live-overlay source of
17130
- * truth (two-plane re-injection). Carries the frame's detections in the
17131
- * `ObjectDetection` wire shape: first-level roots (with track info +
17132
- * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
17133
- * re-projected from per-track detail state, so stream overlays render
17134
- * boxes + recognized names without querying full Track state.
17135
- */
17136
- onFrameTracked: { data: object({
17137
- deviceId: number(),
17138
- timestamp: number(),
17139
- frameWidth: number(),
17140
- frameHeight: number(),
17141
- detections: array(OverlayDetectionSchema).readonly()
17142
- }) },
17143
- /** Track entered active state (first-seen). */
17144
- onTrackStarted: { data: object({
17145
- deviceId: number(),
17146
- trackId: string(),
17147
- className: string()
17148
- }) },
17149
- /** Track expired (TTL reached after last detection). */
17150
- onTrackEnded: { data: object({
17151
- deviceId: number(),
17152
- trackId: string(),
17153
- className: string(),
17154
- durationMs: number()
17155
- }) },
17156
- /** Canonical "something happened at device X" event, per-kind. */
17157
- onDetectionEvent: { data: object({
17158
- deviceId: number(),
17159
- kind: EventKindSchema,
17160
- eventId: string(),
17161
- timestamp: number()
17162
- }) }
17163
- }
17164
- };
17165
- /**
17166
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17167
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17168
- * caps into per-camera event-kind descriptors.
17169
- *
17170
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17171
- * is NOT duplicated here — every entry is derived from the single
17172
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17173
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17174
- * control cap means adding one line here (and a taxonomy entry); the anti-
17175
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17176
- * eventful cap is missing.
17177
- */
17178
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17179
- var LEGACY_ICON = {
17180
- motion: "motion",
17181
- audio: "audio",
17182
- person: "person",
17183
- vehicle: "vehicle",
17184
- animal: "animal",
17185
- package: "package",
17186
- door: "door",
17187
- pir: "pir",
17188
- smoke: "smoke",
17189
- water: "water",
17190
- button: "button",
17191
- generic: "generic",
17192
- gas: "smoke",
17193
- vibration: "generic",
17194
- tamper: "generic",
17195
- presence: "person",
17196
- lock: "generic",
17197
- siren: "generic",
17198
- switch: "generic",
17199
- doorbell: "button"
17200
- };
17201
- function legacyIcon(iconId) {
17202
- return LEGACY_ICON[iconId] ?? "generic";
17203
- }
17204
- /**
17205
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17206
- * The anti-drift guard cross-checks this against the eventful caps declared
17207
- * in `packages/types/src/capabilities/*.cap.ts`.
17208
- */
17209
- var CAP_TO_KIND = {
17210
- contact: "contact",
17211
- motion: "motion-sensor",
17212
- smoke: "smoke",
17213
- flood: "flood",
17214
- gas: "gas",
17215
- "carbon-monoxide": "carbon-monoxide",
17216
- vibration: "vibration",
17217
- tamper: "tamper",
17218
- presence: "presence",
17219
- "enum-sensor": "enum-sensor",
17220
- "event-emitter": "device-event",
17221
- "lock-control": "lock",
17222
- switch: "switch",
17223
- button: "button",
17224
- doorbell: "doorbell"
17225
- };
17226
- function buildDescriptor(capName, kind) {
17227
- const t = EVENT_TAXONOMY[kind];
17228
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17229
- return {
17230
- ...t,
17231
- icon: legacyIcon(t.iconId)
17232
- };
17233
- }
17234
- /**
17235
- * Sensor / control cap name → static event-kind descriptor. A linked device
17236
- * contributes one entry per bound cap present in this map.
17237
- */
17238
- var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17239
- /**
17240
- * Build a full `EventKindDescriptor` for a taxonomy `kind`, stamping the
17241
- * per-device `source`. Returns null when `kind` is not in the taxonomy.
17242
- * This is THE bridge from the serializable taxonomy dictionary to the cap
17243
- * wire shape — every event-kind descriptor the server emits goes through it,
17244
- * so color/iconId/labelKey are never re-declared at a call site.
17245
- */
17246
- function buildEventKindDescriptor(kind, source) {
17247
- const t = EVENT_TAXONOMY[kind];
17248
- if (t === void 0) return null;
17249
- return {
17250
- kind: t.kind,
17251
- labelKey: t.labelKey,
17252
- label: t.label,
17253
- color: t.color,
17254
- iconId: t.iconId,
17255
- icon: legacyIcon(t.iconId),
17256
- category: t.category,
17257
- parentKind: t.parentKind,
17258
- level: t.level,
17259
- source: {
17260
- capName: source.capName,
17261
- deviceId: source.deviceId
17262
- }
17263
- };
17264
- }
17850
+ events: {
17851
+ /**
17852
+ * Enriched frame emitted after refinement — the live-overlay source of
17853
+ * truth (two-plane re-injection). Carries the frame's detections in the
17854
+ * `ObjectDetection` wire shape: first-level roots (with track info +
17855
+ * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
17856
+ * re-projected from per-track detail state, so stream overlays render
17857
+ * boxes + recognized names without querying full Track state.
17858
+ */
17859
+ onFrameTracked: { data: object({
17860
+ deviceId: number(),
17861
+ timestamp: number(),
17862
+ frameWidth: number(),
17863
+ frameHeight: number(),
17864
+ detections: array(OverlayDetectionSchema).readonly()
17865
+ }) },
17866
+ /** Track entered active state (first-seen). */
17867
+ onTrackStarted: { data: object({
17868
+ deviceId: number(),
17869
+ trackId: string(),
17870
+ className: string()
17871
+ }) },
17872
+ /** Track expired (TTL reached after last detection). */
17873
+ onTrackEnded: { data: object({
17874
+ deviceId: number(),
17875
+ trackId: string(),
17876
+ className: string(),
17877
+ durationMs: number()
17878
+ }) },
17879
+ /** Canonical "something happened at device X" event, per-kind. */
17880
+ onDetectionEvent: { data: object({
17881
+ deviceId: number(),
17882
+ kind: EventKindSchema,
17883
+ eventId: string(),
17884
+ timestamp: number()
17885
+ }) }
17886
+ }
17887
+ };
17265
17888
  var CameraPipelineConfigSchema = object({
17266
17889
  engine: PipelineEngineChoiceSchema.optional(),
17267
17890
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17747,6 +18370,106 @@ method(object({
17747
18370
  auth: "admin"
17748
18371
  });
17749
18372
  /**
18373
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
18374
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
18375
+ * caps into per-camera event-kind descriptors.
18376
+ *
18377
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
18378
+ * is NOT duplicated here — every entry is derived from the single
18379
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
18380
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
18381
+ * control cap means adding one line here (and a taxonomy entry); the anti-
18382
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
18383
+ * eventful cap is missing.
18384
+ */
18385
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
18386
+ var LEGACY_ICON = {
18387
+ motion: "motion",
18388
+ audio: "audio",
18389
+ person: "person",
18390
+ vehicle: "vehicle",
18391
+ animal: "animal",
18392
+ package: "package",
18393
+ door: "door",
18394
+ pir: "pir",
18395
+ smoke: "smoke",
18396
+ water: "water",
18397
+ button: "button",
18398
+ generic: "generic",
18399
+ gas: "smoke",
18400
+ vibration: "generic",
18401
+ tamper: "generic",
18402
+ presence: "person",
18403
+ lock: "generic",
18404
+ siren: "generic",
18405
+ switch: "generic",
18406
+ doorbell: "button"
18407
+ };
18408
+ function legacyIcon(iconId) {
18409
+ return LEGACY_ICON[iconId] ?? "generic";
18410
+ }
18411
+ /**
18412
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
18413
+ * The anti-drift guard cross-checks this against the eventful caps declared
18414
+ * in `packages/types/src/capabilities/*.cap.ts`.
18415
+ */
18416
+ var CAP_TO_KIND = {
18417
+ contact: "contact",
18418
+ motion: "motion-sensor",
18419
+ smoke: "smoke",
18420
+ flood: "flood",
18421
+ gas: "gas",
18422
+ "carbon-monoxide": "carbon-monoxide",
18423
+ vibration: "vibration",
18424
+ tamper: "tamper",
18425
+ presence: "presence",
18426
+ "enum-sensor": "enum-sensor",
18427
+ "event-emitter": "device-event",
18428
+ "lock-control": "lock",
18429
+ switch: "switch",
18430
+ button: "button",
18431
+ doorbell: "doorbell"
18432
+ };
18433
+ function buildDescriptor(capName, kind) {
18434
+ const t = EVENT_TAXONOMY[kind];
18435
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
18436
+ return {
18437
+ ...t,
18438
+ icon: legacyIcon(t.iconId)
18439
+ };
18440
+ }
18441
+ /**
18442
+ * Sensor / control cap name → static event-kind descriptor. A linked device
18443
+ * contributes one entry per bound cap present in this map.
18444
+ */
18445
+ var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
18446
+ /**
18447
+ * Build a full `EventKindDescriptor` for a taxonomy `kind`, stamping the
18448
+ * per-device `source`. Returns null when `kind` is not in the taxonomy.
18449
+ * This is THE bridge from the serializable taxonomy dictionary to the cap
18450
+ * wire shape — every event-kind descriptor the server emits goes through it,
18451
+ * so color/iconId/labelKey are never re-declared at a call site.
18452
+ */
18453
+ function buildEventKindDescriptor(kind, source) {
18454
+ const t = EVENT_TAXONOMY[kind];
18455
+ if (t === void 0) return null;
18456
+ return {
18457
+ kind: t.kind,
18458
+ labelKey: t.labelKey,
18459
+ label: t.label,
18460
+ color: t.color,
18461
+ iconId: t.iconId,
18462
+ icon: legacyIcon(t.iconId),
18463
+ category: t.category,
18464
+ parentKind: t.parentKind,
18465
+ level: t.level,
18466
+ source: {
18467
+ capName: source.capName,
18468
+ deviceId: source.deviceId
18469
+ }
18470
+ };
18471
+ }
18472
+ /**
17750
18473
  * server-management — per-NODE singleton capability for a node's ROOT
17751
18474
  * package lifecycle (runtime-updatable node packages).
17752
18475
  *
@@ -19211,7 +19934,28 @@ var FaceInfoSchema = object({
19211
19934
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
19212
19935
  * track produced no key frame (e.g. native/onboard source) — the UI falls
19213
19936
  * back to the inline `base64` face crop. */
19214
- keyFrameMediaKey: string().optional()
19937
+ keyFrameMediaKey: string().optional(),
19938
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19939
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19940
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19941
+ * faces that were never auto-recognized. */
19942
+ bestMatchScore: number().optional(),
19943
+ /** Native-scale face short side (px) at recognition time, when the runner
19944
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19945
+ * legacy rows / runners that reported no native measure. */
19946
+ nativeFaceShortSidePx: number().optional(),
19947
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19948
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19949
+ * but blocked only by the recognition size floor). Mutually exclusive with
19950
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19951
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19952
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19953
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19954
+ suggestedIdentityId: string().optional(),
19955
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19956
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19957
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19958
+ suggestedMatchScore: number().optional()
19215
19959
  });
19216
19960
  var FaceFilterEnum = _enum([
19217
19961
  "unassigned",
@@ -21314,36 +22058,6 @@ Object.freeze({
21314
22058
  addonId: null,
21315
22059
  access: "view"
21316
22060
  },
21317
- "advancedNotifier.deleteRule": {
21318
- capName: "advanced-notifier",
21319
- capScope: "system",
21320
- addonId: null,
21321
- access: "delete"
21322
- },
21323
- "advancedNotifier.getHistory": {
21324
- capName: "advanced-notifier",
21325
- capScope: "system",
21326
- addonId: null,
21327
- access: "view"
21328
- },
21329
- "advancedNotifier.getRules": {
21330
- capName: "advanced-notifier",
21331
- capScope: "system",
21332
- addonId: null,
21333
- access: "view"
21334
- },
21335
- "advancedNotifier.testRule": {
21336
- capName: "advanced-notifier",
21337
- capScope: "system",
21338
- addonId: null,
21339
- access: "create"
21340
- },
21341
- "advancedNotifier.upsertRule": {
21342
- capName: "advanced-notifier",
21343
- capScope: "system",
21344
- addonId: null,
21345
- access: "create"
21346
- },
21347
22061
  "alarmPanel.arm": {
21348
22062
  capName: "alarm-panel",
21349
22063
  capScope: "device",
@@ -23648,6 +24362,60 @@ Object.freeze({
23648
24362
  addonId: null,
23649
24363
  access: "create"
23650
24364
  },
24365
+ "notificationRules.createRule": {
24366
+ capName: "notification-rules",
24367
+ capScope: "system",
24368
+ addonId: null,
24369
+ access: "create"
24370
+ },
24371
+ "notificationRules.deleteRule": {
24372
+ capName: "notification-rules",
24373
+ capScope: "system",
24374
+ addonId: null,
24375
+ access: "delete"
24376
+ },
24377
+ "notificationRules.getConditionCatalog": {
24378
+ capName: "notification-rules",
24379
+ capScope: "system",
24380
+ addonId: null,
24381
+ access: "view"
24382
+ },
24383
+ "notificationRules.getHistory": {
24384
+ capName: "notification-rules",
24385
+ capScope: "system",
24386
+ addonId: null,
24387
+ access: "view"
24388
+ },
24389
+ "notificationRules.getRule": {
24390
+ capName: "notification-rules",
24391
+ capScope: "system",
24392
+ addonId: null,
24393
+ access: "view"
24394
+ },
24395
+ "notificationRules.listRules": {
24396
+ capName: "notification-rules",
24397
+ capScope: "system",
24398
+ addonId: null,
24399
+ access: "view"
24400
+ },
24401
+ "notificationRules.setRuleEnabled": {
24402
+ capName: "notification-rules",
24403
+ capScope: "system",
24404
+ addonId: null,
24405
+ access: "create"
24406
+ },
24407
+ "notificationRules.testRule": {
24408
+ capName: "notification-rules",
24409
+ capScope: "system",
24410
+ addonId: null,
24411
+ access: "create"
24412
+ },
24413
+ "notificationRules.updateRule": {
24414
+ capName: "notification-rules",
24415
+ capScope: "system",
24416
+ addonId: null,
24417
+ access: "create"
24418
+ },
23651
24419
  "notifier.cancel": {
23652
24420
  capName: "notifier",
23653
24421
  capScope: "device",
@@ -25861,183 +26629,4 @@ Object.freeze({
25861
26629
  "smtp-provider": "email"
25862
26630
  });
25863
26631
  //#endregion
25864
- Object.defineProperty(exports, "BaseAddon", {
25865
- enumerable: true,
25866
- get: function() {
25867
- return BaseAddon;
25868
- }
25869
- });
25870
- Object.defineProperty(exports, "DEFAULT_EVENT_COLOR", {
25871
- enumerable: true,
25872
- get: function() {
25873
- return DEFAULT_EVENT_COLOR;
25874
- }
25875
- });
25876
- Object.defineProperty(exports, "DeviceType", {
25877
- enumerable: true,
25878
- get: function() {
25879
- return DeviceType;
25880
- }
25881
- });
25882
- Object.defineProperty(exports, "EVENT_KIND_BY_CAP", {
25883
- enumerable: true,
25884
- get: function() {
25885
- return EVENT_KIND_BY_CAP;
25886
- }
25887
- });
25888
- Object.defineProperty(exports, "EVENT_PAD_MS", {
25889
- enumerable: true,
25890
- get: function() {
25891
- return EVENT_PAD_MS;
25892
- }
25893
- });
25894
- Object.defineProperty(exports, "EventCategory", {
25895
- enumerable: true,
25896
- get: function() {
25897
- return EventCategory;
25898
- }
25899
- });
25900
- Object.defineProperty(exports, "MACRO_LABELS", {
25901
- enumerable: true,
25902
- get: function() {
25903
- return MACRO_LABELS;
25904
- }
25905
- });
25906
- Object.defineProperty(exports, "OpsLogEntrySchema", {
25907
- enumerable: true,
25908
- get: function() {
25909
- return OpsLogEntrySchema;
25910
- }
25911
- });
25912
- Object.defineProperty(exports, "__toESM", {
25913
- enumerable: true,
25914
- get: function() {
25915
- return __toESM;
25916
- }
25917
- });
25918
- Object.defineProperty(exports, "addonWidgetsSourceCapability", {
25919
- enumerable: true,
25920
- get: function() {
25921
- return addonWidgetsSourceCapability;
25922
- }
25923
- });
25924
- Object.defineProperty(exports, "array", {
25925
- enumerable: true,
25926
- get: function() {
25927
- return array;
25928
- }
25929
- });
25930
- Object.defineProperty(exports, "audioMetricsCapability", {
25931
- enumerable: true,
25932
- get: function() {
25933
- return audioMetricsCapability;
25934
- }
25935
- });
25936
- Object.defineProperty(exports, "boolean", {
25937
- enumerable: true,
25938
- get: function() {
25939
- return boolean;
25940
- }
25941
- });
25942
- Object.defineProperty(exports, "buildEventKindDescriptor", {
25943
- enumerable: true,
25944
- get: function() {
25945
- return buildEventKindDescriptor;
25946
- }
25947
- });
25948
- Object.defineProperty(exports, "cosineSimilarity", {
25949
- enumerable: true,
25950
- get: function() {
25951
- return cosineSimilarity;
25952
- }
25953
- });
25954
- Object.defineProperty(exports, "createEvent", {
25955
- enumerable: true,
25956
- get: function() {
25957
- return createEvent;
25958
- }
25959
- });
25960
- Object.defineProperty(exports, "embeddingEncoderCapability", {
25961
- enumerable: true,
25962
- get: function() {
25963
- return embeddingEncoderCapability;
25964
- }
25965
- });
25966
- Object.defineProperty(exports, "errMsg", {
25967
- enumerable: true,
25968
- get: function() {
25969
- return errMsg;
25970
- }
25971
- });
25972
- Object.defineProperty(exports, "faceGalleryCapability", {
25973
- enumerable: true,
25974
- get: function() {
25975
- return faceGalleryCapability;
25976
- }
25977
- });
25978
- Object.defineProperty(exports, "hfModelUrl", {
25979
- enumerable: true,
25980
- get: function() {
25981
- return hfModelUrl;
25982
- }
25983
- });
25984
- Object.defineProperty(exports, "hydrateSchema", {
25985
- enumerable: true,
25986
- get: function() {
25987
- return hydrateSchema;
25988
- }
25989
- });
25990
- Object.defineProperty(exports, "nodePin", {
25991
- enumerable: true,
25992
- get: function() {
25993
- return nodePin;
25994
- }
25995
- });
25996
- Object.defineProperty(exports, "number", {
25997
- enumerable: true,
25998
- get: function() {
25999
- return number;
26000
- }
26001
- });
26002
- Object.defineProperty(exports, "object", {
26003
- enumerable: true,
26004
- get: function() {
26005
- return object;
26006
- }
26007
- });
26008
- Object.defineProperty(exports, "pipelineAnalyticsCapability", {
26009
- enumerable: true,
26010
- get: function() {
26011
- return pipelineAnalyticsCapability;
26012
- }
26013
- });
26014
- Object.defineProperty(exports, "plateGalleryCapability", {
26015
- enumerable: true,
26016
- get: function() {
26017
- return plateGalleryCapability;
26018
- }
26019
- });
26020
- Object.defineProperty(exports, "string", {
26021
- enumerable: true,
26022
- get: function() {
26023
- return string;
26024
- }
26025
- });
26026
- Object.defineProperty(exports, "subKindsOf", {
26027
- enumerable: true,
26028
- get: function() {
26029
- return subKindsOf;
26030
- }
26031
- });
26032
- Object.defineProperty(exports, "videoclipsCapability", {
26033
- enumerable: true,
26034
- get: function() {
26035
- return videoclipsCapability;
26036
- }
26037
- });
26038
- Object.defineProperty(exports, "zoneAnalyticsCapability", {
26039
- enumerable: true,
26040
- get: function() {
26041
- return zoneAnalyticsCapability;
26042
- }
26043
- });
26632
+ export { BaseAddon as A, EventCategory as B, notificationRulesCapability as C, videoclipsCapability as D, subKindsOf as E, boolean as F, literal as I, number as L, createEvent as M, hydrateSchema as N, zoneAnalyticsCapability as O, array as P, object as R, nodePin as S, plateGalleryCapability as T, customAction as _, NC_CONDITION_CATALOG as a, faceGalleryCapability as b, NcRuleInputSchema as c, NcTaxonomySchema as d, OpsLogEntrySchema as f, cosineSimilarity as g, buildEventKindDescriptor as h, MACRO_LABELS as i, DeviceType as j, errMsg as k, NcRulePatchSchema as l, audioMetricsCapability as m, EVENT_KIND_BY_CAP as n, NC_TAXONOMY as o, addonWidgetsSourceCapability as p, EVENT_PAD_MS as r, NcConditionDescriptorSchema as s, DEFAULT_EVENT_COLOR as t, NcRuleSchema as u, defineCustomActions as v, pipelineAnalyticsCapability as w, hfModelUrl as x, embeddingEncoderCapability as y, string as z };